diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54d75515f0c73ccbce5b62c4cd6c9ea8c0032341 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36032f77c542f9f1f0a3fe8dc3589fd9fd98079e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_client.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..def6cd74a7a6f772d3c0700c88e6d5fe37970342 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_common.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_templating.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_templating.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df8dde2dd51daac3c175d48a8ba2350c2c72ce1a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_templating.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_types.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_types.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a381ace3b653073b9463d379c540fabb0b18e62d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/__pycache__/_types.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..833eb3674afd44fbb3cb893c0623a19459d3ae01 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80a809f26b14371146189d818aa88c8ec8c60e59 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__init__.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ece102c4d7a7d1a6c5ee46e066a0a3b867e342e0 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__init__.py @@ -0,0 +1,115 @@ +# This file is auto-generated by `utils/generate_inference_types.py`. +# Do not modify it manually. +# +# ruff: noqa: F401 + +from .audio_classification import ( + AudioClassificationInput, + AudioClassificationOutputElement, + AudioClassificationParameters, +) +from .audio_to_audio import AudioToAudioInput, AudioToAudioOutputElement +from .automatic_speech_recognition import ( + AutomaticSpeechRecognitionGenerationParameters, + AutomaticSpeechRecognitionInput, + AutomaticSpeechRecognitionOutput, + AutomaticSpeechRecognitionOutputChunk, + AutomaticSpeechRecognitionParameters, +) +from .base import BaseInferenceType +from .chat_completion import ( + ChatCompletionInput, + ChatCompletionInputMessage, + ChatCompletionOutput, + ChatCompletionOutputChoice, + ChatCompletionOutputChoiceMessage, + ChatCompletionStreamOutput, + ChatCompletionStreamOutputChoice, + ChatCompletionStreamOutputDelta, +) +from .depth_estimation import DepthEstimationInput, DepthEstimationOutput +from .document_question_answering import ( + DocumentQuestionAnsweringInput, + DocumentQuestionAnsweringInputData, + DocumentQuestionAnsweringOutputElement, + DocumentQuestionAnsweringParameters, +) +from .feature_extraction import FeatureExtractionInput +from .fill_mask import FillMaskInput, FillMaskOutputElement, FillMaskParameters +from .image_classification import ( + ImageClassificationInput, + ImageClassificationOutputElement, + ImageClassificationParameters, +) +from .image_segmentation import ImageSegmentationInput, ImageSegmentationOutputElement, ImageSegmentationParameters +from .image_to_image import ImageToImageInput, ImageToImageOutput, ImageToImageParameters, ImageToImageTargetSize +from .image_to_text import ImageToTextGenerationParameters, ImageToTextInput, ImageToTextOutput, ImageToTextParameters +from .object_detection import ( + ObjectDetectionBoundingBox, + ObjectDetectionInput, + ObjectDetectionOutputElement, + ObjectDetectionParameters, +) +from .question_answering import ( + QuestionAnsweringInput, + QuestionAnsweringInputData, + QuestionAnsweringOutputElement, + QuestionAnsweringParameters, +) +from .sentence_similarity import SentenceSimilarityInput, SentenceSimilarityInputData +from .summarization import SummarizationGenerationParameters, SummarizationInput, SummarizationOutput +from .table_question_answering import ( + TableQuestionAnsweringInput, + TableQuestionAnsweringInputData, + TableQuestionAnsweringOutputElement, +) +from .text2text_generation import Text2TextGenerationInput, Text2TextGenerationOutput, Text2TextGenerationParameters +from .text_classification import TextClassificationInput, TextClassificationOutputElement, TextClassificationParameters +from .text_generation import ( + TextGenerationInput, + TextGenerationOutput, + TextGenerationOutputDetails, + TextGenerationOutputSequenceDetails, + TextGenerationOutputToken, + TextGenerationParameters, + TextGenerationPrefillToken, + TextGenerationStreamDetails, + TextGenerationStreamOutput, +) +from .text_to_audio import TextToAudioGenerationParameters, TextToAudioInput, TextToAudioOutput, TextToAudioParameters +from .text_to_image import TextToImageInput, TextToImageOutput, TextToImageParameters, TextToImageTargetSize +from .token_classification import ( + TokenClassificationInput, + TokenClassificationOutputElement, + TokenClassificationParameters, +) +from .translation import TranslationGenerationParameters, TranslationInput, TranslationOutput +from .video_classification import ( + VideoClassificationInput, + VideoClassificationOutputElement, + VideoClassificationParameters, +) +from .visual_question_answering import ( + VisualQuestionAnsweringInput, + VisualQuestionAnsweringInputData, + VisualQuestionAnsweringOutputElement, + VisualQuestionAnsweringParameters, +) +from .zero_shot_classification import ( + ZeroShotClassificationInput, + ZeroShotClassificationInputData, + ZeroShotClassificationOutputElement, + ZeroShotClassificationParameters, +) +from .zero_shot_image_classification import ( + ZeroShotImageClassificationInput, + ZeroShotImageClassificationInputData, + ZeroShotImageClassificationOutputElement, + ZeroShotImageClassificationParameters, +) +from .zero_shot_object_detection import ( + ZeroShotObjectDetectionBoundingBox, + ZeroShotObjectDetectionInput, + ZeroShotObjectDetectionInputData, + ZeroShotObjectDetectionOutputElement, +) diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/__init__.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd92a6c2468a08e05b58a580858b72d969184345 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/__init__.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/audio_classification.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/audio_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b141b3e91c51aa2e9b1ab9892896723e447b31ed Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/audio_classification.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/audio_to_audio.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/audio_to_audio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e10cad156cb9802621cb4dfe217e273a12558951 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/audio_to_audio.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/automatic_speech_recognition.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/automatic_speech_recognition.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5beef3a3115c9c801565253953cf75d95bc6ec36 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/automatic_speech_recognition.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/base.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e66cb098461ba621c543b4dcbaa17bde94c2aa1a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/base.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a77386f83c99daa77efab38e7a3bfc1ebe1f01a Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/depth_estimation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/depth_estimation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4e0809df1add2aac4a57e884176db26deb51480 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/depth_estimation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e566514ed2c50b71b7e30977c86f005ebaf55146 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/feature_extraction.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/feature_extraction.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..97e87a27dce8e03a8300633023879c96be04f80c Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/feature_extraction.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/fill_mask.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/fill_mask.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..057e05b0312bae9a6960573046be0dbe4b4d080d Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/fill_mask.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_classification.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c9e1716bb7ea9b26a10029bda78d568209b5ef6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_classification.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_segmentation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_segmentation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd29ef30c2e7048599c4d83024370a526bd4b163 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_segmentation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_to_image.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_to_image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..340225041c97b16571e65b245531b50a949e7641 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_to_image.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_to_text.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_to_text.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78b3b49a71b0e9d0929df81789837b8424d6b981 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/image_to_text.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/object_detection.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/object_detection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d377e83d94fcca3a9a3508443e98698bab33e801 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/object_detection.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/question_answering.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/question_answering.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a347240310a70a587ec5c2f7f3ae355af3ee0a2e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/question_answering.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/sentence_similarity.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/sentence_similarity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d795889835794de7ad83f6311b7003b54d733c3 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/sentence_similarity.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/summarization.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/summarization.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34495551fb117b1e7ff10f560538bb10cf366d30 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/summarization.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/table_question_answering.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/table_question_answering.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2edf8214b60c4204b793d5dec35256baf04af12 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/table_question_answering.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..951f3b7365cd8ff6a543bc0347329349303c8a4b Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_classification.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fb661d29dac0f20f3c10f83b1079c6f0ccd6eb5 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_classification.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_generation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_generation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1976bd80ebc34fbdf1a19cf19bb01639b6bef5f6 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_generation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_to_audio.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_to_audio.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c3a28caf1febc04ed6146800c2be5b2ed872e46 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_to_audio.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_to_image.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_to_image.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb85e4cb8ba9787f6a0be0dd83e540bb4323ae26 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/text_to_image.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/token_classification.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/token_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b414140edf9737735474b8163879ed46d61e9af Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/token_classification.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/translation.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/translation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d19e03abb7d687464978ce190cf4dd2dee86dc1 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/translation.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/video_classification.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/video_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e58083ffaaca09b6e22e7cd3babf34b890ed1b8 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/video_classification.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/visual_question_answering.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/visual_question_answering.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..240d93fd603d44ea366889fdab847e84ed4e546f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/visual_question_answering.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_classification.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..863e925126c8b6dba32f574d084ef8da746fc8e8 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_classification.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_image_classification.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_image_classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7242ff2387435c4b9ec9d862cfc5034453574aa0 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_image_classification.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_object_detection.cpython-310.pyc b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_object_detection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..556c7ed057c1c81bf06ead78a472d74e2c28e0cd Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__pycache__/zero_shot_object_detection.cpython-310.pyc differ diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/audio_to_audio.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/audio_to_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..4f473ed106c7d168784ae8e96db18f46237d065e --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/audio_to_audio.py @@ -0,0 +1,31 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any + +from .base import BaseInferenceType + + +@dataclass +class AudioToAudioInput(BaseInferenceType): + """Inputs for Audio to Audio inference""" + + inputs: Any + """The input audio data""" + + +@dataclass +class AudioToAudioOutputElement(BaseInferenceType): + """Outputs of inference for the Audio To Audio task + A generated audio file with its label. + """ + + blob: Any + """The generated audio file.""" + content_type: str + """The content type of audio file.""" + label: str + """The label of the audio file.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/base.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/base.py new file mode 100644 index 0000000000000000000000000000000000000000..8783484d2d466a74c1c634508c39a7e9cb2851a3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/base.py @@ -0,0 +1,149 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains a base class for all inference types.""" + +import inspect +import json +import warnings +from dataclasses import asdict, dataclass +from typing import Any, Dict, List, Type, TypeVar, Union, get_args + + +T = TypeVar("T", bound="BaseInferenceType") + + +@dataclass +class BaseInferenceType(dict): + """Base class for all inference types. + + Object is a dataclass and a dict for backward compatibility but plan is to remove the dict part in the future. + + Handle parsing from dict, list and json strings in a permissive way to ensure future-compatibility (e.g. all fields + are made optional, and non-expected fields are added as dict attributes). + """ + + @classmethod + def parse_obj_as_list(cls: Type[T], data: Union[bytes, str, List, Dict]) -> List[T]: + """Alias to parse server response and return a single instance. + + See `parse_obj` for more details. + """ + output = cls.parse_obj(data) + if not isinstance(output, list): + raise ValueError(f"Invalid input data for {cls}. Expected a list, but got {type(output)}.") + return output + + @classmethod + def parse_obj_as_instance(cls: Type[T], data: Union[bytes, str, List, Dict]) -> T: + """Alias to parse server response and return a single instance. + + See `parse_obj` for more details. + """ + output = cls.parse_obj(data) + if isinstance(output, list): + raise ValueError(f"Invalid input data for {cls}. Expected a single instance, but got a list.") + return output + + @classmethod + def parse_obj(cls: Type[T], data: Union[bytes, str, List, Dict]) -> Union[List[T], T]: + """Parse server response as a dataclass or list of dataclasses. + + To enable future-compatibility, we want to handle cases where the server return more fields than expected. + In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are + added as dict attributes. + """ + # Parse server response (from bytes) + if isinstance(data, bytes): + data = data.decode() + if isinstance(data, str): + data = json.loads(data) + + # If a list, parse each item individually + if isinstance(data, List): + return [cls.parse_obj(d) for d in data] # type: ignore [misc] + + # At this point, we expect a dict + if not isinstance(data, dict): + raise ValueError(f"Invalid data type: {type(data)}") + + init_values = {} + other_values = {} + for key, value in data.items(): + key = normalize_key(key) + if key in cls.__dataclass_fields__ and cls.__dataclass_fields__[key].init: + if isinstance(value, dict) or isinstance(value, list): + field_type = cls.__dataclass_fields__[key].type + + # if `field_type` is a `BaseInferenceType`, parse it + if inspect.isclass(field_type) and issubclass(field_type, BaseInferenceType): + value = field_type.parse_obj(value) + + # otherwise, recursively parse nested dataclasses (if possible) + # `get_args` returns handle Union and Optional for us + else: + expected_types = get_args(field_type) + for expected_type in expected_types: + if getattr(expected_type, "_name", None) == "List": + expected_type = get_args(expected_type)[ + 0 + ] # assume same type for all items in the list + if inspect.isclass(expected_type) and issubclass(expected_type, BaseInferenceType): + value = expected_type.parse_obj(value) + break + init_values[key] = value + else: + other_values[key] = value + + # Make all missing fields default to None + # => ensure that dataclass initialization will never fail even if the server does not return all fields. + for key in cls.__dataclass_fields__: + if key not in init_values: + init_values[key] = None + + # Initialize dataclass with expected values + item = cls(**init_values) + + # Add remaining fields as dict attributes + item.update(other_values) + return item + + def __post_init__(self): + self.update(asdict(self)) + + def __setitem__(self, __key: Any, __value: Any) -> None: + # Hacky way to keep dataclass values in sync when dict is updated + super().__setitem__(__key, __value) + if __key in self.__dataclass_fields__ and getattr(self, __key, None) != __value: + self.__setattr__(__key, __value) + return + + def __setattr__(self, __name: str, __value: Any) -> None: + # Hacky way to keep dict values is sync when dataclass is updated + super().__setattr__(__name, __value) + if self.get(__name) != __value: + self[__name] = __value + return + + def __getitem__(self, __key: Any) -> Any: + warnings.warn( + f"Accessing '{self.__class__.__name__}' values through dict is deprecated and " + "will be removed from version '0.25'. Use dataclass attributes instead.", + FutureWarning, + ) + return super().__getitem__(__key) + + +def normalize_key(key: str) -> str: + # e.g "content-type" -> "content_type", "Accept" -> "accept" + return key.replace("-", "_").replace(" ", "_").lower() diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/depth_estimation.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/depth_estimation.py new file mode 100644 index 0000000000000000000000000000000000000000..fbaa5feeadff9721ba543cb77121b98c17e3ee8c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/depth_estimation.py @@ -0,0 +1,29 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from .base import BaseInferenceType + + +@dataclass +class DepthEstimationInput(BaseInferenceType): + """Inputs for Depth Estimation inference""" + + inputs: Any + """The input image data""" + parameters: Optional[Dict[str, Any]] = None + """Additional inference parameters""" + + +@dataclass +class DepthEstimationOutput(BaseInferenceType): + """Outputs of inference for the Depth Estimation task""" + + depth: Any + """The predicted depth as an image""" + predicted_depth: Any + """The predicted depth as a tensor""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/document_question_answering.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/document_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..c68be4bde00a98fbce46a2ef6a93bb549d4d920b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/document_question_answering.py @@ -0,0 +1,85 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, List, Optional, Union + +from .base import BaseInferenceType + + +@dataclass +class DocumentQuestionAnsweringInputData(BaseInferenceType): + """One (document, question) pair to answer""" + + image: Any + """The image on which the question is asked""" + question: str + """A question to ask of the document""" + + +@dataclass +class DocumentQuestionAnsweringParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Document Question Answering + """ + + doc_stride: Optional[int] = None + """If the words in the document are too long to fit with the question for the model, it will + be split in several chunks with some overlap. This argument controls the size of that + overlap. + """ + handle_impossible_answer: Optional[bool] = None + """Whether to accept impossible as an answer""" + lang: Optional[str] = None + """Language to use while running OCR. Defaults to english.""" + max_answer_len: Optional[int] = None + """The maximum length of predicted answers (e.g., only answers with a shorter length are + considered). + """ + max_question_len: Optional[int] = None + """The maximum length of the question after tokenization. It will be truncated if needed.""" + max_seq_len: Optional[int] = None + """The maximum length of the total sentence (context + question) in tokens of each chunk + passed to the model. The context will be split in several chunks (using doc_stride as + overlap) if needed. + """ + top_k: Optional[int] = None + """The number of answers to return (will be chosen by order of likelihood). Can return less + than top_k answers if there are not enough options available within the context. + """ + word_boxes: Optional[List[Union[List[float], str]]] = None + """A list of words and bounding boxes (normalized 0->1000). If provided, the inference will + skip the OCR step and use the provided bounding boxes instead. + """ + + +@dataclass +class DocumentQuestionAnsweringInput(BaseInferenceType): + """Inputs for Document Question Answering inference""" + + inputs: DocumentQuestionAnsweringInputData + """One (document, question) pair to answer""" + parameters: Optional[DocumentQuestionAnsweringParameters] = None + """Additional inference parameters""" + + +@dataclass +class DocumentQuestionAnsweringOutputElement(BaseInferenceType): + """Outputs of inference for the Document Question Answering task""" + + answer: str + """The answer to the question.""" + end: int + """The end word index of the answer (in the OCR’d version of the input or provided word + boxes). + """ + score: float + """The probability associated to the answer.""" + start: int + """The start word index of the answer (in the OCR’d version of the input or provided word + boxes). + """ + words: List[int] + """The index of each word/box pair that is in the answer""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/feature_extraction.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..df563e671a68926df1d96898879ae775f0d20a6c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/feature_extraction.py @@ -0,0 +1,19 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from .base import BaseInferenceType + + +@dataclass +class FeatureExtractionInput(BaseInferenceType): + """Inputs for Text Embedding inference""" + + inputs: str + """The text to get the embeddings of""" + parameters: Optional[Dict[str, Any]] = None + """Additional inference parameters""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_classification.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..fd52db005a0be62e7f063c0a16569a1fc2b273da --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_classification.py @@ -0,0 +1,43 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Literal, Optional + +from .base import BaseInferenceType + + +ClassificationOutputTransform = Literal["sigmoid", "softmax", "none"] + + +@dataclass +class ImageClassificationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Image Classification + """ + + function_to_apply: Optional["ClassificationOutputTransform"] = None + top_k: Optional[int] = None + """When specified, limits the output to the top K most probable classes.""" + + +@dataclass +class ImageClassificationInput(BaseInferenceType): + """Inputs for Image Classification inference""" + + inputs: Any + """The input image data""" + parameters: Optional[ImageClassificationParameters] = None + """Additional inference parameters""" + + +@dataclass +class ImageClassificationOutputElement(BaseInferenceType): + """Outputs of inference for the Image Classification task""" + + label: str + """The predicted class label.""" + score: float + """The corresponding probability.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_segmentation.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..67dd7c28b3cddd21d495ada70b7689a098accfd6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_segmentation.py @@ -0,0 +1,52 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Literal, Optional + +from .base import BaseInferenceType + + +ImageSegmentationSubtask = Literal["instance", "panoptic", "semantic"] + + +@dataclass +class ImageSegmentationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Image Segmentation + """ + + mask_threshold: Optional[float] = None + """Threshold to use when turning the predicted masks into binary values.""" + overlap_mask_area_threshold: Optional[float] = None + """Mask overlap threshold to eliminate small, disconnected segments.""" + subtask: Optional["ImageSegmentationSubtask"] = None + """Segmentation task to be performed, depending on model capabilities.""" + threshold: Optional[float] = None + """Probability threshold to filter out predicted masks.""" + + +@dataclass +class ImageSegmentationInput(BaseInferenceType): + """Inputs for Image Segmentation inference""" + + inputs: Any + """The input image data""" + parameters: Optional[ImageSegmentationParameters] = None + """Additional inference parameters""" + + +@dataclass +class ImageSegmentationOutputElement(BaseInferenceType): + """Outputs of inference for the Image Segmentation task + A predicted mask / segment + """ + + label: str + """The label of the predicted segment""" + mask: Any + """The corresponding mask as a black-and-white image""" + score: Optional[float] = None + """The score or confidence degreee the model has""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_image.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_image.py new file mode 100644 index 0000000000000000000000000000000000000000..8c208ede6f7f2fb73b5dd059fe71bc8d2c4ca140 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_image.py @@ -0,0 +1,55 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, List, Optional + +from .base import BaseInferenceType + + +@dataclass +class ImageToImageTargetSize(BaseInferenceType): + """The size in pixel of the output image""" + + height: int + width: int + + +@dataclass +class ImageToImageParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Image To Image + """ + + guidance_scale: Optional[float] = None + """For diffusion models. A higher guidance scale value encourages the model to generate + images closely linked to the text prompt at the expense of lower image quality. + """ + negative_prompt: Optional[List[str]] = None + """One or several prompt to guide what NOT to include in image generation.""" + num_inference_steps: Optional[int] = None + """For diffusion models. The number of denoising steps. More denoising steps usually lead to + a higher quality image at the expense of slower inference. + """ + target_size: Optional[ImageToImageTargetSize] = None + """The size in pixel of the output image""" + + +@dataclass +class ImageToImageInput(BaseInferenceType): + """Inputs for Image To Image inference""" + + inputs: Any + """The input image data""" + parameters: Optional[ImageToImageParameters] = None + """Additional inference parameters""" + + +@dataclass +class ImageToImageOutput(BaseInferenceType): + """Outputs of inference for the Image To Image task""" + + image: Any + """The output image""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_text.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_text.py new file mode 100644 index 0000000000000000000000000000000000000000..0ebb9a9bc667bdb0d2afd7bb8e482fc18f6634d7 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_text.py @@ -0,0 +1,105 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Literal, Optional, Union + +from .base import BaseInferenceType + + +EarlyStoppingEnum = Literal["never"] + + +@dataclass +class ImageToTextGenerationParameters(BaseInferenceType): + """Parametrization of the text generation process + Ad-hoc parametrization of the text generation process + """ + + do_sample: Optional[bool] = None + """Whether to use sampling instead of greedy decoding when generating new tokens.""" + early_stopping: Optional[Union[bool, "EarlyStoppingEnum"]] = None + """Controls the stopping condition for beam-based methods.""" + epsilon_cutoff: Optional[float] = None + """If set to float strictly between 0 and 1, only tokens with a conditional probability + greater than epsilon_cutoff will be sampled. In the paper, suggested values range from + 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language + Model Desmoothing](https://hf.co/papers/2210.15191) for more details. + """ + eta_cutoff: Optional[float] = None + """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to + float strictly between 0 and 1, a token is only considered if it is greater than either + eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter + term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In + the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. + See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) + for more details. + """ + max_length: Optional[int] = None + """The maximum length (in tokens) of the generated text, including the input.""" + max_new_tokens: Optional[int] = None + """The maximum number of tokens to generate. Takes precedence over maxLength.""" + min_length: Optional[int] = None + """The minimum length (in tokens) of the generated text, including the input.""" + min_new_tokens: Optional[int] = None + """The minimum number of tokens to generate. Takes precedence over maxLength.""" + num_beam_groups: Optional[int] = None + """Number of groups to divide num_beams into in order to ensure diversity among different + groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details. + """ + num_beams: Optional[int] = None + """Number of beams to use for beam search.""" + penalty_alpha: Optional[float] = None + """The value balances the model confidence and the degeneration penalty in contrastive + search decoding. + """ + temperature: Optional[float] = None + """The value used to modulate the next token probabilities.""" + top_k: Optional[int] = None + """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" + top_p: Optional[float] = None + """If set to float < 1, only the smallest set of most probable tokens with probabilities + that add up to top_p or higher are kept for generation. + """ + typical_p: Optional[float] = None + """Local typicality measures how similar the conditional probability of predicting a target + token next is to the expected conditional probability of predicting a random token next, + given the partial text already generated. If set to float < 1, the smallest set of the + most locally typical tokens with probabilities that add up to typical_p or higher are + kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details. + """ + use_cache: Optional[bool] = None + """Whether the model should use the past last key/values attentions to speed up decoding""" + + +@dataclass +class ImageToTextParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Image To Text + """ + + generate: Optional[ImageToTextGenerationParameters] = None + """Parametrization of the text generation process""" + max_new_tokens: Optional[int] = None + """The amount of maximum tokens to generate.""" + + +@dataclass +class ImageToTextInput(BaseInferenceType): + """Inputs for Image To Text inference""" + + inputs: Any + """The input image data""" + parameters: Optional[ImageToTextParameters] = None + """Additional inference parameters""" + + +@dataclass +class ImageToTextOutput(BaseInferenceType): + """Outputs of inference for the Image To Text task""" + + generated_text: Any + image_to_text_output_generated_text: Optional[str] = None + """The generated text.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/object_detection.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/object_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..42b03a841b793fd4cb301bf51695bd35054a6af2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/object_detection.py @@ -0,0 +1,55 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Optional + +from .base import BaseInferenceType + + +@dataclass +class ObjectDetectionParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Object Detection + """ + + threshold: Optional[float] = None + """The probability necessary to make a prediction.""" + + +@dataclass +class ObjectDetectionInput(BaseInferenceType): + """Inputs for Object Detection inference""" + + inputs: Any + """The input image data""" + parameters: Optional[ObjectDetectionParameters] = None + """Additional inference parameters""" + + +@dataclass +class ObjectDetectionBoundingBox(BaseInferenceType): + """The predicted bounding box. Coordinates are relative to the top left corner of the input + image. + """ + + xmax: int + xmin: int + ymax: int + ymin: int + + +@dataclass +class ObjectDetectionOutputElement(BaseInferenceType): + """Outputs of inference for the Object Detection task""" + + box: ObjectDetectionBoundingBox + """The predicted bounding box. Coordinates are relative to the top left corner of the input + image. + """ + label: str + """The predicted label for the bounding box""" + score: float + """The associated score / probability""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/question_answering.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..3810fc594af5cf0712cb0cb0db077383220b175a --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/question_answering.py @@ -0,0 +1,77 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Optional + +from .base import BaseInferenceType + + +@dataclass +class QuestionAnsweringInputData(BaseInferenceType): + """One (context, question) pair to answer""" + + context: str + """The context to be used for answering the question""" + question: str + """The question to be answered""" + + +@dataclass +class QuestionAnsweringParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Question Answering + """ + + align_to_words: Optional[bool] = None + """Attempts to align the answer to real words. Improves quality on space separated + languages. Might hurt on non-space-separated languages (like Japanese or Chinese) + """ + doc_stride: Optional[int] = None + """If the context is too long to fit with the question for the model, it will be split in + several chunks with some overlap. This argument controls the size of that overlap. + """ + handle_impossible_answer: Optional[bool] = None + """Whether to accept impossible as an answer.""" + max_answer_len: Optional[int] = None + """The maximum length of predicted answers (e.g., only answers with a shorter length are + considered). + """ + max_question_len: Optional[int] = None + """The maximum length of the question after tokenization. It will be truncated if needed.""" + max_seq_len: Optional[int] = None + """The maximum length of the total sentence (context + question) in tokens of each chunk + passed to the model. The context will be split in several chunks (using docStride as + overlap) if needed. + """ + top_k: Optional[int] = None + """The number of answers to return (will be chosen by order of likelihood). Note that we + return less than topk answers if there are not enough options available within the + context. + """ + + +@dataclass +class QuestionAnsweringInput(BaseInferenceType): + """Inputs for Question Answering inference""" + + inputs: QuestionAnsweringInputData + """One (context, question) pair to answer""" + parameters: Optional[QuestionAnsweringParameters] = None + """Additional inference parameters""" + + +@dataclass +class QuestionAnsweringOutputElement(BaseInferenceType): + """Outputs of inference for the Question Answering task""" + + answer: str + """The answer to the question.""" + end: int + """The character position in the input where the answer ends.""" + score: float + """The probability associated to the answer.""" + start: int + """The character position in the input where the answer begins.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/summarization.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/summarization.py new file mode 100644 index 0000000000000000000000000000000000000000..a6a00e53264bd9a53a24d2ee7b12f428c068a117 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/summarization.py @@ -0,0 +1,46 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Dict, Literal, Optional + +from .base import BaseInferenceType + + +SummarizationGenerationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"] + + +@dataclass +class SummarizationGenerationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Text2text Generation + """ + + clean_up_tokenization_spaces: Optional[bool] = None + """Whether to clean up the potential extra spaces in the text output.""" + generate_parameters: Optional[Dict[str, Any]] = None + """Additional parametrization of the text generation algorithm""" + truncation: Optional["SummarizationGenerationTruncationStrategy"] = None + """The truncation strategy to use""" + + +@dataclass +class SummarizationInput(BaseInferenceType): + """Inputs for Summarization inference + Inputs for Text2text Generation inference + """ + + inputs: str + """The input text data""" + parameters: Optional[SummarizationGenerationParameters] = None + """Additional inference parameters""" + + +@dataclass +class SummarizationOutput(BaseInferenceType): + """Outputs of inference for the Summarization task""" + + summary_text: str + """The summarized text.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_classification.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..bf61a4eebcf367b4ab15e8970bfac8e1d8f8458d --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_classification.py @@ -0,0 +1,43 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Literal, Optional + +from .base import BaseInferenceType + + +ClassificationOutputTransform = Literal["sigmoid", "softmax", "none"] + + +@dataclass +class TextClassificationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Text Classification + """ + + function_to_apply: Optional["ClassificationOutputTransform"] = None + top_k: Optional[int] = None + """When specified, limits the output to the top K most probable classes.""" + + +@dataclass +class TextClassificationInput(BaseInferenceType): + """Inputs for Text Classification inference""" + + inputs: str + """The text to classify""" + parameters: Optional[TextClassificationParameters] = None + """Additional inference parameters""" + + +@dataclass +class TextClassificationOutputElement(BaseInferenceType): + """Outputs of inference for the Text Classification task""" + + label: str + """The predicted class label.""" + score: float + """The corresponding probability.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_generation.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..2866985071741b26d69c1afc8902738cff10ef03 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_generation.py @@ -0,0 +1,161 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import List, Literal, Optional + +from .base import BaseInferenceType + + +@dataclass +class TextGenerationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Text Generation + """ + + best_of: Optional[int] = None + """The number of sampling queries to run. Only the best one (in terms of total logprob) will + be returned. + """ + decoder_input_details: Optional[bool] = None + """Whether or not to output decoder input details""" + details: Optional[bool] = None + """Whether or not to output details""" + do_sample: Optional[bool] = None + """Whether to use logits sampling instead of greedy decoding when generating new tokens.""" + max_new_tokens: Optional[int] = None + """The maximum number of tokens to generate.""" + repetition_penalty: Optional[float] = None + """The parameter for repetition penalty. A value of 1.0 means no penalty. See [this + paper](https://hf.co/papers/1909.05858) for more details. + """ + return_full_text: Optional[bool] = None + """Whether to prepend the prompt to the generated text.""" + seed: Optional[int] = None + """The random sampling seed.""" + stop_sequences: Optional[List[str]] = None + """Stop generating tokens if a member of `stop_sequences` is generated.""" + temperature: Optional[float] = None + """The value used to modulate the logits distribution.""" + top_k: Optional[int] = None + """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" + top_p: Optional[float] = None + """If set to < 1, only the smallest set of most probable tokens with probabilities that add + up to `top_p` or higher are kept for generation. + """ + truncate: Optional[int] = None + """Truncate input tokens to the given size.""" + typical_p: Optional[float] = None + """Typical Decoding mass. See [Typical Decoding for Natural Language + Generation](https://hf.co/papers/2202.00666) for more information + """ + watermark: Optional[bool] = None + """Watermarking with [A Watermark for Large Language Models](https://hf.co/papers/2301.10226)""" + + +@dataclass +class TextGenerationInput(BaseInferenceType): + """Inputs for Text Generation inference""" + + inputs: str + """The text to initialize generation with""" + parameters: Optional[TextGenerationParameters] = None + """Additional inference parameters""" + stream: Optional[bool] = None + """Whether to stream output tokens""" + + +TextGenerationFinishReason = Literal["length", "eos_token", "stop_sequence"] + + +@dataclass +class TextGenerationPrefillToken(BaseInferenceType): + id: int + logprob: float + text: str + """The text associated with that token""" + + +@dataclass +class TextGenerationOutputToken(BaseInferenceType): + """Generated token.""" + + id: int + special: bool + """Whether or not that token is a special one""" + text: str + """The text associated with that token""" + logprob: Optional[float] = None + + +@dataclass +class TextGenerationOutputSequenceDetails(BaseInferenceType): + finish_reason: "TextGenerationFinishReason" + generated_text: str + """The generated text""" + generated_tokens: int + """The number of generated tokens""" + prefill: List[TextGenerationPrefillToken] + tokens: List[TextGenerationOutputToken] + """The generated tokens and associated details""" + seed: Optional[int] = None + """The random seed used for generation""" + top_tokens: Optional[List[List[TextGenerationOutputToken]]] = None + """Most likely tokens""" + + +@dataclass +class TextGenerationOutputDetails(BaseInferenceType): + """When enabled, details about the generation""" + + finish_reason: "TextGenerationFinishReason" + """The reason why the generation was stopped.""" + generated_tokens: int + """The number of generated tokens""" + prefill: List[TextGenerationPrefillToken] + tokens: List[TextGenerationOutputToken] + """The generated tokens and associated details""" + best_of_sequences: Optional[List[TextGenerationOutputSequenceDetails]] = None + """Details about additional sequences when best_of is provided""" + seed: Optional[int] = None + """The random seed used for generation""" + top_tokens: Optional[List[List[TextGenerationOutputToken]]] = None + """Most likely tokens""" + + +@dataclass +class TextGenerationOutput(BaseInferenceType): + """Outputs for Text Generation inference""" + + generated_text: str + """The generated text""" + details: Optional[TextGenerationOutputDetails] = None + """When enabled, details about the generation""" + + +@dataclass +class TextGenerationStreamDetails(BaseInferenceType): + """Generation details. Only available when the generation is finished.""" + + finish_reason: "TextGenerationFinishReason" + """The reason why the generation was stopped.""" + generated_tokens: int + """The number of generated tokens""" + seed: int + """The random seed used for generation""" + + +@dataclass +class TextGenerationStreamOutput(BaseInferenceType): + """Text Generation Stream Output""" + + token: TextGenerationOutputToken + """Generated token.""" + details: Optional[TextGenerationStreamDetails] = None + """Generation details. Only available when the generation is finished.""" + generated_text: Optional[str] = None + """The complete generated text. Only available when the generation is finished.""" + index: Optional[int] = None + """The token index within the stream. Optional to support older clients that omit it.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_to_audio.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_to_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8369de4b26cf8ef38cf8cfbafdc1a8bb12d552 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_to_audio.py @@ -0,0 +1,105 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Literal, Optional, Union + +from .base import BaseInferenceType + + +EarlyStoppingEnum = Literal["never"] + + +@dataclass +class TextToAudioGenerationParameters(BaseInferenceType): + """Parametrization of the text generation process + Ad-hoc parametrization of the text generation process + """ + + do_sample: Optional[bool] = None + """Whether to use sampling instead of greedy decoding when generating new tokens.""" + early_stopping: Optional[Union[bool, "EarlyStoppingEnum"]] = None + """Controls the stopping condition for beam-based methods.""" + epsilon_cutoff: Optional[float] = None + """If set to float strictly between 0 and 1, only tokens with a conditional probability + greater than epsilon_cutoff will be sampled. In the paper, suggested values range from + 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language + Model Desmoothing](https://hf.co/papers/2210.15191) for more details. + """ + eta_cutoff: Optional[float] = None + """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to + float strictly between 0 and 1, a token is only considered if it is greater than either + eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter + term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In + the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model. + See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191) + for more details. + """ + max_length: Optional[int] = None + """The maximum length (in tokens) of the generated text, including the input.""" + max_new_tokens: Optional[int] = None + """The maximum number of tokens to generate. Takes precedence over maxLength.""" + min_length: Optional[int] = None + """The minimum length (in tokens) of the generated text, including the input.""" + min_new_tokens: Optional[int] = None + """The minimum number of tokens to generate. Takes precedence over maxLength.""" + num_beam_groups: Optional[int] = None + """Number of groups to divide num_beams into in order to ensure diversity among different + groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details. + """ + num_beams: Optional[int] = None + """Number of beams to use for beam search.""" + penalty_alpha: Optional[float] = None + """The value balances the model confidence and the degeneration penalty in contrastive + search decoding. + """ + temperature: Optional[float] = None + """The value used to modulate the next token probabilities.""" + top_k: Optional[int] = None + """The number of highest probability vocabulary tokens to keep for top-k-filtering.""" + top_p: Optional[float] = None + """If set to float < 1, only the smallest set of most probable tokens with probabilities + that add up to top_p or higher are kept for generation. + """ + typical_p: Optional[float] = None + """Local typicality measures how similar the conditional probability of predicting a target + token next is to the expected conditional probability of predicting a random token next, + given the partial text already generated. If set to float < 1, the smallest set of the + most locally typical tokens with probabilities that add up to typical_p or higher are + kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details. + """ + use_cache: Optional[bool] = None + """Whether the model should use the past last key/values attentions to speed up decoding""" + + +@dataclass +class TextToAudioParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Text To Audio + """ + + generate: Optional[TextToAudioGenerationParameters] = None + """Parametrization of the text generation process""" + + +@dataclass +class TextToAudioInput(BaseInferenceType): + """Inputs for Text To Audio inference""" + + inputs: str + """The input text data""" + parameters: Optional[TextToAudioParameters] = None + """Additional inference parameters""" + + +@dataclass +class TextToAudioOutput(BaseInferenceType): + """Outputs of inference for the Text To Audio task""" + + audio: Any + """The generated audio waveform.""" + sampling_rate: Any + text_to_audio_output_sampling_rate: Optional[float] = None + """The sampling rate of the generated audio waveform.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/token_classification.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/token_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..2d60ea27eedbfe28096435c84e4002c0d9a64bc6 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/token_classification.py @@ -0,0 +1,53 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, List, Literal, Optional + +from .base import BaseInferenceType + + +TokenClassificationAggregationStrategy = Literal["none", "simple", "first", "average", "max"] + + +@dataclass +class TokenClassificationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Token Classification + """ + + aggregation_strategy: Optional["TokenClassificationAggregationStrategy"] = None + """The strategy used to fuse tokens based on model predictions""" + ignore_labels: Optional[List[str]] = None + """A list of labels to ignore""" + stride: Optional[int] = None + """The number of overlapping tokens between chunks when splitting the input text.""" + + +@dataclass +class TokenClassificationInput(BaseInferenceType): + """Inputs for Token Classification inference""" + + inputs: str + """The input text data""" + parameters: Optional[TokenClassificationParameters] = None + """Additional inference parameters""" + + +@dataclass +class TokenClassificationOutputElement(BaseInferenceType): + """Outputs of inference for the Token Classification task""" + + label: Any + score: float + """The associated score / probability""" + end: Optional[int] = None + """The character position in the input where this group ends.""" + entity_group: Optional[str] = None + """The predicted label for that group of tokens""" + start: Optional[int] = None + """The character position in the input where this group begins.""" + word: Optional[str] = None + """The corresponding text""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/translation.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/translation.py new file mode 100644 index 0000000000000000000000000000000000000000..e06ad2b72d35dcf814b110112cd882cb4b4cc616 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/translation.py @@ -0,0 +1,46 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Dict, Literal, Optional + +from .base import BaseInferenceType + + +TranslationGenerationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"] + + +@dataclass +class TranslationGenerationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Text2text Generation + """ + + clean_up_tokenization_spaces: Optional[bool] = None + """Whether to clean up the potential extra spaces in the text output.""" + generate_parameters: Optional[Dict[str, Any]] = None + """Additional parametrization of the text generation algorithm""" + truncation: Optional["TranslationGenerationTruncationStrategy"] = None + """The truncation strategy to use""" + + +@dataclass +class TranslationInput(BaseInferenceType): + """Inputs for Translation inference + Inputs for Text2text Generation inference + """ + + inputs: str + """The input text data""" + parameters: Optional[TranslationGenerationParameters] = None + """Additional inference parameters""" + + +@dataclass +class TranslationOutput(BaseInferenceType): + """Outputs of inference for the Translation task""" + + translation_text: str + """The translated text.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/video_classification.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/video_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..0c5a9d55a81fab6fc71e1226e7776a7a68ee688f --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/video_classification.py @@ -0,0 +1,47 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Literal, Optional + +from .base import BaseInferenceType + + +ClassificationOutputTransform = Literal["sigmoid", "softmax", "none"] + + +@dataclass +class VideoClassificationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Video Classification + """ + + frame_sampling_rate: Optional[int] = None + """The sampling rate used to select frames from the video.""" + function_to_apply: Optional["ClassificationOutputTransform"] = None + num_frames: Optional[int] = None + """The number of sampled frames to consider for classification.""" + top_k: Optional[int] = None + """When specified, limits the output to the top K most probable classes.""" + + +@dataclass +class VideoClassificationInput(BaseInferenceType): + """Inputs for Video Classification inference""" + + inputs: Any + """The input video data""" + parameters: Optional[VideoClassificationParameters] = None + """Additional inference parameters""" + + +@dataclass +class VideoClassificationOutputElement(BaseInferenceType): + """Outputs of inference for the Video Classification task""" + + label: str + """The predicted class label.""" + score: float + """The corresponding probability.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_image_classification.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_image_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..1d635187d7ed2f92eb239dc1e4ee4754394dad4c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_image_classification.py @@ -0,0 +1,51 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, List, Optional + +from .base import BaseInferenceType + + +@dataclass +class ZeroShotImageClassificationInputData(BaseInferenceType): + """The input image data, with candidate labels""" + + candidate_labels: List[str] + """The candidate labels for this image""" + image: Any + """The image data to classify""" + + +@dataclass +class ZeroShotImageClassificationParameters(BaseInferenceType): + """Additional inference parameters + Additional inference parameters for Zero Shot Image Classification + """ + + hypothesis_template: Optional[str] = None + """The sentence used in conjunction with candidateLabels to attempt the text classification + by replacing the placeholder with the candidate labels. + """ + + +@dataclass +class ZeroShotImageClassificationInput(BaseInferenceType): + """Inputs for Zero Shot Image Classification inference""" + + inputs: ZeroShotImageClassificationInputData + """The input image data, with candidate labels""" + parameters: Optional[ZeroShotImageClassificationParameters] = None + """Additional inference parameters""" + + +@dataclass +class ZeroShotImageClassificationOutputElement(BaseInferenceType): + """Outputs of inference for the Zero Shot Image Classification task""" + + label: str + """The predicted class label.""" + score: float + """The corresponding probability.""" diff --git a/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_object_detection.py b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_object_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..42a21568c9c652eb307cf2bd44ee9aa06ab4df7b --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/zero_shot_object_detection.py @@ -0,0 +1,55 @@ +# Inference code generated from the JSON schema spec in @huggingface/tasks. +# +# See: +# - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts +# - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks. +from dataclasses import dataclass +from typing import Any, Dict, List, Optional + +from .base import BaseInferenceType + + +@dataclass +class ZeroShotObjectDetectionInputData(BaseInferenceType): + """The input image data, with candidate labels""" + + candidate_labels: List[str] + """The candidate labels for this image""" + image: Any + """The image data to generate bounding boxes from""" + + +@dataclass +class ZeroShotObjectDetectionInput(BaseInferenceType): + """Inputs for Zero Shot Object Detection inference""" + + inputs: ZeroShotObjectDetectionInputData + """The input image data, with candidate labels""" + parameters: Optional[Dict[str, Any]] = None + """Additional inference parameters""" + + +@dataclass +class ZeroShotObjectDetectionBoundingBox(BaseInferenceType): + """The predicted bounding box. Coordinates are relative to the top left corner of the input + image. + """ + + xmax: int + xmin: int + ymax: int + ymin: int + + +@dataclass +class ZeroShotObjectDetectionOutputElement(BaseInferenceType): + """Outputs of inference for the Zero Shot Object Detection task""" + + box: ZeroShotObjectDetectionBoundingBox + """The predicted bounding box. Coordinates are relative to the top left corner of the input + image. + """ + label: str + """A candidate label""" + score: float + """The associated score / probability""" diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/__config__.py b/env-llmeval/lib/python3.10/site-packages/scipy/__config__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a40526d1d3326491cbd6f6169cf57e258645a22 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/__config__.py @@ -0,0 +1,161 @@ +# This file is generated by SciPy's build process +# It contains system_info results at the time of building this package. +from enum import Enum + +__all__ = ["show"] +_built_with_meson = True + + +class DisplayModes(Enum): + stdout = "stdout" + dicts = "dicts" + + +def _cleanup(d): + """ + Removes empty values in a `dict` recursively + This ensures we remove values that Meson could not provide to CONFIG + """ + if isinstance(d, dict): + return { k: _cleanup(v) for k, v in d.items() if v != '' and _cleanup(v) != '' } + else: + return d + + +CONFIG = _cleanup( + { + "Compilers": { + "c": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.2.1", + "commands": r"cc", + "args": r"", + "linker args": r"", + }, + "cython": { + "name": r"cython", + "linker": r"cython", + "version": r"3.0.10", + "commands": r"cython", + "args": r"", + "linker args": r"", + }, + "c++": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.2.1", + "commands": r"c++", + "args": r"", + "linker args": r"", + }, + "fortran": { + "name": "gcc", + "linker": r"ld.bfd", + "version": "10.2.1", + "commands": r"gfortran", + "args": r"", + "linker args": r"", + }, + "pythran": { + "version": r"0.15.0", + "include directory": r"../../tmp/pip-build-env-0blqy1or/overlay/lib/python3.10/site-packages/pythran" + }, + }, + "Machine Information": { + "host": { + "cpu": r"x86_64", + "family": r"x86_64", + "endian": r"little", + "system": r"linux", + }, + "build": { + "cpu": r"x86_64", + "family": r"x86_64", + "endian": r"little", + "system": r"linux", + }, + "cross-compiled": bool("False".lower().replace('false', '')), + }, + "Build Dependencies": { + "blas": { + "name": "openblas", + "found": bool("True".lower().replace('false', '')), + "version": "0.3.26.dev", + "detection method": "pkgconfig", + "include directory": r"/usr/local/include", + "lib directory": r"/usr/local/lib", + "openblas configuration": r"USE_64BITINT=0 DYNAMIC_ARCH=1 DYNAMIC_OLDER= NO_CBLAS= NO_LAPACK= NO_LAPACKE= NO_AFFINITY=1 USE_OPENMP= ZEN MAX_THREADS=64", + "pc file directory": r"/usr/local/lib/pkgconfig", + }, + "lapack": { + "name": "openblas", + "found": bool("True".lower().replace('false', '')), + "version": "0.3.26.dev", + "detection method": "pkgconfig", + "include directory": r"/usr/local/include", + "lib directory": r"/usr/local/lib", + "openblas configuration": r"USE_64BITINT=0 DYNAMIC_ARCH=1 DYNAMIC_OLDER= NO_CBLAS= NO_LAPACK= NO_LAPACKE= NO_AFFINITY=1 USE_OPENMP= ZEN MAX_THREADS=64", + "pc file directory": r"/usr/local/lib/pkgconfig", + }, + "pybind11": { + "name": "pybind11", + "version": "2.12.0", + "detection method": "config-tool", + "include directory": r"unknown", + }, + }, + "Python Information": { + "path": r"/opt/python/cp310-cp310/bin/python", + "version": "3.10", + }, + } +) + + +def _check_pyyaml(): + import yaml + + return yaml + + +def show(mode=DisplayModes.stdout.value): + """ + Show libraries and system information on which SciPy was built + and is being used + + Parameters + ---------- + mode : {`'stdout'`, `'dicts'`}, optional. + Indicates how to display the config information. + `'stdout'` prints to console, `'dicts'` returns a dictionary + of the configuration. + + Returns + ------- + out : {`dict`, `None`} + If mode is `'dicts'`, a dict is returned, else None + + Notes + ----- + 1. The `'stdout'` mode will give more readable + output if ``pyyaml`` is installed + + """ + if mode == DisplayModes.stdout.value: + try: # Non-standard library, check import + yaml = _check_pyyaml() + + print(yaml.dump(CONFIG)) + except ModuleNotFoundError: + import warnings + import json + + warnings.warn("Install `pyyaml` for better output", stacklevel=1) + print(json.dumps(CONFIG, indent=2)) + elif mode == DisplayModes.dicts.value: + return CONFIG + else: + raise AttributeError( + f"Invalid `mode`, use one of: {', '.join([e.value for e in DisplayModes])}" + ) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/__init__.py b/env-llmeval/lib/python3.10/site-packages/scipy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d6bbed182a50ee24fe15d2a4a13847684317b318 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/__init__.py @@ -0,0 +1,141 @@ +""" +SciPy: A scientific computing package for Python +================================================ + +Documentation is available in the docstrings and +online at https://docs.scipy.org. + +Subpackages +----------- +Using any of these subpackages requires an explicit import. For example, +``import scipy.cluster``. + +:: + + cluster --- Vector Quantization / Kmeans + constants --- Physical and mathematical constants and units + datasets --- Dataset methods + fft --- Discrete Fourier transforms + fftpack --- Legacy discrete Fourier transforms + integrate --- Integration routines + interpolate --- Interpolation Tools + io --- Data input and output + linalg --- Linear algebra routines + misc --- Utilities that don't have another home. + ndimage --- N-D image package + odr --- Orthogonal Distance Regression + optimize --- Optimization Tools + signal --- Signal Processing Tools + sparse --- Sparse Matrices + spatial --- Spatial data structures and algorithms + special --- Special functions + stats --- Statistical Functions + +Public API in the main SciPy namespace +-------------------------------------- +:: + + __version__ --- SciPy version string + LowLevelCallable --- Low-level callback function + show_config --- Show scipy build configuration + test --- Run scipy unittests + +""" + +import importlib as _importlib + +from numpy import __version__ as __numpy_version__ + + +try: + from scipy.__config__ import show as show_config +except ImportError as e: + msg = """Error importing SciPy: you cannot import SciPy while + being in scipy source directory; please exit the SciPy source + tree first and relaunch your Python interpreter.""" + raise ImportError(msg) from e + + +from scipy.version import version as __version__ + + +# Allow distributors to run custom init code +from . import _distributor_init +del _distributor_init + + +from scipy._lib import _pep440 +# In maintenance branch, change to np_maxversion N+3 if numpy is at N +np_minversion = '1.22.4' +np_maxversion = '2.3.0' +if (_pep440.parse(__numpy_version__) < _pep440.Version(np_minversion) or + _pep440.parse(__numpy_version__) >= _pep440.Version(np_maxversion)): + import warnings + warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}" + f" is required for this version of SciPy (detected " + f"version {__numpy_version__})", + UserWarning, stacklevel=2) +del _pep440 + + +# This is the first import of an extension module within SciPy. If there's +# a general issue with the install, such that extension modules are missing +# or cannot be imported, this is where we'll get a failure - so give an +# informative error message. +try: + from scipy._lib._ccallback import LowLevelCallable +except ImportError as e: + msg = "The `scipy` install you are using seems to be broken, " + \ + "(extension modules cannot be imported), " + \ + "please try reinstalling." + raise ImportError(msg) from e + + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester + + +submodules = [ + 'cluster', + 'constants', + 'datasets', + 'fft', + 'fftpack', + 'integrate', + 'interpolate', + 'io', + 'linalg', + 'misc', + 'ndimage', + 'odr', + 'optimize', + 'signal', + 'sparse', + 'spatial', + 'special', + 'stats' +] + +__all__ = submodules + [ + 'LowLevelCallable', + 'test', + 'show_config', + '__version__', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + if name in submodules: + return _importlib.import_module(f'scipy.{name}') + else: + try: + return globals()[name] + except KeyError: + raise AttributeError( + f"Module 'scipy' has no attribute '{name}'" + ) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/_distributor_init.py b/env-llmeval/lib/python3.10/site-packages/scipy/_distributor_init.py new file mode 100644 index 0000000000000000000000000000000000000000..5df134975aa27d31beaff74c3cbfd2d3fb0a55dd --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/_distributor_init.py @@ -0,0 +1,18 @@ +""" Distributor init file + +Distributors: you can replace the contents of this file with your own custom +code to support particular distributions of SciPy. + +For example, this is a good place to put any checks for hardware requirements +or BLAS/LAPACK library initialization. + +The SciPy standard source distribution will not put code in this file beyond +the try-except import of `_distributor_init_local` (which is not part of a +standard source distribution), so you can safely replace this file with your +own version. +""" + +try: + from . import _distributor_init_local # noqa: F401 +except ImportError: + pass diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0b236497fc7c2bb5ca9350180744ccf392779b4e Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_bspl.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc6eb5411ede7cc7ca1b597c41125b2c0220af4 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_bsplines.py @@ -0,0 +1,2215 @@ +import operator +from math import prod + +import numpy as np +from scipy._lib._util import normalize_axis_index +from scipy.linalg import (get_lapack_funcs, LinAlgError, + cholesky_banded, cho_solve_banded, + solve, solve_banded) +from scipy.optimize import minimize_scalar +from . import _bspl +from . import _fitpack_impl +from scipy.sparse import csr_array +from scipy.special import poch +from itertools import combinations + +__all__ = ["BSpline", "make_interp_spline", "make_lsq_spline", + "make_smoothing_spline"] + + +def _get_dtype(dtype): + """Return np.complex128 for complex dtypes, np.float64 otherwise.""" + if np.issubdtype(dtype, np.complexfloating): + return np.complex128 + else: + return np.float64 + + +def _as_float_array(x, check_finite=False): + """Convert the input into a C contiguous float array. + + NB: Upcasts half- and single-precision floats to double precision. + """ + x = np.ascontiguousarray(x) + dtyp = _get_dtype(x.dtype) + x = x.astype(dtyp, copy=False) + if check_finite and not np.isfinite(x).all(): + raise ValueError("Array must not contain infs or nans.") + return x + + +def _dual_poly(j, k, t, y): + """ + Dual polynomial of the B-spline B_{j,k,t} - + polynomial which is associated with B_{j,k,t}: + $p_{j,k}(y) = (y - t_{j+1})(y - t_{j+2})...(y - t_{j+k})$ + """ + if k == 0: + return 1 + return np.prod([(y - t[j + i]) for i in range(1, k + 1)]) + + +def _diff_dual_poly(j, k, y, d, t): + """ + d-th derivative of the dual polynomial $p_{j,k}(y)$ + """ + if d == 0: + return _dual_poly(j, k, t, y) + if d == k: + return poch(1, k) + comb = list(combinations(range(j + 1, j + k + 1), d)) + res = 0 + for i in range(len(comb) * len(comb[0])): + res += np.prod([(y - t[j + p]) for p in range(1, k + 1) + if (j + p) not in comb[i//d]]) + return res + + +class BSpline: + r"""Univariate spline in the B-spline basis. + + .. math:: + + S(x) = \sum_{j=0}^{n-1} c_j B_{j, k; t}(x) + + where :math:`B_{j, k; t}` are B-spline basis functions of degree `k` + and knots `t`. + + Parameters + ---------- + t : ndarray, shape (n+k+1,) + knots + c : ndarray, shape (>=n, ...) + spline coefficients + k : int + B-spline degree + extrapolate : bool or 'periodic', optional + whether to extrapolate beyond the base interval, ``t[k] .. t[n]``, + or to return nans. + If True, extrapolates the first and last polynomial pieces of b-spline + functions active on the base interval. + If 'periodic', periodic extrapolation is used. + Default is True. + axis : int, optional + Interpolation axis. Default is zero. + + Attributes + ---------- + t : ndarray + knot vector + c : ndarray + spline coefficients + k : int + spline degree + extrapolate : bool + If True, extrapolates the first and last polynomial pieces of b-spline + functions active on the base interval. + axis : int + Interpolation axis. + tck : tuple + A read-only equivalent of ``(self.t, self.c, self.k)`` + + Methods + ------- + __call__ + basis_element + derivative + antiderivative + integrate + insert_knot + construct_fast + design_matrix + from_power_basis + + Notes + ----- + B-spline basis elements are defined via + + .. math:: + + B_{i, 0}(x) = 1, \textrm{if $t_i \le x < t_{i+1}$, otherwise $0$,} + + B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x) + + \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x) + + **Implementation details** + + - At least ``k+1`` coefficients are required for a spline of degree `k`, + so that ``n >= k+1``. Additional coefficients, ``c[j]`` with + ``j > n``, are ignored. + + - B-spline basis elements of degree `k` form a partition of unity on the + *base interval*, ``t[k] <= x <= t[n]``. + + + Examples + -------- + + Translating the recursive definition of B-splines into Python code, we have: + + >>> def B(x, k, i, t): + ... if k == 0: + ... return 1.0 if t[i] <= x < t[i+1] else 0.0 + ... if t[i+k] == t[i]: + ... c1 = 0.0 + ... else: + ... c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t) + ... if t[i+k+1] == t[i+1]: + ... c2 = 0.0 + ... else: + ... c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t) + ... return c1 + c2 + + >>> def bspline(x, t, c, k): + ... n = len(t) - k - 1 + ... assert (n >= k+1) and (len(c) >= n) + ... return sum(c[i] * B(x, k, i, t) for i in range(n)) + + Note that this is an inefficient (if straightforward) way to + evaluate B-splines --- this spline class does it in an equivalent, + but much more efficient way. + + Here we construct a quadratic spline function on the base interval + ``2 <= x <= 4`` and compare with the naive way of evaluating the spline: + + >>> from scipy.interpolate import BSpline + >>> k = 2 + >>> t = [0, 1, 2, 3, 4, 5, 6] + >>> c = [-1, 2, 0, -1] + >>> spl = BSpline(t, c, k) + >>> spl(2.5) + array(1.375) + >>> bspline(2.5, t, c, k) + 1.375 + + Note that outside of the base interval results differ. This is because + `BSpline` extrapolates the first and last polynomial pieces of B-spline + functions active on the base interval. + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> fig, ax = plt.subplots() + >>> xx = np.linspace(1.5, 4.5, 50) + >>> ax.plot(xx, [bspline(x, t, c ,k) for x in xx], 'r-', lw=3, label='naive') + >>> ax.plot(xx, spl(xx), 'b-', lw=4, alpha=0.7, label='BSpline') + >>> ax.grid(True) + >>> ax.legend(loc='best') + >>> plt.show() + + + References + ---------- + .. [1] Tom Lyche and Knut Morken, Spline methods, + http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/ + .. [2] Carl de Boor, A practical guide to splines, Springer, 2001. + + """ + + def __init__(self, t, c, k, extrapolate=True, axis=0): + super().__init__() + + self.k = operator.index(k) + self.c = np.asarray(c) + self.t = np.ascontiguousarray(t, dtype=np.float64) + + if extrapolate == 'periodic': + self.extrapolate = extrapolate + else: + self.extrapolate = bool(extrapolate) + + n = self.t.shape[0] - self.k - 1 + + axis = normalize_axis_index(axis, self.c.ndim) + + # Note that the normalized axis is stored in the object. + self.axis = axis + if axis != 0: + # roll the interpolation axis to be the first one in self.c + # More specifically, the target shape for self.c is (n, ...), + # and axis !=0 means that we have c.shape (..., n, ...) + # ^ + # axis + self.c = np.moveaxis(self.c, axis, 0) + + if k < 0: + raise ValueError("Spline order cannot be negative.") + if self.t.ndim != 1: + raise ValueError("Knot vector must be one-dimensional.") + if n < self.k + 1: + raise ValueError("Need at least %d knots for degree %d" % + (2*k + 2, k)) + if (np.diff(self.t) < 0).any(): + raise ValueError("Knots must be in a non-decreasing order.") + if len(np.unique(self.t[k:n+1])) < 2: + raise ValueError("Need at least two internal knots.") + if not np.isfinite(self.t).all(): + raise ValueError("Knots should not have nans or infs.") + if self.c.ndim < 1: + raise ValueError("Coefficients must be at least 1-dimensional.") + if self.c.shape[0] < n: + raise ValueError("Knots, coefficients and degree are inconsistent.") + + dt = _get_dtype(self.c.dtype) + self.c = np.ascontiguousarray(self.c, dtype=dt) + + @classmethod + def construct_fast(cls, t, c, k, extrapolate=True, axis=0): + """Construct a spline without making checks. + + Accepts same parameters as the regular constructor. Input arrays + `t` and `c` must of correct shape and dtype. + """ + self = object.__new__(cls) + self.t, self.c, self.k = t, c, k + self.extrapolate = extrapolate + self.axis = axis + return self + + @property + def tck(self): + """Equivalent to ``(self.t, self.c, self.k)`` (read-only). + """ + return self.t, self.c, self.k + + @classmethod + def basis_element(cls, t, extrapolate=True): + """Return a B-spline basis element ``B(x | t[0], ..., t[k+1])``. + + Parameters + ---------- + t : ndarray, shape (k+2,) + internal knots + extrapolate : bool or 'periodic', optional + whether to extrapolate beyond the base interval, ``t[0] .. t[k+1]``, + or to return nans. + If 'periodic', periodic extrapolation is used. + Default is True. + + Returns + ------- + basis_element : callable + A callable representing a B-spline basis element for the knot + vector `t`. + + Notes + ----- + The degree of the B-spline, `k`, is inferred from the length of `t` as + ``len(t)-2``. The knot vector is constructed by appending and prepending + ``k+1`` elements to internal knots `t`. + + Examples + -------- + + Construct a cubic B-spline: + + >>> import numpy as np + >>> from scipy.interpolate import BSpline + >>> b = BSpline.basis_element([0, 1, 2, 3, 4]) + >>> k = b.k + >>> b.t[k:-k] + array([ 0., 1., 2., 3., 4.]) + >>> k + 3 + + Construct a quadratic B-spline on ``[0, 1, 1, 2]``, and compare + to its explicit form: + + >>> t = [0, 1, 1, 2] + >>> b = BSpline.basis_element(t) + >>> def f(x): + ... return np.where(x < 1, x*x, (2. - x)**2) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> x = np.linspace(0, 2, 51) + >>> ax.plot(x, b(x), 'g', lw=3) + >>> ax.plot(x, f(x), 'r', lw=8, alpha=0.4) + >>> ax.grid(True) + >>> plt.show() + + """ + k = len(t) - 2 + t = _as_float_array(t) + t = np.r_[(t[0]-1,) * k, t, (t[-1]+1,) * k] + c = np.zeros_like(t) + c[k] = 1. + return cls.construct_fast(t, c, k, extrapolate) + + @classmethod + def design_matrix(cls, x, t, k, extrapolate=False): + """ + Returns a design matrix as a CSR format sparse array. + + Parameters + ---------- + x : array_like, shape (n,) + Points to evaluate the spline at. + t : array_like, shape (nt,) + Sorted 1D array of knots. + k : int + B-spline degree. + extrapolate : bool or 'periodic', optional + Whether to extrapolate based on the first and last intervals + or raise an error. If 'periodic', periodic extrapolation is used. + Default is False. + + .. versionadded:: 1.10.0 + + Returns + ------- + design_matrix : `csr_array` object + Sparse matrix in CSR format where each row contains all the basis + elements of the input row (first row = basis elements of x[0], + ..., last row = basis elements x[-1]). + + Examples + -------- + Construct a design matrix for a B-spline + + >>> from scipy.interpolate import make_interp_spline, BSpline + >>> import numpy as np + >>> x = np.linspace(0, np.pi * 2, 4) + >>> y = np.sin(x) + >>> k = 3 + >>> bspl = make_interp_spline(x, y, k=k) + >>> design_matrix = bspl.design_matrix(x, bspl.t, k) + >>> design_matrix.toarray() + [[1. , 0. , 0. , 0. ], + [0.2962963 , 0.44444444, 0.22222222, 0.03703704], + [0.03703704, 0.22222222, 0.44444444, 0.2962963 ], + [0. , 0. , 0. , 1. ]] + + Construct a design matrix for some vector of knots + + >>> k = 2 + >>> t = [-1, 0, 1, 2, 3, 4, 5, 6] + >>> x = [1, 2, 3, 4] + >>> design_matrix = BSpline.design_matrix(x, t, k).toarray() + >>> design_matrix + [[0.5, 0.5, 0. , 0. , 0. ], + [0. , 0.5, 0.5, 0. , 0. ], + [0. , 0. , 0.5, 0.5, 0. ], + [0. , 0. , 0. , 0.5, 0.5]] + + This result is equivalent to the one created in the sparse format + + >>> c = np.eye(len(t) - k - 1) + >>> design_matrix_gh = BSpline(t, c, k)(x) + >>> np.allclose(design_matrix, design_matrix_gh, atol=1e-14) + True + + Notes + ----- + .. versionadded:: 1.8.0 + + In each row of the design matrix all the basis elements are evaluated + at the certain point (first row - x[0], ..., last row - x[-1]). + + `nt` is a length of the vector of knots: as far as there are + `nt - k - 1` basis elements, `nt` should be not less than `2 * k + 2` + to have at least `k + 1` basis element. + + Out of bounds `x` raises a ValueError. + """ + x = _as_float_array(x, True) + t = _as_float_array(t, True) + + if extrapolate != 'periodic': + extrapolate = bool(extrapolate) + + if k < 0: + raise ValueError("Spline order cannot be negative.") + if t.ndim != 1 or np.any(t[1:] < t[:-1]): + raise ValueError(f"Expect t to be a 1-D sorted array_like, but " + f"got t={t}.") + # There are `nt - k - 1` basis elements in a BSpline built on the + # vector of knots with length `nt`, so to have at least `k + 1` basis + # elements we need to have at least `2 * k + 2` elements in the vector + # of knots. + if len(t) < 2 * k + 2: + raise ValueError(f"Length t is not enough for k={k}.") + + if extrapolate == 'periodic': + # With periodic extrapolation we map x to the segment + # [t[k], t[n]]. + n = t.size - k - 1 + x = t[k] + (x - t[k]) % (t[n] - t[k]) + extrapolate = False + elif not extrapolate and ( + (min(x) < t[k]) or (max(x) > t[t.shape[0] - k - 1]) + ): + # Checks from `find_interval` function + raise ValueError(f'Out of bounds w/ x = {x}.') + + # Compute number of non-zeros of final CSR array in order to determine + # the dtype of indices and indptr of the CSR array. + n = x.shape[0] + nnz = n * (k + 1) + if nnz < np.iinfo(np.int32).max: + int_dtype = np.int32 + else: + int_dtype = np.int64 + # Preallocate indptr and indices + indices = np.empty(n * (k + 1), dtype=int_dtype) + indptr = np.arange(0, (n + 1) * (k + 1), k + 1, dtype=int_dtype) + + # indptr is not passed to Cython as it is already fully computed + data, indices = _bspl._make_design_matrix( + x, t, k, extrapolate, indices + ) + return csr_array( + (data, indices, indptr), + shape=(x.shape[0], t.shape[0] - k - 1) + ) + + def __call__(self, x, nu=0, extrapolate=None): + """ + Evaluate a spline function. + + Parameters + ---------- + x : array_like + points to evaluate the spline at. + nu : int, optional + derivative to evaluate (default is 0). + extrapolate : bool or 'periodic', optional + whether to extrapolate based on the first and last intervals + or return nans. If 'periodic', periodic extrapolation is used. + Default is `self.extrapolate`. + + Returns + ------- + y : array_like + Shape is determined by replacing the interpolation axis + in the coefficient array with the shape of `x`. + + """ + if extrapolate is None: + extrapolate = self.extrapolate + x = np.asarray(x) + x_shape, x_ndim = x.shape, x.ndim + x = np.ascontiguousarray(x.ravel(), dtype=np.float64) + + # With periodic extrapolation we map x to the segment + # [self.t[k], self.t[n]]. + if extrapolate == 'periodic': + n = self.t.size - self.k - 1 + x = self.t[self.k] + (x - self.t[self.k]) % (self.t[n] - + self.t[self.k]) + extrapolate = False + + out = np.empty((len(x), prod(self.c.shape[1:])), dtype=self.c.dtype) + self._ensure_c_contiguous() + self._evaluate(x, nu, extrapolate, out) + out = out.reshape(x_shape + self.c.shape[1:]) + if self.axis != 0: + # transpose to move the calculated values to the interpolation axis + l = list(range(out.ndim)) + l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:] + out = out.transpose(l) + return out + + def _evaluate(self, xp, nu, extrapolate, out): + _bspl.evaluate_spline(self.t, self.c.reshape(self.c.shape[0], -1), + self.k, xp, nu, extrapolate, out) + + def _ensure_c_contiguous(self): + """ + c and t may be modified by the user. The Cython code expects + that they are C contiguous. + + """ + if not self.t.flags.c_contiguous: + self.t = self.t.copy() + if not self.c.flags.c_contiguous: + self.c = self.c.copy() + + def derivative(self, nu=1): + """Return a B-spline representing the derivative. + + Parameters + ---------- + nu : int, optional + Derivative order. + Default is 1. + + Returns + ------- + b : BSpline object + A new instance representing the derivative. + + See Also + -------- + splder, splantider + + """ + c = self.c + # pad the c array if needed + ct = len(self.t) - len(c) + if ct > 0: + c = np.r_[c, np.zeros((ct,) + c.shape[1:])] + tck = _fitpack_impl.splder((self.t, c, self.k), nu) + return self.construct_fast(*tck, extrapolate=self.extrapolate, + axis=self.axis) + + def antiderivative(self, nu=1): + """Return a B-spline representing the antiderivative. + + Parameters + ---------- + nu : int, optional + Antiderivative order. Default is 1. + + Returns + ------- + b : BSpline object + A new instance representing the antiderivative. + + Notes + ----- + If antiderivative is computed and ``self.extrapolate='periodic'``, + it will be set to False for the returned instance. This is done because + the antiderivative is no longer periodic and its correct evaluation + outside of the initially given x interval is difficult. + + See Also + -------- + splder, splantider + + """ + c = self.c + # pad the c array if needed + ct = len(self.t) - len(c) + if ct > 0: + c = np.r_[c, np.zeros((ct,) + c.shape[1:])] + tck = _fitpack_impl.splantider((self.t, c, self.k), nu) + + if self.extrapolate == 'periodic': + extrapolate = False + else: + extrapolate = self.extrapolate + + return self.construct_fast(*tck, extrapolate=extrapolate, + axis=self.axis) + + def integrate(self, a, b, extrapolate=None): + """Compute a definite integral of the spline. + + Parameters + ---------- + a : float + Lower limit of integration. + b : float + Upper limit of integration. + extrapolate : bool or 'periodic', optional + whether to extrapolate beyond the base interval, + ``t[k] .. t[-k-1]``, or take the spline to be zero outside of the + base interval. If 'periodic', periodic extrapolation is used. + If None (default), use `self.extrapolate`. + + Returns + ------- + I : array_like + Definite integral of the spline over the interval ``[a, b]``. + + Examples + -------- + Construct the linear spline ``x if x < 1 else 2 - x`` on the base + interval :math:`[0, 2]`, and integrate it + + >>> from scipy.interpolate import BSpline + >>> b = BSpline.basis_element([0, 1, 2]) + >>> b.integrate(0, 1) + array(0.5) + + If the integration limits are outside of the base interval, the result + is controlled by the `extrapolate` parameter + + >>> b.integrate(-1, 1) + array(0.0) + >>> b.integrate(-1, 1, extrapolate=False) + array(0.5) + + >>> import matplotlib.pyplot as plt + >>> fig, ax = plt.subplots() + >>> ax.grid(True) + >>> ax.axvline(0, c='r', lw=5, alpha=0.5) # base interval + >>> ax.axvline(2, c='r', lw=5, alpha=0.5) + >>> xx = [-1, 1, 2] + >>> ax.plot(xx, b(xx)) + >>> plt.show() + + """ + if extrapolate is None: + extrapolate = self.extrapolate + + # Prepare self.t and self.c. + self._ensure_c_contiguous() + + # Swap integration bounds if needed. + sign = 1 + if b < a: + a, b = b, a + sign = -1 + n = self.t.size - self.k - 1 + + if extrapolate != "periodic" and not extrapolate: + # Shrink the integration interval, if needed. + a = max(a, self.t[self.k]) + b = min(b, self.t[n]) + + if self.c.ndim == 1: + # Fast path: use FITPACK's routine + # (cf _fitpack_impl.splint). + integral = _fitpack_impl.splint(a, b, self.tck) + return integral * sign + + out = np.empty((2, prod(self.c.shape[1:])), dtype=self.c.dtype) + + # Compute the antiderivative. + c = self.c + ct = len(self.t) - len(c) + if ct > 0: + c = np.r_[c, np.zeros((ct,) + c.shape[1:])] + ta, ca, ka = _fitpack_impl.splantider((self.t, c, self.k), 1) + + if extrapolate == 'periodic': + # Split the integral into the part over period (can be several + # of them) and the remaining part. + + ts, te = self.t[self.k], self.t[n] + period = te - ts + interval = b - a + n_periods, left = divmod(interval, period) + + if n_periods > 0: + # Evaluate the difference of antiderivatives. + x = np.asarray([ts, te], dtype=np.float64) + _bspl.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral = out[1] - out[0] + integral *= n_periods + else: + integral = np.zeros((1, prod(self.c.shape[1:])), + dtype=self.c.dtype) + + # Map a to [ts, te], b is always a + left. + a = ts + (a - ts) % period + b = a + left + + # If b <= te then we need to integrate over [a, b], otherwise + # over [a, te] and from xs to what is remained. + if b <= te: + x = np.asarray([a, b], dtype=np.float64) + _bspl.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral += out[1] - out[0] + else: + x = np.asarray([a, te], dtype=np.float64) + _bspl.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral += out[1] - out[0] + + x = np.asarray([ts, ts + b - te], dtype=np.float64) + _bspl.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, False, out) + integral += out[1] - out[0] + else: + # Evaluate the difference of antiderivatives. + x = np.asarray([a, b], dtype=np.float64) + _bspl.evaluate_spline(ta, ca.reshape(ca.shape[0], -1), + ka, x, 0, extrapolate, out) + integral = out[1] - out[0] + + integral *= sign + return integral.reshape(ca.shape[1:]) + + @classmethod + def from_power_basis(cls, pp, bc_type='not-a-knot'): + r""" + Construct a polynomial in the B-spline basis + from a piecewise polynomial in the power basis. + + For now, accepts ``CubicSpline`` instances only. + + Parameters + ---------- + pp : CubicSpline + A piecewise polynomial in the power basis, as created + by ``CubicSpline`` + bc_type : string, optional + Boundary condition type as in ``CubicSpline``: one of the + ``not-a-knot``, ``natural``, ``clamped``, or ``periodic``. + Necessary for construction an instance of ``BSpline`` class. + Default is ``not-a-knot``. + + Returns + ------- + b : BSpline object + A new instance representing the initial polynomial + in the B-spline basis. + + Notes + ----- + .. versionadded:: 1.8.0 + + Accepts only ``CubicSpline`` instances for now. + + The algorithm follows from differentiation + the Marsden's identity [1]: each of coefficients of spline + interpolation function in the B-spline basis is computed as follows: + + .. math:: + + c_j = \sum_{m=0}^{k} \frac{(k-m)!}{k!} + c_{m,i} (-1)^{k-m} D^m p_{j,k}(x_i) + + :math:`c_{m, i}` - a coefficient of CubicSpline, + :math:`D^m p_{j, k}(x_i)` - an m-th defivative of a dual polynomial + in :math:`x_i`. + + ``k`` always equals 3 for now. + + First ``n - 2`` coefficients are computed in :math:`x_i = x_j`, e.g. + + .. math:: + + c_1 = \sum_{m=0}^{k} \frac{(k-1)!}{k!} c_{m,1} D^m p_{j,3}(x_1) + + Last ``nod + 2`` coefficients are computed in ``x[-2]``, + ``nod`` - number of derivatives at the ends. + + For example, consider :math:`x = [0, 1, 2, 3, 4]`, + :math:`y = [1, 1, 1, 1, 1]` and bc_type = ``natural`` + + The coefficients of CubicSpline in the power basis: + + :math:`[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], [1, 1, 1, 1, 1]]` + + The knot vector: :math:`t = [0, 0, 0, 0, 1, 2, 3, 4, 4, 4, 4]` + + In this case + + .. math:: + + c_j = \frac{0!}{k!} c_{3, i} k! = c_{3, i} = 1,~j = 0, ..., 6 + + References + ---------- + .. [1] Tom Lyche and Knut Morken, Spline Methods, 2005, Section 3.1.2 + + """ + from ._cubic import CubicSpline + if not isinstance(pp, CubicSpline): + raise NotImplementedError("Only CubicSpline objects are accepted" + "for now. Got %s instead." % type(pp)) + x = pp.x + coef = pp.c + k = pp.c.shape[0] - 1 + n = x.shape[0] + + if bc_type == 'not-a-knot': + t = _not_a_knot(x, k) + elif bc_type == 'natural' or bc_type == 'clamped': + t = _augknt(x, k) + elif bc_type == 'periodic': + t = _periodic_knots(x, k) + else: + raise TypeError('Unknown boundary condition: %s' % bc_type) + + nod = t.shape[0] - (n + k + 1) # number of derivatives at the ends + c = np.zeros(n + nod, dtype=pp.c.dtype) + for m in range(k + 1): + for i in range(n - 2): + c[i] += poch(k + 1, -m) * coef[m, i]\ + * np.power(-1, k - m)\ + * _diff_dual_poly(i, k, x[i], m, t) + for j in range(n - 2, n + nod): + c[j] += poch(k + 1, -m) * coef[m, n - 2]\ + * np.power(-1, k - m)\ + * _diff_dual_poly(j, k, x[n - 2], m, t) + return cls.construct_fast(t, c, k, pp.extrapolate, pp.axis) + + def insert_knot(self, x, m=1): + """Insert a new knot at `x` of multiplicity `m`. + + Given the knots and coefficients of a B-spline representation, create a + new B-spline with a knot inserted `m` times at point `x`. + + Parameters + ---------- + x : float + The position of the new knot + m : int, optional + The number of times to insert the given knot (its multiplicity). + Default is 1. + + Returns + ------- + spl : BSpline object + A new BSpline object with the new knot inserted. + + Notes + ----- + Based on algorithms from [1]_ and [2]_. + + In case of a periodic spline (``self.extrapolate == "periodic"``) + there must be either at least k interior knots t(j) satisfying + ``t(k+1)>> import numpy as np + >>> from scipy.interpolate import BSpline, make_interp_spline + >>> x = np.linspace(0, 10, 5) + >>> y = np.sin(x) + >>> spl = make_interp_spline(x, y, k=3) + >>> spl.t + array([ 0., 0., 0., 0., 5., 10., 10., 10., 10.]) + + Insert a single knot + + >>> spl_1 = spl.insert_knot(3) + >>> spl_1.t + array([ 0., 0., 0., 0., 3., 5., 10., 10., 10., 10.]) + + Insert a multiple knot + + >>> spl_2 = spl.insert_knot(8, m=3) + >>> spl_2.t + array([ 0., 0., 0., 0., 5., 8., 8., 8., 10., 10., 10., 10.]) + + """ + if x < self.t[self.k] or x > self.t[-self.k-1]: + raise ValueError(f"Cannot insert a knot at {x}.") + if m <= 0: + raise ValueError(f"`m` must be positive, got {m = }.") + + extradim = self.c.shape[1:] + num_extra = prod(extradim) + + tt = self.t.copy() + cc = self.c.copy() + cc = cc.reshape(-1, num_extra) + + for _ in range(m): + tt, cc = _bspl.insert(x, tt, cc, self.k, self.extrapolate == "periodic") + + return self.construct_fast( + tt, cc.reshape((-1,) + extradim), self.k, self.extrapolate, self.axis + ) + + +################################# +# Interpolating spline helpers # +################################# + +def _not_a_knot(x, k): + """Given data x, construct the knot vector w/ not-a-knot BC. + cf de Boor, XIII(12).""" + x = np.asarray(x) + if k % 2 != 1: + raise ValueError("Odd degree for now only. Got %s." % k) + + m = (k - 1) // 2 + t = x[m+1:-m-1] + t = np.r_[(x[0],)*(k+1), t, (x[-1],)*(k+1)] + return t + + +def _augknt(x, k): + """Construct a knot vector appropriate for the order-k interpolation.""" + return np.r_[(x[0],)*k, x, (x[-1],)*k] + + +def _convert_string_aliases(deriv, target_shape): + if isinstance(deriv, str): + if deriv == "clamped": + deriv = [(1, np.zeros(target_shape))] + elif deriv == "natural": + deriv = [(2, np.zeros(target_shape))] + else: + raise ValueError("Unknown boundary condition : %s" % deriv) + return deriv + + +def _process_deriv_spec(deriv): + if deriv is not None: + try: + ords, vals = zip(*deriv) + except TypeError as e: + msg = ("Derivatives, `bc_type`, should be specified as a pair of " + "iterables of pairs of (order, value).") + raise ValueError(msg) from e + else: + ords, vals = [], [] + return np.atleast_1d(ords, vals) + + +def _woodbury_algorithm(A, ur, ll, b, k): + ''' + Solve a cyclic banded linear system with upper right + and lower blocks of size ``(k-1) / 2`` using + the Woodbury formula + + Parameters + ---------- + A : 2-D array, shape(k, n) + Matrix of diagonals of original matrix (see + ``solve_banded`` documentation). + ur : 2-D array, shape(bs, bs) + Upper right block matrix. + ll : 2-D array, shape(bs, bs) + Lower left block matrix. + b : 1-D array, shape(n,) + Vector of constant terms of the system of linear equations. + k : int + B-spline degree. + + Returns + ------- + c : 1-D array, shape(n,) + Solution of the original system of linear equations. + + Notes + ----- + This algorithm works only for systems with banded matrix A plus + a correction term U @ V.T, where the matrix U @ V.T gives upper right + and lower left block of A + The system is solved with the following steps: + 1. New systems of linear equations are constructed: + A @ z_i = u_i, + u_i - column vector of U, + i = 1, ..., k - 1 + 2. Matrix Z is formed from vectors z_i: + Z = [ z_1 | z_2 | ... | z_{k - 1} ] + 3. Matrix H = (1 + V.T @ Z)^{-1} + 4. The system A' @ y = b is solved + 5. x = y - Z @ (H @ V.T @ y) + Also, ``n`` should be greater than ``k``, otherwise corner block + elements will intersect with diagonals. + + Examples + -------- + Consider the case of n = 8, k = 5 (size of blocks - 2 x 2). + The matrix of a system: U: V: + x x x * * a b a b 0 0 0 0 1 0 + x x x x * * c 0 c 0 0 0 0 0 1 + x x x x x * * 0 0 0 0 0 0 0 0 + * x x x x x * 0 0 0 0 0 0 0 0 + * * x x x x x 0 0 0 0 0 0 0 0 + d * * x x x x 0 0 d 0 1 0 0 0 + e f * * x x x 0 0 e f 0 1 0 0 + + References + ---------- + .. [1] William H. Press, Saul A. Teukolsky, William T. Vetterling + and Brian P. Flannery, Numerical Recipes, 2007, Section 2.7.3 + + ''' + k_mod = k - k % 2 + bs = int((k - 1) / 2) + (k + 1) % 2 + + n = A.shape[1] + 1 + U = np.zeros((n - 1, k_mod)) + VT = np.zeros((k_mod, n - 1)) # V transpose + + # upper right block + U[:bs, :bs] = ur + VT[np.arange(bs), np.arange(bs) - bs] = 1 + + # lower left block + U[-bs:, -bs:] = ll + VT[np.arange(bs) - bs, np.arange(bs)] = 1 + + Z = solve_banded((bs, bs), A, U) + + H = solve(np.identity(k_mod) + VT @ Z, np.identity(k_mod)) + + y = solve_banded((bs, bs), A, b) + c = y - Z @ (H @ (VT @ y)) + + return c + + +def _periodic_knots(x, k): + ''' + returns vector of nodes on circle + ''' + xc = np.copy(x) + n = len(xc) + if k % 2 == 0: + dx = np.diff(xc) + xc[1: -1] -= dx[:-1] / 2 + dx = np.diff(xc) + t = np.zeros(n + 2 * k) + t[k: -k] = xc + for i in range(0, k): + # filling first `k` elements in descending order + t[k - i - 1] = t[k - i] - dx[-(i % (n - 1)) - 1] + # filling last `k` elements in ascending order + t[-k + i] = t[-k + i - 1] + dx[i % (n - 1)] + return t + + +def _make_interp_per_full_matr(x, y, t, k): + ''' + Returns a solution of a system for B-spline interpolation with periodic + boundary conditions. First ``k - 1`` rows of matrix are conditions of + periodicity (continuity of ``k - 1`` derivatives at the boundary points). + Last ``n`` rows are interpolation conditions. + RHS is ``k - 1`` zeros and ``n`` ordinates in this case. + + Parameters + ---------- + x : 1-D array, shape (n,) + Values of x - coordinate of a given set of points. + y : 1-D array, shape (n,) + Values of y - coordinate of a given set of points. + t : 1-D array, shape(n+2*k,) + Vector of knots. + k : int + The maximum degree of spline + + Returns + ------- + c : 1-D array, shape (n+k-1,) + B-spline coefficients + + Notes + ----- + ``t`` is supposed to be taken on circle. + + ''' + + x, y, t = map(np.asarray, (x, y, t)) + + n = x.size + # LHS: the collocation matrix + derivatives at edges + matr = np.zeros((n + k - 1, n + k - 1)) + + # derivatives at x[0] and x[-1]: + for i in range(k - 1): + bb = _bspl.evaluate_all_bspl(t, k, x[0], k, nu=i + 1) + matr[i, : k + 1] += bb + bb = _bspl.evaluate_all_bspl(t, k, x[-1], n + k - 1, nu=i + 1)[:-1] + matr[i, -k:] -= bb + + # collocation matrix + for i in range(n): + xval = x[i] + # find interval + if xval == t[k]: + left = k + else: + left = np.searchsorted(t, xval) - 1 + + # fill a row + bb = _bspl.evaluate_all_bspl(t, k, xval, left) + matr[i + k - 1, left-k:left+1] = bb + + # RHS + b = np.r_[[0] * (k - 1), y] + + c = solve(matr, b) + return c + + +def _make_periodic_spline(x, y, t, k, axis): + ''' + Compute the (coefficients of) interpolating B-spline with periodic + boundary conditions. + + Parameters + ---------- + x : array_like, shape (n,) + Abscissas. + y : array_like, shape (n,) + Ordinates. + k : int + B-spline degree. + t : array_like, shape (n + 2 * k,). + Knots taken on a circle, ``k`` on the left and ``k`` on the right + of the vector ``x``. + + Returns + ------- + b : a BSpline object of the degree ``k`` and with knots ``t``. + + Notes + ----- + The original system is formed by ``n + k - 1`` equations where the first + ``k - 1`` of them stand for the ``k - 1`` derivatives continuity on the + edges while the other equations correspond to an interpolating case + (matching all the input points). Due to a special form of knot vector, it + can be proved that in the original system the first and last ``k`` + coefficients of a spline function are the same, respectively. It follows + from the fact that all ``k - 1`` derivatives are equal term by term at ends + and that the matrix of the original system of linear equations is + non-degenerate. So, we can reduce the number of equations to ``n - 1`` + (first ``k - 1`` equations could be reduced). Another trick of this + implementation is cyclic shift of values of B-splines due to equality of + ``k`` unknown coefficients. With this we can receive matrix of the system + with upper right and lower left blocks, and ``k`` diagonals. It allows + to use Woodbury formula to optimize the computations. + + ''' + n = y.shape[0] + + extradim = prod(y.shape[1:]) + y_new = y.reshape(n, extradim) + c = np.zeros((n + k - 1, extradim)) + + # n <= k case is solved with full matrix + if n <= k: + for i in range(extradim): + c[:, i] = _make_interp_per_full_matr(x, y_new[:, i], t, k) + c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:])) + return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis) + + nt = len(t) - k - 1 + + # size of block elements + kul = int(k / 2) + + # kl = ku = k + ab = np.zeros((3 * k + 1, nt), dtype=np.float64, order='F') + + # upper right and lower left blocks + ur = np.zeros((kul, kul)) + ll = np.zeros_like(ur) + + # `offset` is made to shift all the non-zero elements to the end of the + # matrix + _bspl._colloc(x, t, k, ab, offset=k) + + # remove zeros before the matrix + ab = ab[-k - (k + 1) % 2:, :] + + # The least elements in rows (except repetitions) are diagonals + # of block matrices. Upper right matrix is an upper triangular + # matrix while lower left is a lower triangular one. + for i in range(kul): + ur += np.diag(ab[-i - 1, i: kul], k=i) + ll += np.diag(ab[i, -kul - (k % 2): n - 1 + 2 * kul - i], k=-i) + + # remove elements that occur in the last point + # (first and last points are equivalent) + A = ab[:, kul: -k + kul] + + for i in range(extradim): + cc = _woodbury_algorithm(A, ur, ll, y_new[:, i][:-1], k) + c[:, i] = np.concatenate((cc[-kul:], cc, cc[:kul + k % 2])) + c = np.ascontiguousarray(c.reshape((n + k - 1,) + y.shape[1:])) + return BSpline.construct_fast(t, c, k, extrapolate='periodic', axis=axis) + + +def make_interp_spline(x, y, k=3, t=None, bc_type=None, axis=0, + check_finite=True): + """Compute the (coefficients of) interpolating B-spline. + + Parameters + ---------- + x : array_like, shape (n,) + Abscissas. + y : array_like, shape (n, ...) + Ordinates. + k : int, optional + B-spline degree. Default is cubic, ``k = 3``. + t : array_like, shape (nt + k + 1,), optional. + Knots. + The number of knots needs to agree with the number of data points and + the number of derivatives at the edges. Specifically, ``nt - n`` must + equal ``len(deriv_l) + len(deriv_r)``. + bc_type : 2-tuple or None + Boundary conditions. + Default is None, which means choosing the boundary conditions + automatically. Otherwise, it must be a length-two tuple where the first + element (``deriv_l``) sets the boundary conditions at ``x[0]`` and + the second element (``deriv_r``) sets the boundary conditions at + ``x[-1]``. Each of these must be an iterable of pairs + ``(order, value)`` which gives the values of derivatives of specified + orders at the given edge of the interpolation interval. + Alternatively, the following string aliases are recognized: + + * ``"clamped"``: The first derivatives at the ends are zero. This is + equivalent to ``bc_type=([(1, 0.0)], [(1, 0.0)])``. + * ``"natural"``: The second derivatives at ends are zero. This is + equivalent to ``bc_type=([(2, 0.0)], [(2, 0.0)])``. + * ``"not-a-knot"`` (default): The first and second segments are the + same polynomial. This is equivalent to having ``bc_type=None``. + * ``"periodic"``: The values and the first ``k-1`` derivatives at the + ends are equivalent. + + axis : int, optional + Interpolation axis. Default is 0. + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default is True. + + Returns + ------- + b : a BSpline object of the degree ``k`` and with knots ``t``. + + See Also + -------- + BSpline : base class representing the B-spline objects + CubicSpline : a cubic spline in the polynomial basis + make_lsq_spline : a similar factory function for spline fitting + UnivariateSpline : a wrapper over FITPACK spline fitting routines + splrep : a wrapper over FITPACK spline fitting routines + + Examples + -------- + + Use cubic interpolation on Chebyshev nodes: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> def cheb_nodes(N): + ... jj = 2.*np.arange(N) + 1 + ... x = np.cos(np.pi * jj / 2 / N)[::-1] + ... return x + + >>> x = cheb_nodes(20) + >>> y = np.sqrt(1 - x**2) + + >>> from scipy.interpolate import BSpline, make_interp_spline + >>> b = make_interp_spline(x, y) + >>> np.allclose(b(x), y) + True + + Note that the default is a cubic spline with a not-a-knot boundary condition + + >>> b.k + 3 + + Here we use a 'natural' spline, with zero 2nd derivatives at edges: + + >>> l, r = [(2, 0.0)], [(2, 0.0)] + >>> b_n = make_interp_spline(x, y, bc_type=(l, r)) # or, bc_type="natural" + >>> np.allclose(b_n(x), y) + True + >>> x0, x1 = x[0], x[-1] + >>> np.allclose([b_n(x0, 2), b_n(x1, 2)], [0, 0]) + True + + Interpolation of parametric curves is also supported. As an example, we + compute a discretization of a snail curve in polar coordinates + + >>> phi = np.linspace(0, 2.*np.pi, 40) + >>> r = 0.3 + np.cos(phi) + >>> x, y = r*np.cos(phi), r*np.sin(phi) # convert to Cartesian coordinates + + Build an interpolating curve, parameterizing it by the angle + + >>> spl = make_interp_spline(phi, np.c_[x, y]) + + Evaluate the interpolant on a finer grid (note that we transpose the result + to unpack it into a pair of x- and y-arrays) + + >>> phi_new = np.linspace(0, 2.*np.pi, 100) + >>> x_new, y_new = spl(phi_new).T + + Plot the result + + >>> plt.plot(x, y, 'o') + >>> plt.plot(x_new, y_new, '-') + >>> plt.show() + + Build a B-spline curve with 2 dimensional y + + >>> x = np.linspace(0, 2*np.pi, 10) + >>> y = np.array([np.sin(x), np.cos(x)]) + + Periodic condition is satisfied because y coordinates of points on the ends + are equivalent + + >>> ax = plt.axes(projection='3d') + >>> xx = np.linspace(0, 2*np.pi, 100) + >>> bspl = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1) + >>> ax.plot3D(xx, *bspl(xx)) + >>> ax.scatter3D(x, *y, color='red') + >>> plt.show() + + """ + # convert string aliases for the boundary conditions + if bc_type is None or bc_type == 'not-a-knot' or bc_type == 'periodic': + deriv_l, deriv_r = None, None + elif isinstance(bc_type, str): + deriv_l, deriv_r = bc_type, bc_type + else: + try: + deriv_l, deriv_r = bc_type + except TypeError as e: + raise ValueError("Unknown boundary condition: %s" % bc_type) from e + + y = np.asarray(y) + + axis = normalize_axis_index(axis, y.ndim) + + x = _as_float_array(x, check_finite) + y = _as_float_array(y, check_finite) + + y = np.moveaxis(y, axis, 0) # now internally interp axis is zero + + # sanity check the input + if bc_type == 'periodic' and not np.allclose(y[0], y[-1], atol=1e-15): + raise ValueError("First and last points does not match while " + "periodic case expected") + if x.size != y.shape[0]: + raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible') + if np.any(x[1:] == x[:-1]): + raise ValueError("Expect x to not have duplicates") + if x.ndim != 1 or np.any(x[1:] < x[:-1]): + raise ValueError("Expect x to be a 1D strictly increasing sequence.") + + # special-case k=0 right away + if k == 0: + if any(_ is not None for _ in (t, deriv_l, deriv_r)): + raise ValueError("Too much info for k=0: t and bc_type can only " + "be None.") + t = np.r_[x, x[-1]] + c = np.asarray(y) + c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype)) + return BSpline.construct_fast(t, c, k, axis=axis) + + # special-case k=1 (e.g., Lyche and Morken, Eq.(2.16)) + if k == 1 and t is None: + if not (deriv_l is None and deriv_r is None): + raise ValueError("Too much info for k=1: bc_type can only be None.") + t = np.r_[x[0], x, x[-1]] + c = np.asarray(y) + c = np.ascontiguousarray(c, dtype=_get_dtype(c.dtype)) + return BSpline.construct_fast(t, c, k, axis=axis) + + k = operator.index(k) + + if bc_type == 'periodic' and t is not None: + raise NotImplementedError("For periodic case t is constructed " + "automatically and can not be passed " + "manually") + + # come up with a sensible knot vector, if needed + if t is None: + if deriv_l is None and deriv_r is None: + if bc_type == 'periodic': + t = _periodic_knots(x, k) + elif k == 2: + # OK, it's a bit ad hoc: Greville sites + omit + # 2nd and 2nd-to-last points, a la not-a-knot + t = (x[1:] + x[:-1]) / 2. + t = np.r_[(x[0],)*(k+1), + t[1:-1], + (x[-1],)*(k+1)] + else: + t = _not_a_knot(x, k) + else: + t = _augknt(x, k) + + t = _as_float_array(t, check_finite) + + if k < 0: + raise ValueError("Expect non-negative k.") + if t.ndim != 1 or np.any(t[1:] < t[:-1]): + raise ValueError("Expect t to be a 1-D sorted array_like.") + if t.size < x.size + k + 1: + raise ValueError('Got %d knots, need at least %d.' % + (t.size, x.size + k + 1)) + if (x[0] < t[k]) or (x[-1] > t[-k]): + raise ValueError('Out of bounds w/ x = %s.' % x) + + if bc_type == 'periodic': + return _make_periodic_spline(x, y, t, k, axis) + + # Here : deriv_l, r = [(nu, value), ...] + deriv_l = _convert_string_aliases(deriv_l, y.shape[1:]) + deriv_l_ords, deriv_l_vals = _process_deriv_spec(deriv_l) + nleft = deriv_l_ords.shape[0] + + deriv_r = _convert_string_aliases(deriv_r, y.shape[1:]) + deriv_r_ords, deriv_r_vals = _process_deriv_spec(deriv_r) + nright = deriv_r_ords.shape[0] + + # have `n` conditions for `nt` coefficients; need nt-n derivatives + n = x.size + nt = t.size - k - 1 + + if nt - n != nleft + nright: + raise ValueError("The number of derivatives at boundaries does not " + f"match: expected {nt-n}, got {nleft}+{nright}") + + # bail out if the `y` array is zero-sized + if y.size == 0: + c = np.zeros((nt,) + y.shape[1:], dtype=float) + return BSpline.construct_fast(t, c, k, axis=axis) + + # set up the LHS: the collocation matrix + derivatives at boundaries + kl = ku = k + ab = np.zeros((2*kl + ku + 1, nt), dtype=np.float64, order='F') + _bspl._colloc(x, t, k, ab, offset=nleft) + if nleft > 0: + _bspl._handle_lhs_derivatives(t, k, x[0], ab, kl, ku, + deriv_l_ords.astype(np.dtype("long"))) + if nright > 0: + _bspl._handle_lhs_derivatives(t, k, x[-1], ab, kl, ku, + deriv_r_ords.astype(np.dtype("long")), + offset=nt-nright) + + # set up the RHS: values to interpolate (+ derivative values, if any) + extradim = prod(y.shape[1:]) + rhs = np.empty((nt, extradim), dtype=y.dtype) + if nleft > 0: + rhs[:nleft] = deriv_l_vals.reshape(-1, extradim) + rhs[nleft:nt - nright] = y.reshape(-1, extradim) + if nright > 0: + rhs[nt - nright:] = deriv_r_vals.reshape(-1, extradim) + + # solve Ab @ x = rhs; this is the relevant part of linalg.solve_banded + if check_finite: + ab, rhs = map(np.asarray_chkfinite, (ab, rhs)) + gbsv, = get_lapack_funcs(('gbsv',), (ab, rhs)) + lu, piv, c, info = gbsv(kl, ku, ab, rhs, + overwrite_ab=True, overwrite_b=True) + + if info > 0: + raise LinAlgError("Collocation matrix is singular.") + elif info < 0: + raise ValueError('illegal value in %d-th argument of internal gbsv' % -info) + + c = np.ascontiguousarray(c.reshape((nt,) + y.shape[1:])) + return BSpline.construct_fast(t, c, k, axis=axis) + + +def make_lsq_spline(x, y, t, k=3, w=None, axis=0, check_finite=True): + r"""Compute the (coefficients of) an LSQ (Least SQuared) based + fitting B-spline. + + The result is a linear combination + + .. math:: + + S(x) = \sum_j c_j B_j(x; t) + + of the B-spline basis elements, :math:`B_j(x; t)`, which minimizes + + .. math:: + + \sum_{j} \left( w_j \times (S(x_j) - y_j) \right)^2 + + Parameters + ---------- + x : array_like, shape (m,) + Abscissas. + y : array_like, shape (m, ...) + Ordinates. + t : array_like, shape (n + k + 1,). + Knots. + Knots and data points must satisfy Schoenberg-Whitney conditions. + k : int, optional + B-spline degree. Default is cubic, ``k = 3``. + w : array_like, shape (m,), optional + Weights for spline fitting. Must be positive. If ``None``, + then weights are all equal. + Default is ``None``. + axis : int, optional + Interpolation axis. Default is zero. + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination) if the inputs do contain infinities or NaNs. + Default is True. + + Returns + ------- + b : a BSpline object of the degree ``k`` with knots ``t``. + + See Also + -------- + BSpline : base class representing the B-spline objects + make_interp_spline : a similar factory function for interpolating splines + LSQUnivariateSpline : a FITPACK-based spline fitting routine + splrep : a FITPACK-based fitting routine + + Notes + ----- + The number of data points must be larger than the spline degree ``k``. + + Knots ``t`` must satisfy the Schoenberg-Whitney conditions, + i.e., there must be a subset of data points ``x[j]`` such that + ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``. + + Examples + -------- + Generate some noisy data: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + + Now fit a smoothing cubic spline with a pre-defined internal knots. + Here we make the knot vector (k+1)-regular by adding boundary knots: + + >>> from scipy.interpolate import make_lsq_spline, BSpline + >>> t = [-1, 0, 1] + >>> k = 3 + >>> t = np.r_[(x[0],)*(k+1), + ... t, + ... (x[-1],)*(k+1)] + >>> spl = make_lsq_spline(x, y, t, k) + + For comparison, we also construct an interpolating spline for the same + set of data: + + >>> from scipy.interpolate import make_interp_spline + >>> spl_i = make_interp_spline(x, y) + + Plot both: + + >>> xs = np.linspace(-3, 3, 100) + >>> plt.plot(x, y, 'ro', ms=5) + >>> plt.plot(xs, spl(xs), 'g-', lw=3, label='LSQ spline') + >>> plt.plot(xs, spl_i(xs), 'b-', lw=3, alpha=0.7, label='interp spline') + >>> plt.legend(loc='best') + >>> plt.show() + + **NaN handling**: If the input arrays contain ``nan`` values, the result is + not useful since the underlying spline fitting routines cannot deal with + ``nan``. A workaround is to use zero weights for not-a-number data points: + + >>> y[8] = np.nan + >>> w = np.isnan(y) + >>> y[w] = 0. + >>> tck = make_lsq_spline(x, y, t, w=~w) + + Notice the need to replace a ``nan`` by a numerical value (precise value + does not matter as long as the corresponding weight is zero.) + + """ + x = _as_float_array(x, check_finite) + y = _as_float_array(y, check_finite) + t = _as_float_array(t, check_finite) + if w is not None: + w = _as_float_array(w, check_finite) + else: + w = np.ones_like(x) + k = operator.index(k) + + axis = normalize_axis_index(axis, y.ndim) + + y = np.moveaxis(y, axis, 0) # now internally interp axis is zero + + if x.ndim != 1 or np.any(x[1:] - x[:-1] <= 0): + raise ValueError("Expect x to be a 1-D sorted array_like.") + if x.shape[0] < k+1: + raise ValueError("Need more x points.") + if k < 0: + raise ValueError("Expect non-negative k.") + if t.ndim != 1 or np.any(t[1:] - t[:-1] < 0): + raise ValueError("Expect t to be a 1-D sorted array_like.") + if x.size != y.shape[0]: + raise ValueError(f'Shapes of x {x.shape} and y {y.shape} are incompatible') + if k > 0 and np.any((x < t[k]) | (x > t[-k])): + raise ValueError('Out of bounds w/ x = %s.' % x) + if x.size != w.size: + raise ValueError(f'Shapes of x {x.shape} and w {w.shape} are incompatible') + + # number of coefficients + n = t.size - k - 1 + + # construct A.T @ A and rhs with A the collocation matrix, and + # rhs = A.T @ y for solving the LSQ problem ``A.T @ A @ c = A.T @ y`` + lower = True + extradim = prod(y.shape[1:]) + ab = np.zeros((k+1, n), dtype=np.float64, order='F') + rhs = np.zeros((n, extradim), dtype=y.dtype, order='F') + _bspl._norm_eq_lsq(x, t, k, + y.reshape(-1, extradim), + w, + ab, rhs) + rhs = rhs.reshape((n,) + y.shape[1:]) + + # have observation matrix & rhs, can solve the LSQ problem + cho_decomp = cholesky_banded(ab, overwrite_ab=True, lower=lower, + check_finite=check_finite) + c = cho_solve_banded((cho_decomp, lower), rhs, overwrite_b=True, + check_finite=check_finite) + + c = np.ascontiguousarray(c) + return BSpline.construct_fast(t, c, k, axis=axis) + + +############################# +# Smoothing spline helpers # +############################# + +def _compute_optimal_gcv_parameter(X, wE, y, w): + """ + Returns an optimal regularization parameter from the GCV criteria [1]. + + Parameters + ---------- + X : array, shape (5, n) + 5 bands of the design matrix ``X`` stored in LAPACK banded storage. + wE : array, shape (5, n) + 5 bands of the penalty matrix :math:`W^{-1} E` stored in LAPACK banded + storage. + y : array, shape (n,) + Ordinates. + w : array, shape (n,) + Vector of weights. + + Returns + ------- + lam : float + An optimal from the GCV criteria point of view regularization + parameter. + + Notes + ----- + No checks are performed. + + References + ---------- + .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models + for observational data, Philadelphia, Pennsylvania: Society for + Industrial and Applied Mathematics, 1990, pp. 45-65. + :doi:`10.1137/1.9781611970128` + + """ + + def compute_banded_symmetric_XT_W_Y(X, w, Y): + """ + Assuming that the product :math:`X^T W Y` is symmetric and both ``X`` + and ``Y`` are 5-banded, compute the unique bands of the product. + + Parameters + ---------- + X : array, shape (5, n) + 5 bands of the matrix ``X`` stored in LAPACK banded storage. + w : array, shape (n,) + Array of weights + Y : array, shape (5, n) + 5 bands of the matrix ``Y`` stored in LAPACK banded storage. + + Returns + ------- + res : array, shape (4, n) + The result of the product :math:`X^T Y` stored in the banded way. + + Notes + ----- + As far as the matrices ``X`` and ``Y`` are 5-banded, their product + :math:`X^T W Y` is 7-banded. It is also symmetric, so we can store only + unique diagonals. + + """ + # compute W Y + W_Y = np.copy(Y) + + W_Y[2] *= w + for i in range(2): + W_Y[i, 2 - i:] *= w[:-2 + i] + W_Y[3 + i, :-1 - i] *= w[1 + i:] + + n = X.shape[1] + res = np.zeros((4, n)) + for i in range(n): + for j in range(min(n-i, 4)): + res[-j-1, i + j] = sum(X[j:, i] * W_Y[:5-j, i + j]) + return res + + def compute_b_inv(A): + """ + Inverse 3 central bands of matrix :math:`A=U^T D^{-1} U` assuming that + ``U`` is a unit upper triangular banded matrix using an algorithm + proposed in [1]. + + Parameters + ---------- + A : array, shape (4, n) + Matrix to inverse, stored in LAPACK banded storage. + + Returns + ------- + B : array, shape (4, n) + 3 unique bands of the symmetric matrix that is an inverse to ``A``. + The first row is filled with zeros. + + Notes + ----- + The algorithm is based on the cholesky decomposition and, therefore, + in case matrix ``A`` is close to not positive defined, the function + raises LinalgError. + + Both matrices ``A`` and ``B`` are stored in LAPACK banded storage. + + References + ---------- + .. [1] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with + spline functions," Numerische Mathematik, vol. 47, no. 1, + pp. 99-106, 1985. + :doi:`10.1007/BF01389878` + + """ + + def find_b_inv_elem(i, j, U, D, B): + rng = min(3, n - i - 1) + rng_sum = 0. + if j == 0: + # use 2-nd formula from [1] + for k in range(1, rng + 1): + rng_sum -= U[-k - 1, i + k] * B[-k - 1, i + k] + rng_sum += D[i] + B[-1, i] = rng_sum + else: + # use 1-st formula from [1] + for k in range(1, rng + 1): + diag = abs(k - j) + ind = i + min(k, j) + rng_sum -= U[-k - 1, i + k] * B[-diag - 1, ind + diag] + B[-j - 1, i + j] = rng_sum + + U = cholesky_banded(A) + for i in range(2, 5): + U[-i, i-1:] /= U[-1, :-i+1] + D = 1. / (U[-1])**2 + U[-1] /= U[-1] + + n = U.shape[1] + + B = np.zeros(shape=(4, n)) + for i in range(n - 1, -1, -1): + for j in range(min(3, n - i - 1), -1, -1): + find_b_inv_elem(i, j, U, D, B) + # the first row contains garbage and should be removed + B[0] = [0.] * n + return B + + def _gcv(lam, X, XtWX, wE, XtE): + r""" + Computes the generalized cross-validation criteria [1]. + + Parameters + ---------- + lam : float, (:math:`\lambda \geq 0`) + Regularization parameter. + X : array, shape (5, n) + Matrix is stored in LAPACK banded storage. + XtWX : array, shape (4, n) + Product :math:`X^T W X` stored in LAPACK banded storage. + wE : array, shape (5, n) + Matrix :math:`W^{-1} E` stored in LAPACK banded storage. + XtE : array, shape (4, n) + Product :math:`X^T E` stored in LAPACK banded storage. + + Returns + ------- + res : float + Value of the GCV criteria with the regularization parameter + :math:`\lambda`. + + Notes + ----- + Criteria is computed from the formula (1.3.2) [3]: + + .. math: + + GCV(\lambda) = \dfrac{1}{n} \sum\limits_{k = 1}^{n} \dfrac{ \left( + y_k - f_{\lambda}(x_k) \right)^2}{\left( 1 - \Tr{A}/n\right)^2}$. + The criteria is discussed in section 1.3 [3]. + + The numerator is computed using (2.2.4) [3] and the denominator is + computed using an algorithm from [2] (see in the ``compute_b_inv`` + function). + + References + ---------- + .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models + for observational data, Philadelphia, Pennsylvania: Society for + Industrial and Applied Mathematics, 1990, pp. 45-65. + :doi:`10.1137/1.9781611970128` + .. [2] M. F. Hutchinson and F. R. de Hoog, "Smoothing noisy data with + spline functions," Numerische Mathematik, vol. 47, no. 1, + pp. 99-106, 1985. + :doi:`10.1007/BF01389878` + .. [3] E. Zemlyanoy, "Generalized cross-validation smoothing splines", + BSc thesis, 2022. Might be available (in Russian) + `here `_ + + """ + # Compute the numerator from (2.2.4) [3] + n = X.shape[1] + c = solve_banded((2, 2), X + lam * wE, y) + res = np.zeros(n) + # compute ``W^{-1} E c`` with respect to banded-storage of ``E`` + tmp = wE * c + for i in range(n): + for j in range(max(0, i - n + 3), min(5, i + 3)): + res[i] += tmp[j, i + 2 - j] + numer = np.linalg.norm(lam * res)**2 / n + + # compute the denominator + lhs = XtWX + lam * XtE + try: + b_banded = compute_b_inv(lhs) + # compute the trace of the product b_banded @ XtX + tr = b_banded * XtWX + tr[:-1] *= 2 + # find the denominator + denom = (1 - sum(sum(tr)) / n)**2 + except LinAlgError: + # cholesky decomposition cannot be performed + raise ValueError('Seems like the problem is ill-posed') + + res = numer / denom + + return res + + n = X.shape[1] + + XtWX = compute_banded_symmetric_XT_W_Y(X, w, X) + XtE = compute_banded_symmetric_XT_W_Y(X, w, wE) + + def fun(lam): + return _gcv(lam, X, XtWX, wE, XtE) + + gcv_est = minimize_scalar(fun, bounds=(0, n), method='Bounded') + if gcv_est.success: + return gcv_est.x + raise ValueError(f"Unable to find minimum of the GCV " + f"function: {gcv_est.message}") + + +def _coeff_of_divided_diff(x): + """ + Returns the coefficients of the divided difference. + + Parameters + ---------- + x : array, shape (n,) + Array which is used for the computation of divided difference. + + Returns + ------- + res : array_like, shape (n,) + Coefficients of the divided difference. + + Notes + ----- + Vector ``x`` should have unique elements, otherwise an error division by + zero might be raised. + + No checks are performed. + + """ + n = x.shape[0] + res = np.zeros(n) + for i in range(n): + pp = 1. + for k in range(n): + if k != i: + pp *= (x[i] - x[k]) + res[i] = 1. / pp + return res + + +def make_smoothing_spline(x, y, w=None, lam=None): + r""" + Compute the (coefficients of) smoothing cubic spline function using + ``lam`` to control the tradeoff between the amount of smoothness of the + curve and its proximity to the data. In case ``lam`` is None, using the + GCV criteria [1] to find it. + + A smoothing spline is found as a solution to the regularized weighted + linear regression problem: + + .. math:: + + \sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2 + + \lambda\int\limits_{x_1}^{x_n} (f^{(2)}(u))^2 d u + + where :math:`f` is a spline function, :math:`w` is a vector of weights and + :math:`\lambda` is a regularization parameter. + + If ``lam`` is None, we use the GCV criteria to find an optimal + regularization parameter, otherwise we solve the regularized weighted + linear regression problem with given parameter. The parameter controls + the tradeoff in the following way: the larger the parameter becomes, the + smoother the function gets. + + Parameters + ---------- + x : array_like, shape (n,) + Abscissas. `n` must be at least 5. + y : array_like, shape (n,) + Ordinates. `n` must be at least 5. + w : array_like, shape (n,), optional + Vector of weights. Default is ``np.ones_like(x)``. + lam : float, (:math:`\lambda \geq 0`), optional + Regularization parameter. If ``lam`` is None, then it is found from + the GCV criteria. Default is None. + + Returns + ------- + func : a BSpline object. + A callable representing a spline in the B-spline basis + as a solution of the problem of smoothing splines using + the GCV criteria [1] in case ``lam`` is None, otherwise using the + given parameter ``lam``. + + Notes + ----- + This algorithm is a clean room reimplementation of the algorithm + introduced by Woltring in FORTRAN [2]. The original version cannot be used + in SciPy source code because of the license issues. The details of the + reimplementation are discussed here (available only in Russian) [4]. + + If the vector of weights ``w`` is None, we assume that all the points are + equal in terms of weights, and vector of weights is vector of ones. + + Note that in weighted residual sum of squares, weights are not squared: + :math:`\sum\limits_{i=1}^n w_i\lvert y_i - f(x_i) \rvert^2` while in + ``splrep`` the sum is built from the squared weights. + + In cases when the initial problem is ill-posed (for example, the product + :math:`X^T W X` where :math:`X` is a design matrix is not a positive + defined matrix) a ValueError is raised. + + References + ---------- + .. [1] G. Wahba, "Estimating the smoothing parameter" in Spline models for + observational data, Philadelphia, Pennsylvania: Society for Industrial + and Applied Mathematics, 1990, pp. 45-65. + :doi:`10.1137/1.9781611970128` + .. [2] H. J. Woltring, A Fortran package for generalized, cross-validatory + spline smoothing and differentiation, Advances in Engineering + Software, vol. 8, no. 2, pp. 104-113, 1986. + :doi:`10.1016/0141-1195(86)90098-7` + .. [3] T. Hastie, J. Friedman, and R. Tisbshirani, "Smoothing Splines" in + The elements of Statistical Learning: Data Mining, Inference, and + prediction, New York: Springer, 2017, pp. 241-249. + :doi:`10.1007/978-0-387-84858-7` + .. [4] E. Zemlyanoy, "Generalized cross-validation smoothing splines", + BSc thesis, 2022. + ``_ (in + Russian) + + Examples + -------- + Generate some noisy data + + >>> import numpy as np + >>> np.random.seed(1234) + >>> n = 200 + >>> def func(x): + ... return x**3 + x**2 * np.sin(4 * x) + >>> x = np.sort(np.random.random_sample(n) * 4 - 2) + >>> y = func(x) + np.random.normal(scale=1.5, size=n) + + Make a smoothing spline function + + >>> from scipy.interpolate import make_smoothing_spline + >>> spl = make_smoothing_spline(x, y) + + Plot both + + >>> import matplotlib.pyplot as plt + >>> grid = np.linspace(x[0], x[-1], 400) + >>> plt.plot(grid, spl(grid), label='Spline') + >>> plt.plot(grid, func(grid), label='Original function') + >>> plt.scatter(x, y, marker='.') + >>> plt.legend(loc='best') + >>> plt.show() + + """ + + x = np.ascontiguousarray(x, dtype=float) + y = np.ascontiguousarray(y, dtype=float) + + if any(x[1:] - x[:-1] <= 0): + raise ValueError('``x`` should be an ascending array') + + if x.ndim != 1 or y.ndim != 1 or x.shape[0] != y.shape[0]: + raise ValueError('``x`` and ``y`` should be one dimensional and the' + ' same size') + + if w is None: + w = np.ones(len(x)) + else: + w = np.ascontiguousarray(w) + if any(w <= 0): + raise ValueError('Invalid vector of weights') + + t = np.r_[[x[0]] * 3, x, [x[-1]] * 3] + n = x.shape[0] + + if n <= 4: + raise ValueError('``x`` and ``y`` length must be at least 5') + + # It is known that the solution to the stated minimization problem exists + # and is a natural cubic spline with vector of knots equal to the unique + # elements of ``x`` [3], so we will solve the problem in the basis of + # natural splines. + + # create design matrix in the B-spline basis + X_bspl = BSpline.design_matrix(x, t, 3) + # move from B-spline basis to the basis of natural splines using equations + # (2.1.7) [4] + # central elements + X = np.zeros((5, n)) + for i in range(1, 4): + X[i, 2: -2] = X_bspl[i: i - 4, 3: -3][np.diag_indices(n - 4)] + + # first elements + X[1, 1] = X_bspl[0, 0] + X[2, :2] = ((x[2] + x[1] - 2 * x[0]) * X_bspl[0, 0], + X_bspl[1, 1] + X_bspl[1, 2]) + X[3, :2] = ((x[2] - x[0]) * X_bspl[1, 1], X_bspl[2, 2]) + + # last elements + X[1, -2:] = (X_bspl[-3, -3], (x[-1] - x[-3]) * X_bspl[-2, -2]) + X[2, -2:] = (X_bspl[-2, -3] + X_bspl[-2, -2], + (2 * x[-1] - x[-2] - x[-3]) * X_bspl[-1, -1]) + X[3, -2] = X_bspl[-1, -1] + + # create penalty matrix and divide it by vector of weights: W^{-1} E + wE = np.zeros((5, n)) + wE[2:, 0] = _coeff_of_divided_diff(x[:3]) / w[:3] + wE[1:, 1] = _coeff_of_divided_diff(x[:4]) / w[:4] + for j in range(2, n - 2): + wE[:, j] = (x[j+2] - x[j-2]) * _coeff_of_divided_diff(x[j-2:j+3])\ + / w[j-2: j+3] + + wE[:-1, -2] = -_coeff_of_divided_diff(x[-4:]) / w[-4:] + wE[:-2, -1] = _coeff_of_divided_diff(x[-3:]) / w[-3:] + wE *= 6 + + if lam is None: + lam = _compute_optimal_gcv_parameter(X, wE, y, w) + elif lam < 0.: + raise ValueError('Regularization parameter should be non-negative') + + # solve the initial problem in the basis of natural splines + c = solve_banded((2, 2), X + lam * wE, y) + # move back to B-spline basis using equations (2.2.10) [4] + c_ = np.r_[c[0] * (t[5] + t[4] - 2 * t[3]) + c[1], + c[0] * (t[5] - t[3]) + c[1], + c[1: -1], + c[-1] * (t[-4] - t[-6]) + c[-2], + c[-1] * (2 * t[-4] - t[-5] - t[-6]) + c[-2]] + + return BSpline.construct_fast(t, c_, 3) + + +######################## +# FITPACK look-alikes # +######################## + +def fpcheck(x, t, k): + """ Check consistency of the data vector `x` and the knot vector `t`. + + Return None if inputs are consistent, raises a ValueError otherwise. + """ + # This routine is a clone of the `fpchec` Fortran routine, + # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f + # which carries the following comment: + # + # subroutine fpchec verifies the number and the position of the knots + # t(j),j=1,2,...,n of a spline of degree k, in relation to the number + # and the position of the data points x(i),i=1,2,...,m. if all of the + # following conditions are fulfilled, the error parameter ier is set + # to zero. if one of the conditions is violated ier is set to ten. + # 1) k+1 <= n-k-1 <= m + # 2) t(1) <= t(2) <= ... <= t(k+1) + # t(n-k) <= t(n-k+1) <= ... <= t(n) + # 3) t(k+1) < t(k+2) < ... < t(n-k) + # 4) t(k+1) <= x(i) <= t(n-k) + # 5) the conditions specified by schoenberg and whitney must hold + # for at least one subset of data points, i.e. there must be a + # subset of data points y(j) such that + # t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 + x = np.asarray(x) + t = np.asarray(t) + + if x.ndim != 1 or t.ndim != 1: + raise ValueError(f"Expect `x` and `t` be 1D sequences. Got {x = } and {t = }") + + m = x.shape[0] + n = t.shape[0] + nk1 = n - k - 1 + + # check condition no 1 + # c 1) k+1 <= n-k-1 <= m + if not (k + 1 <= nk1 <= m): + raise ValueError(f"Need k+1 <= n-k-1 <= m. Got {m = }, {n = } and {k = }.") + + # check condition no 2 + # c 2) t(1) <= t(2) <= ... <= t(k+1) + # c t(n-k) <= t(n-k+1) <= ... <= t(n) + if (t[:k+1] > t[1:k+2]).any(): + raise ValueError(f"First k knots must be ordered; got {t = }.") + + if (t[nk1:] < t[nk1-1:-1]).any(): + raise ValueError(f"Last k knots must be ordered; got {t = }.") + + # c check condition no 3 + # c 3) t(k+1) < t(k+2) < ... < t(n-k) + if (t[k+1:n-k] <= t[k:n-k-1]).any(): + raise ValueError(f"Internal knots must be distinct. Got {t = }.") + + # c check condition no 4 + # c 4) t(k+1) <= x(i) <= t(n-k) + # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow. + if (x[0] < t[k]) or (x[-1] > t[n-k-1]): + raise ValueError(f"Out of bounds: {x = } and {t = }.") + + # c check condition no 5 + # c 5) the conditions specified by schoenberg and whitney must hold + # c for at least one subset of data points, i.e. there must be a + # c subset of data points y(j) such that + # c t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 + mesg = f"Schoenberg-Whitney condition is violated with {t = } and {x =}." + + if (x[0] >= t[k+1]) or (x[-1] <= t[n-k-2]): + raise ValueError(mesg) + + m = x.shape[0] + l = k+1 + nk3 = n - k - 3 + if nk3 < 2: + return + for j in range(1, nk3+1): + tj = t[j] + l += 1 + tl = t[l] + i = np.argmax(x > tj) + if i >= m-1: + raise ValueError(mesg) + if x[i] >= tl: + raise ValueError(mesg) + return diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..88e916287c98ea12f75d06871dc4a493082493a2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_fitpack2.py @@ -0,0 +1,2362 @@ +""" +fitpack --- curve and surface fitting with splines + +fitpack is based on a collection of Fortran routines DIERCKX +by P. Dierckx (see http://www.netlib.org/dierckx/) transformed +to double routines by Pearu Peterson. +""" +# Created by Pearu Peterson, June,August 2003 +__all__ = [ + 'UnivariateSpline', + 'InterpolatedUnivariateSpline', + 'LSQUnivariateSpline', + 'BivariateSpline', + 'LSQBivariateSpline', + 'SmoothBivariateSpline', + 'LSQSphereBivariateSpline', + 'SmoothSphereBivariateSpline', + 'RectBivariateSpline', + 'RectSphereBivariateSpline'] + + +import warnings + +from numpy import zeros, concatenate, ravel, diff, array, ones # noqa:F401 +import numpy as np + +from . import _fitpack_impl +from . import dfitpack + + +dfitpack_int = dfitpack.types.intvar.dtype + + +# ############### Univariate spline #################### + +_curfit_messages = {1: """ +The required storage space exceeds the available storage space, as +specified by the parameter nest: nest too small. If nest is already +large (say nest > m/2), it may also indicate that s is too small. +The approximation returned is the weighted least-squares spline +according to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp +gives the corresponding weighted sum of squared residuals (fp>s). +""", + 2: """ +A theoretically impossible result was found during the iteration +process for finding a smoothing spline with fp = s: s too small. +There is an approximation returned but the corresponding weighted sum +of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""", + 3: """ +The maximal number of iterations maxit (set to 20 by the program) +allowed for finding a smoothing spline with fp=s has been reached: s +too small. +There is an approximation returned but the corresponding weighted sum +of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""", + 10: """ +Error on entry, no approximation returned. The following conditions +must hold: +xb<=x[0]0, i=0..m-1 +if iopt=-1: + xb>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4]) + >>> w = np.isnan(y) + >>> y[w] = 0. + >>> spl = UnivariateSpline(x, y, w=~w) + + Notice the need to replace a ``nan`` by a numerical value (precise value + does not matter as long as the corresponding weight is zero.) + + References + ---------- + Based on algorithms described in [1]_, [2]_, [3]_, and [4]_: + + .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and + integration of experimental data using spline functions", + J.Comp.Appl.Maths 1 (1975) 165-184. + .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular + grid while using spline functions", SIAM J.Numer.Anal. 19 (1982) + 1286-1304. + .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline + functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981. + .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on + Numerical Analysis, Oxford University Press, 1993. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import UnivariateSpline + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + >>> plt.plot(x, y, 'ro', ms=5) + + Use the default value for the smoothing parameter: + + >>> spl = UnivariateSpline(x, y) + >>> xs = np.linspace(-3, 3, 1000) + >>> plt.plot(xs, spl(xs), 'g', lw=3) + + Manually change the amount of smoothing: + + >>> spl.set_smoothing_factor(0.5) + >>> plt.plot(xs, spl(xs), 'b', lw=3) + >>> plt.show() + + """ + + def __init__(self, x, y, w=None, bbox=[None]*2, k=3, s=None, + ext=0, check_finite=False): + + x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, s, ext, + check_finite) + + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0], + xe=bbox[1], s=s) + if data[-1] == 1: + # nest too small, setting to maximum bound + data = self._reset_nest(data) + self._data = data + self._reset_class() + + @staticmethod + def validate_input(x, y, w, bbox, k, s, ext, check_finite): + x, y, bbox = np.asarray(x), np.asarray(y), np.asarray(bbox) + if w is not None: + w = np.asarray(w) + if check_finite: + w_finite = np.isfinite(w).all() if w is not None else True + if (not np.isfinite(x).all() or not np.isfinite(y).all() or + not w_finite): + raise ValueError("x and y array must not contain " + "NaNs or infs.") + if s is None or s > 0: + if not np.all(diff(x) >= 0.0): + raise ValueError("x must be increasing if s > 0") + else: + if not np.all(diff(x) > 0.0): + raise ValueError("x must be strictly increasing if s = 0") + if x.size != y.size: + raise ValueError("x and y should have a same length") + elif w is not None and not x.size == y.size == w.size: + raise ValueError("x, y, and w should have a same length") + elif bbox.shape != (2,): + raise ValueError("bbox shape should be (2,)") + elif not (1 <= k <= 5): + raise ValueError("k should be 1 <= k <= 5") + elif s is not None and not s >= 0.0: + raise ValueError("s should be s >= 0.0") + + try: + ext = _extrap_modes[ext] + except KeyError as e: + raise ValueError("Unknown extrapolation mode %s." % ext) from e + + return x, y, w, bbox, ext + + @classmethod + def _from_tck(cls, tck, ext=0): + """Construct a spline object from given tck""" + self = cls.__new__(cls) + t, c, k = tck + self._eval_args = tck + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + self._data = (None, None, None, None, None, k, None, len(t), t, + c, None, None, None, None) + self.ext = ext + return self + + def _reset_class(self): + data = self._data + n, t, c, k, ier = data[7], data[8], data[9], data[5], data[-1] + self._eval_args = t[:n], c[:n], k + if ier == 0: + # the spline returned has a residual sum of squares fp + # such that abs(fp-s)/s <= tol with tol a relative + # tolerance set to 0.001 by the program + pass + elif ier == -1: + # the spline returned is an interpolating spline + self._set_class(InterpolatedUnivariateSpline) + elif ier == -2: + # the spline returned is the weighted least-squares + # polynomial of degree k. In this extreme case fp gives + # the upper bound fp0 for the smoothing factor s. + self._set_class(LSQUnivariateSpline) + else: + # error + if ier == 1: + self._set_class(LSQUnivariateSpline) + message = _curfit_messages.get(ier, 'ier=%s' % (ier)) + warnings.warn(message, stacklevel=3) + + def _set_class(self, cls): + self._spline_class = cls + if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline, + LSQUnivariateSpline): + self.__class__ = cls + else: + # It's an unknown subclass -- don't change class. cf. #731 + pass + + def _reset_nest(self, data, nest=None): + n = data[10] + if nest is None: + k, m = data[5], len(data[0]) + nest = m+k+1 # this is the maximum bound for nest + else: + if not n <= nest: + raise ValueError("`nest` can only be increased") + t, c, fpint, nrdata = (np.resize(data[j], nest) for j in + [8, 9, 11, 12]) + + args = data[:8] + (t, c, n, fpint, nrdata, data[13]) + data = dfitpack.fpcurf1(*args) + return data + + def set_smoothing_factor(self, s): + """ Continue spline computation with the given smoothing + factor s and with the knots found at the last call. + + This routine modifies the spline in place. + + """ + data = self._data + if data[6] == -1: + warnings.warn('smoothing factor unchanged for' + 'LSQ spline with fixed knots', + stacklevel=2) + return + args = data[:6] + (s,) + data[7:] + data = dfitpack.fpcurf1(*args) + if data[-1] == 1: + # nest too small, setting to maximum bound + data = self._reset_nest(data) + self._data = data + self._reset_class() + + def __call__(self, x, nu=0, ext=None): + """ + Evaluate spline (or its nu-th derivative) at positions x. + + Parameters + ---------- + x : array_like + A 1-D array of points at which to return the value of the smoothed + spline or its derivatives. Note: `x` can be unordered but the + evaluation is more efficient if `x` is (partially) ordered. + nu : int + The order of derivative of the spline to compute. + ext : int + Controls the value returned for elements of `x` not in the + interval defined by the knot sequence. + + * if ext=0 or 'extrapolate', return the extrapolated value. + * if ext=1 or 'zeros', return 0 + * if ext=2 or 'raise', raise a ValueError + * if ext=3 or 'const', return the boundary value. + + The default value is 0, passed from the initialization of + UnivariateSpline. + + """ + x = np.asarray(x) + # empty input yields empty output + if x.size == 0: + return array([]) + if ext is None: + ext = self.ext + else: + try: + ext = _extrap_modes[ext] + except KeyError as e: + raise ValueError("Unknown extrapolation mode %s." % ext) from e + return _fitpack_impl.splev(x, self._eval_args, der=nu, ext=ext) + + def get_knots(self): + """ Return positions of interior knots of the spline. + + Internally, the knot vector contains ``2*k`` additional boundary knots. + """ + data = self._data + k, n = data[5], data[7] + return data[8][k:n-k] + + def get_coeffs(self): + """Return spline coefficients.""" + data = self._data + k, n = data[5], data[7] + return data[9][:n-k-1] + + def get_residual(self): + """Return weighted sum of squared residuals of the spline approximation. + + This is equivalent to:: + + sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) + + """ + return self._data[10] + + def integral(self, a, b): + """ Return definite integral of the spline between two given points. + + Parameters + ---------- + a : float + Lower limit of integration. + b : float + Upper limit of integration. + + Returns + ------- + integral : float + The value of the definite integral of the spline between limits. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, 3, 11) + >>> y = x**2 + >>> spl = UnivariateSpline(x, y) + >>> spl.integral(0, 3) + 9.0 + + which agrees with :math:`\\int x^2 dx = x^3 / 3` between the limits + of 0 and 3. + + A caveat is that this routine assumes the spline to be zero outside of + the data limits: + + >>> spl.integral(-1, 4) + 9.0 + >>> spl.integral(-1, 0) + 0.0 + + """ + return _fitpack_impl.splint(a, b, self._eval_args) + + def derivatives(self, x): + """ Return all derivatives of the spline at the point x. + + Parameters + ---------- + x : float + The point to evaluate the derivatives at. + + Returns + ------- + der : ndarray, shape(k+1,) + Derivatives of the orders 0 to k. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, 3, 11) + >>> y = x**2 + >>> spl = UnivariateSpline(x, y) + >>> spl.derivatives(1.5) + array([2.25, 3.0, 2.0, 0]) + + """ + return _fitpack_impl.spalde(x, self._eval_args) + + def roots(self): + """ Return the zeros of the spline. + + Notes + ----- + Restriction: only cubic splines are supported by FITPACK. For non-cubic + splines, use `PPoly.root` (see below for an example). + + Examples + -------- + + For some data, this method may miss a root. This happens when one of + the spline knots (which FITPACK places automatically) happens to + coincide with the true root. A workaround is to convert to `PPoly`, + which uses a different root-finding algorithm. + + For example, + + >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05] + >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03, + ... 4.440892e-16, 1.616930e-03, 3.243000e-03, 4.877670e-03, + ... 6.520430e-03, 8.170770e-03] + >>> from scipy.interpolate import UnivariateSpline + >>> spl = UnivariateSpline(x, y, s=0) + >>> spl.roots() + array([], dtype=float64) + + Converting to a PPoly object does find the roots at `x=2`: + + >>> from scipy.interpolate import splrep, PPoly + >>> tck = splrep(x, y, s=0) + >>> ppoly = PPoly.from_spline(tck) + >>> ppoly.roots(extrapolate=False) + array([2.]) + + See Also + -------- + sproot + PPoly.roots + + """ + k = self._data[5] + if k == 3: + t = self._eval_args[0] + mest = 3 * (len(t) - 7) + return _fitpack_impl.sproot(self._eval_args, mest=mest) + raise NotImplementedError('finding roots unsupported for ' + 'non-cubic splines') + + def derivative(self, n=1): + """ + Construct a new spline representing the derivative of this spline. + + Parameters + ---------- + n : int, optional + Order of derivative to evaluate. Default: 1 + + Returns + ------- + spline : UnivariateSpline + Spline of order k2=k-n representing the derivative of this + spline. + + See Also + -------- + splder, antiderivative + + Notes + ----- + + .. versionadded:: 0.13.0 + + Examples + -------- + This can be used for finding maxima of a curve: + + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, 10, 70) + >>> y = np.sin(x) + >>> spl = UnivariateSpline(x, y, k=4, s=0) + + Now, differentiate the spline and find the zeros of the + derivative. (NB: `sproot` only works for order 3 splines, so we + fit an order 4 spline): + + >>> spl.derivative().roots() / np.pi + array([ 0.50000001, 1.5 , 2.49999998]) + + This agrees well with roots :math:`\\pi/2 + n\\pi` of + :math:`\\cos(x) = \\sin'(x)`. + + """ + tck = _fitpack_impl.splder(self._eval_args, n) + # if self.ext is 'const', derivative.ext will be 'zeros' + ext = 1 if self.ext == 3 else self.ext + return UnivariateSpline._from_tck(tck, ext=ext) + + def antiderivative(self, n=1): + """ + Construct a new spline representing the antiderivative of this spline. + + Parameters + ---------- + n : int, optional + Order of antiderivative to evaluate. Default: 1 + + Returns + ------- + spline : UnivariateSpline + Spline of order k2=k+n representing the antiderivative of this + spline. + + Notes + ----- + + .. versionadded:: 0.13.0 + + See Also + -------- + splantider, derivative + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import UnivariateSpline + >>> x = np.linspace(0, np.pi/2, 70) + >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2) + >>> spl = UnivariateSpline(x, y, s=0) + + The derivative is the inverse operation of the antiderivative, + although some floating point error accumulates: + + >>> spl(1.7), spl.antiderivative().derivative()(1.7) + (array(2.1565429877197317), array(2.1565429877201865)) + + Antiderivative can be used to evaluate definite integrals: + + >>> ispl = spl.antiderivative() + >>> ispl(np.pi/2) - ispl(0) + 2.2572053588768486 + + This is indeed an approximation to the complete elliptic integral + :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`: + + >>> from scipy.special import ellipk + >>> ellipk(0.8) + 2.2572053268208538 + + """ + tck = _fitpack_impl.splantider(self._eval_args, n) + return UnivariateSpline._from_tck(tck, self.ext) + + +class InterpolatedUnivariateSpline(UnivariateSpline): + """ + 1-D interpolating spline for a given set of data points. + + Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. + Spline function passes through all provided points. Equivalent to + `UnivariateSpline` with `s` = 0. + + Parameters + ---------- + x : (N,) array_like + Input dimension of data points -- must be strictly increasing + y : (N,) array_like + input dimension of data points + w : (N,) array_like, optional + Weights for spline fitting. Must be positive. If None (default), + weights are all 1. + bbox : (2,) array_like, optional + 2-sequence specifying the boundary of the approximation interval. If + None (default), ``bbox=[x[0], x[-1]]``. + k : int, optional + Degree of the smoothing spline. Must be ``1 <= k <= 5``. Default is + ``k = 3``, a cubic spline. + ext : int or str, optional + Controls the extrapolation mode for elements + not in the interval defined by the knot sequence. + + * if ext=0 or 'extrapolate', return the extrapolated value. + * if ext=1 or 'zeros', return 0 + * if ext=2 or 'raise', raise a ValueError + * if ext=3 of 'const', return the boundary value. + + The default value is 0. + + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination or non-sensical results) if the inputs + do contain infinities or NaNs. + Default is False. + + See Also + -------- + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + LSQUnivariateSpline : + a spline for which knots are user-selected + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + splrep : + a function to find the B-spline representation of a 1-D curve + splev : + a function to evaluate a B-spline or its derivatives + sproot : + a function to find the roots of a cubic B-spline + splint : + a function to evaluate the definite integral of a B-spline between two + given points + spalde : + a function to evaluate all derivatives of a B-spline + + Notes + ----- + The number of data points must be larger than the spline degree `k`. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.interpolate import InterpolatedUnivariateSpline + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + >>> spl = InterpolatedUnivariateSpline(x, y) + >>> plt.plot(x, y, 'ro', ms=5) + >>> xs = np.linspace(-3, 3, 1000) + >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7) + >>> plt.show() + + Notice that the ``spl(x)`` interpolates `y`: + + >>> spl.get_residual() + 0.0 + + """ + + def __init__(self, x, y, w=None, bbox=[None]*2, k=3, + ext=0, check_finite=False): + + x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None, + ext, check_finite) + if not np.all(diff(x) > 0.0): + raise ValueError('x must be strictly increasing') + + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + self._data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0], + xe=bbox[1], s=0) + self._reset_class() + + +_fpchec_error_string = """The input parameters have been rejected by fpchec. \ +This means that at least one of the following conditions is violated: + +1) k+1 <= n-k-1 <= m +2) t(1) <= t(2) <= ... <= t(k+1) + t(n-k) <= t(n-k+1) <= ... <= t(n) +3) t(k+1) < t(k+2) < ... < t(n-k) +4) t(k+1) <= x(i) <= t(n-k) +5) The conditions specified by Schoenberg and Whitney must hold + for at least one subset of data points, i.e., there must be a + subset of data points y(j) such that + t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1 +""" + + +class LSQUnivariateSpline(UnivariateSpline): + """ + 1-D spline with explicit internal knots. + + Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. `t` + specifies the internal knots of the spline + + Parameters + ---------- + x : (N,) array_like + Input dimension of data points -- must be increasing + y : (N,) array_like + Input dimension of data points + t : (M,) array_like + interior knots of the spline. Must be in ascending order and:: + + bbox[0] < t[0] < ... < t[-1] < bbox[-1] + + w : (N,) array_like, optional + weights for spline fitting. Must be positive. If None (default), + weights are all 1. + bbox : (2,) array_like, optional + 2-sequence specifying the boundary of the approximation interval. If + None (default), ``bbox = [x[0], x[-1]]``. + k : int, optional + Degree of the smoothing spline. Must be 1 <= `k` <= 5. + Default is `k` = 3, a cubic spline. + ext : int or str, optional + Controls the extrapolation mode for elements + not in the interval defined by the knot sequence. + + * if ext=0 or 'extrapolate', return the extrapolated value. + * if ext=1 or 'zeros', return 0 + * if ext=2 or 'raise', raise a ValueError + * if ext=3 of 'const', return the boundary value. + + The default value is 0. + + check_finite : bool, optional + Whether to check that the input arrays contain only finite numbers. + Disabling may give a performance gain, but may result in problems + (crashes, non-termination or non-sensical results) if the inputs + do contain infinities or NaNs. + Default is False. + + Raises + ------ + ValueError + If the interior knots do not satisfy the Schoenberg-Whitney conditions + + See Also + -------- + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + InterpolatedUnivariateSpline : + a interpolating univariate spline for a given set of data points. + splrep : + a function to find the B-spline representation of a 1-D curve + splev : + a function to evaluate a B-spline or its derivatives + sproot : + a function to find the roots of a cubic B-spline + splint : + a function to evaluate the definite integral of a B-spline between two + given points + spalde : + a function to evaluate all derivatives of a B-spline + + Notes + ----- + The number of data points must be larger than the spline degree `k`. + + Knots `t` must satisfy the Schoenberg-Whitney conditions, + i.e., there must be a subset of data points ``x[j]`` such that + ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline + >>> import matplotlib.pyplot as plt + >>> rng = np.random.default_rng() + >>> x = np.linspace(-3, 3, 50) + >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50) + + Fit a smoothing spline with a pre-defined internal knots: + + >>> t = [-1, 0, 1] + >>> spl = LSQUnivariateSpline(x, y, t) + + >>> xs = np.linspace(-3, 3, 1000) + >>> plt.plot(x, y, 'ro', ms=5) + >>> plt.plot(xs, spl(xs), 'g-', lw=3) + >>> plt.show() + + Check the knot vector: + + >>> spl.get_knots() + array([-3., -1., 0., 1., 3.]) + + Constructing lsq spline using the knots from another spline: + + >>> x = np.arange(10) + >>> s = UnivariateSpline(x, x, s=0) + >>> s.get_knots() + array([ 0., 2., 3., 4., 5., 6., 7., 9.]) + >>> knt = s.get_knots() + >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1]) # Chop 1st and last knot + >>> s1.get_knots() + array([ 0., 2., 3., 4., 5., 6., 7., 9.]) + + """ + + def __init__(self, x, y, t, w=None, bbox=[None]*2, k=3, + ext=0, check_finite=False): + + x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None, + ext, check_finite) + if not np.all(diff(x) >= 0.0): + raise ValueError('x must be increasing') + + # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier + xb = bbox[0] + xe = bbox[1] + if xb is None: + xb = x[0] + if xe is None: + xe = x[-1] + t = concatenate(([xb]*(k+1), t, [xe]*(k+1))) + n = len(t) + if not np.all(t[k+1:n-k]-t[k:n-k-1] > 0, axis=0): + raise ValueError('Interior knots t must satisfy ' + 'Schoenberg-Whitney conditions') + if not dfitpack.fpchec(x, t, k) == 0: + raise ValueError(_fpchec_error_string) + data = dfitpack.fpcurfm1(x, y, k, t, w=w, xb=xb, xe=xe) + self._data = data[:-3] + (None, None, data[-1]) + self._reset_class() + + +# ############### Bivariate spline #################### + +class _BivariateSplineBase: + """ Base class for Bivariate spline s(x,y) interpolation on the rectangle + [xb,xe] x [yb, ye] calculated from a given set of data points + (x,y,z). + + See Also + -------- + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + BivariateSpline : + a base class for bivariate splines. + SphereBivariateSpline : + a bivariate spline on a spherical grid + """ + + @classmethod + def _from_tck(cls, tck): + """Construct a spline object from given tck and degree""" + self = cls.__new__(cls) + if len(tck) != 5: + raise ValueError("tck should be a 5 element tuple of tx," + " ty, c, kx, ky") + self.tck = tck[:3] + self.degrees = tck[3:] + return self + + def get_residual(self): + """ Return weighted sum of squared residuals of the spline + approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0) + """ + return self.fp + + def get_knots(self): + """ Return a tuple (tx,ty) where tx,ty contain knots positions + of the spline with respect to x-, y-variable, respectively. + The position of interior and additional knots are given as + t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively. + """ + return self.tck[:2] + + def get_coeffs(self): + """ Return spline coefficients.""" + return self.tck[2] + + def __call__(self, x, y, dx=0, dy=0, grid=True): + """ + Evaluate the spline or its derivatives at given positions. + + Parameters + ---------- + x, y : array_like + Input coordinates. + + If `grid` is False, evaluate the spline at points ``(x[i], + y[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting + is obeyed. + + If `grid` is True: evaluate spline at the grid points + defined by the coordinate arrays x, y. The arrays must be + sorted to increasing order. + + The ordering of axes is consistent with + ``np.meshgrid(..., indexing="ij")`` and inconsistent with the + default ordering ``np.meshgrid(..., indexing="xy")``. + dx : int + Order of x-derivative + + .. versionadded:: 0.14.0 + dy : int + Order of y-derivative + + .. versionadded:: 0.14.0 + grid : bool + Whether to evaluate the results on a grid spanned by the + input arrays, or at points specified by the input arrays. + + .. versionadded:: 0.14.0 + + Examples + -------- + Suppose that we want to bilinearly interpolate an exponentially decaying + function in 2 dimensions. + + >>> import numpy as np + >>> from scipy.interpolate import RectBivariateSpline + + We sample the function on a coarse grid. Note that the default indexing="xy" + of meshgrid would result in an unexpected (transposed) result after + interpolation. + + >>> xarr = np.linspace(-3, 3, 100) + >>> yarr = np.linspace(-3, 3, 100) + >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij") + + The function to interpolate decays faster along one axis than the other. + + >>> zdata = np.exp(-np.sqrt((xgrid / 2) ** 2 + ygrid**2)) + + Next we sample on a finer grid using interpolation (kx=ky=1 for bilinear). + + >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1) + >>> xarr_fine = np.linspace(-3, 3, 200) + >>> yarr_fine = np.linspace(-3, 3, 200) + >>> xgrid_fine, ygrid_fine = np.meshgrid(xarr_fine, yarr_fine, indexing="ij") + >>> zdata_interp = rbs(xgrid_fine, ygrid_fine, grid=False) + + And check that the result agrees with the input by plotting both. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 2, 1, aspect="equal") + >>> ax2 = fig.add_subplot(1, 2, 2, aspect="equal") + >>> ax1.imshow(zdata) + >>> ax2.imshow(zdata_interp) + >>> plt.show() + """ + x = np.asarray(x) + y = np.asarray(y) + + tx, ty, c = self.tck[:3] + kx, ky = self.degrees + if grid: + if x.size == 0 or y.size == 0: + return np.zeros((x.size, y.size), dtype=self.tck[2].dtype) + + if (x.size >= 2) and (not np.all(np.diff(x) >= 0.0)): + raise ValueError("x must be strictly increasing when `grid` is True") + if (y.size >= 2) and (not np.all(np.diff(y) >= 0.0)): + raise ValueError("y must be strictly increasing when `grid` is True") + + if dx or dy: + z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y) + if not ier == 0: + raise ValueError("Error code returned by parder: %s" % ier) + else: + z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y) + if not ier == 0: + raise ValueError("Error code returned by bispev: %s" % ier) + else: + # standard Numpy broadcasting + if x.shape != y.shape: + x, y = np.broadcast_arrays(x, y) + + shape = x.shape + x = x.ravel() + y = y.ravel() + + if x.size == 0 or y.size == 0: + return np.zeros(shape, dtype=self.tck[2].dtype) + + if dx or dy: + z, ier = dfitpack.pardeu(tx, ty, c, kx, ky, dx, dy, x, y) + if not ier == 0: + raise ValueError("Error code returned by pardeu: %s" % ier) + else: + z, ier = dfitpack.bispeu(tx, ty, c, kx, ky, x, y) + if not ier == 0: + raise ValueError("Error code returned by bispeu: %s" % ier) + + z = z.reshape(shape) + return z + + def partial_derivative(self, dx, dy): + """Construct a new spline representing a partial derivative of this + spline. + + Parameters + ---------- + dx, dy : int + Orders of the derivative in x and y respectively. They must be + non-negative integers and less than the respective degree of the + original spline (self) in that direction (``kx``, ``ky``). + + Returns + ------- + spline : + A new spline of degrees (``kx - dx``, ``ky - dy``) representing the + derivative of this spline. + + Notes + ----- + + .. versionadded:: 1.9.0 + + """ + if dx == 0 and dy == 0: + return self + else: + kx, ky = self.degrees + if not (dx >= 0 and dy >= 0): + raise ValueError("order of derivative must be positive or" + " zero") + if not (dx < kx and dy < ky): + raise ValueError("order of derivative must be less than" + " degree of spline") + tx, ty, c = self.tck[:3] + newc, ier = dfitpack.pardtc(tx, ty, c, kx, ky, dx, dy) + if ier != 0: + # This should not happen under normal conditions. + raise ValueError("Unexpected error code returned by" + " pardtc: %d" % ier) + nx = len(tx) + ny = len(ty) + newtx = tx[dx:nx - dx] + newty = ty[dy:ny - dy] + newkx, newky = kx - dx, ky - dy + newclen = (nx - dx - kx - 1) * (ny - dy - ky - 1) + return _DerivedBivariateSpline._from_tck((newtx, newty, + newc[:newclen], + newkx, newky)) + + +_surfit_messages = {1: """ +The required storage space exceeds the available storage space: nxest +or nyest too small, or s too small. +The weighted least-squares spline corresponds to the current set of +knots.""", + 2: """ +A theoretically impossible result was found during the iteration +process for finding a smoothing spline with fp = s: s too small or +badly chosen eps. +Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""", + 3: """ +the maximal number of iterations maxit (set to 20 by the program) +allowed for finding a smoothing spline with fp=s has been reached: +s too small. +Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""", + 4: """ +No more knots can be added because the number of b-spline coefficients +(nx-kx-1)*(ny-ky-1) already exceeds the number of data points m: +either s or m too small. +The weighted least-squares spline corresponds to the current set of +knots.""", + 5: """ +No more knots can be added because the additional knot would (quasi) +coincide with an old one: s too small or too large a weight to an +inaccurate data point. +The weighted least-squares spline corresponds to the current set of +knots.""", + 10: """ +Error on entry, no approximation returned. The following conditions +must hold: +xb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1 +If iopt==-1, then + xb>> import numpy as np + >>> from scipy.interpolate import RectBivariateSpline + >>> def f(x, y): + ... return np.exp(-np.sqrt((x / 2) ** 2 + y**2)) + + We sample the function on a coarse grid and set up the interpolator. Note that + the default ``indexing="xy"`` of meshgrid would result in an unexpected + (transposed) result after interpolation. + + >>> xarr = np.linspace(-3, 3, 21) + >>> yarr = np.linspace(-3, 3, 21) + >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij") + >>> zdata = f(xgrid, ygrid) + >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1) + + Next we sample the function along a diagonal slice through the coordinate space + on a finer grid using interpolation. + + >>> xinterp = np.linspace(-3, 3, 201) + >>> yinterp = np.linspace(3, -3, 201) + >>> zinterp = rbs.ev(xinterp, yinterp) + + And check that the interpolation passes through the function evaluations as a + function of the distance from the origin along the slice. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 1, 1) + >>> ax1.plot(np.sqrt(xarr**2 + yarr**2), np.diag(zdata), "or") + >>> ax1.plot(np.sqrt(xinterp**2 + yinterp**2), zinterp, "-b") + >>> plt.show() + """ + return self.__call__(xi, yi, dx=dx, dy=dy, grid=False) + + def integral(self, xa, xb, ya, yb): + """ + Evaluate the integral of the spline over area [xa,xb] x [ya,yb]. + + Parameters + ---------- + xa, xb : float + The end-points of the x integration interval. + ya, yb : float + The end-points of the y integration interval. + + Returns + ------- + integ : float + The value of the resulting integral. + + """ + tx, ty, c = self.tck[:3] + kx, ky = self.degrees + return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb) + + @staticmethod + def _validate_input(x, y, z, w, kx, ky, eps): + x, y, z = np.asarray(x), np.asarray(y), np.asarray(z) + if not x.size == y.size == z.size: + raise ValueError('x, y, and z should have a same length') + + if w is not None: + w = np.asarray(w) + if x.size != w.size: + raise ValueError('x, y, z, and w should have a same length') + elif not np.all(w >= 0.0): + raise ValueError('w should be positive') + if (eps is not None) and (not 0.0 < eps < 1.0): + raise ValueError('eps should be between (0, 1)') + if not x.size >= (kx + 1) * (ky + 1): + raise ValueError('The length of x, y and z should be at least' + ' (kx+1) * (ky+1)') + return x, y, z, w + + +class _DerivedBivariateSpline(_BivariateSplineBase): + """Bivariate spline constructed from the coefficients and knots of another + spline. + + Notes + ----- + The class is not meant to be instantiated directly from the data to be + interpolated or smoothed. As a result, its ``fp`` attribute and + ``get_residual`` method are inherited but overridden; ``AttributeError`` is + raised when they are accessed. + + The other inherited attributes can be used as usual. + """ + _invalid_why = ("is unavailable, because _DerivedBivariateSpline" + " instance is not constructed from data that are to be" + " interpolated or smoothed, but derived from the" + " underlying knots and coefficients of another spline" + " object") + + @property + def fp(self): + raise AttributeError("attribute \"fp\" %s" % self._invalid_why) + + def get_residual(self): + raise AttributeError("method \"get_residual\" %s" % self._invalid_why) + + +class SmoothBivariateSpline(BivariateSpline): + """ + Smooth bivariate spline approximation. + + Parameters + ---------- + x, y, z : array_like + 1-D sequences of data points (order is not important). + w : array_like, optional + Positive 1-D sequence of weights, of same length as `x`, `y` and `z`. + bbox : array_like, optional + Sequence of length 4 specifying the boundary of the rectangular + approximation domain. By default, + ``bbox=[min(x), max(x), min(y), max(y)]``. + kx, ky : ints, optional + Degrees of the bivariate spline. Default is 3. + s : float, optional + Positive smoothing factor defined for estimation condition: + ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s`` + Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an + estimate of the standard deviation of ``z[i]``. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the open + interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``. + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + This routine constructs spline knot vectors automatically via the FITPACK + algorithm. The spline knots may be placed away from the data points. For + some data sets, this routine may fail to construct an interpolating spline, + even if one is requested via ``s=0`` parameter. In such situations, it is + recommended to use `bisplrep` / `bisplev` directly instead of this routine + and, if needed, increase the values of ``nxest`` and ``nyest`` parameters + of `bisplrep`. + + For linear interpolation, prefer `LinearNDInterpolator`. + See ``https://gist.github.com/ev-br/8544371b40f414b7eaf3fe6217209bff`` + for discussion. + + """ + + def __init__(self, x, y, z, w=None, bbox=[None] * 4, kx=3, ky=3, s=None, + eps=1e-16): + + x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps) + bbox = ravel(bbox) + if not bbox.shape == (4,): + raise ValueError('bbox shape should be (4,)') + if s is not None and not s >= 0.0: + raise ValueError("s should be s >= 0.0") + + xb, xe, yb, ye = bbox + nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(x, y, z, w, + xb, xe, yb, + ye, kx, ky, + s=s, eps=eps, + lwrk2=1) + if ier > 10: # lwrk2 was to small, re-run + nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(x, y, z, w, + xb, xe, yb, + ye, kx, ky, + s=s, + eps=eps, + lwrk2=ier) + if ier in [0, -1, -2]: # normal return + pass + else: + message = _surfit_messages.get(ier, 'ier=%s' % (ier)) + warnings.warn(message, stacklevel=2) + + self.fp = fp + self.tck = tx[:nx], ty[:ny], c[:(nx-kx-1)*(ny-ky-1)] + self.degrees = kx, ky + + +class LSQBivariateSpline(BivariateSpline): + """ + Weighted least-squares bivariate spline approximation. + + Parameters + ---------- + x, y, z : array_like + 1-D sequences of data points (order is not important). + tx, ty : array_like + Strictly ordered 1-D sequences of knots coordinates. + w : array_like, optional + Positive 1-D array of weights, of the same length as `x`, `y` and `z`. + bbox : (4,) array_like, optional + Sequence of length 4 specifying the boundary of the rectangular + approximation domain. By default, + ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``. + kx, ky : ints, optional + Degrees of the bivariate spline. Default is 3. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the open + interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``. + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + """ + + def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3, + eps=None): + + x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps) + bbox = ravel(bbox) + if not bbox.shape == (4,): + raise ValueError('bbox shape should be (4,)') + + nx = 2*kx+2+len(tx) + ny = 2*ky+2+len(ty) + # The Fortran subroutine "surfit" (called as dfitpack.surfit_lsq) + # requires that the knot arrays passed as input should be "real + # array(s) of dimension nmax" where "nmax" refers to the greater of nx + # and ny. We pad the tx1/ty1 arrays here so that this is satisfied, and + # slice them to the desired sizes upon return. + nmax = max(nx, ny) + tx1 = zeros((nmax,), float) + ty1 = zeros((nmax,), float) + tx1[kx+1:nx-kx-1] = tx + ty1[ky+1:ny-ky-1] = ty + + xb, xe, yb, ye = bbox + tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1, + w, xb, xe, yb, ye, + kx, ky, eps, lwrk2=1) + if ier > 10: + tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, + nx, tx1, ny, ty1, w, + xb, xe, yb, ye, + kx, ky, eps, lwrk2=ier) + if ier in [0, -1, -2]: # normal return + pass + else: + if ier < -2: + deficiency = (nx-kx-1)*(ny-ky-1)+ier + message = _surfit_messages.get(-3) % (deficiency) + else: + message = _surfit_messages.get(ier, 'ier=%s' % (ier)) + warnings.warn(message, stacklevel=2) + self.fp = fp + self.tck = tx1[:nx], ty1[:ny], c + self.degrees = kx, ky + + +class RectBivariateSpline(BivariateSpline): + """ + Bivariate spline approximation over a rectangular mesh. + + Can be used for both smoothing and interpolating data. + + Parameters + ---------- + x,y : array_like + 1-D arrays of coordinates in strictly ascending order. + Evaluated points outside the data range will be extrapolated. + z : array_like + 2-D array of data with shape (x.size,y.size). + bbox : array_like, optional + Sequence of length 4 specifying the boundary of the rectangular + approximation domain, which means the start and end spline knots of + each dimension are set by these values. By default, + ``bbox=[min(x), max(x), min(y), max(y)]``. + kx, ky : ints, optional + Degrees of the bivariate spline. Default is 3. + s : float, optional + Positive smoothing factor defined for estimation condition: + ``sum((z[i]-f(x[i], y[i]))**2, axis=0) <= s`` where f is a spline + function. Default is ``s=0``, which is for interpolation. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + + If the input data is such that input dimensions have incommensurate + units and differ by many orders of magnitude, the interpolant may have + numerical artifacts. Consider rescaling the data before interpolating. + + """ + + def __init__(self, x, y, z, bbox=[None] * 4, kx=3, ky=3, s=0): + x, y, bbox = ravel(x), ravel(y), ravel(bbox) + z = np.asarray(z) + if not np.all(diff(x) > 0.0): + raise ValueError('x must be strictly increasing') + if not np.all(diff(y) > 0.0): + raise ValueError('y must be strictly increasing') + if not x.size == z.shape[0]: + raise ValueError('x dimension of z must have same number of ' + 'elements as x') + if not y.size == z.shape[1]: + raise ValueError('y dimension of z must have same number of ' + 'elements as y') + if not bbox.shape == (4,): + raise ValueError('bbox shape should be (4,)') + if s is not None and not s >= 0.0: + raise ValueError("s should be s >= 0.0") + + z = ravel(z) + xb, xe, yb, ye = bbox + nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth(x, y, z, xb, xe, yb, + ye, kx, ky, s) + + if ier not in [0, -1, -2]: + msg = _surfit_messages.get(ier, 'ier=%s' % (ier)) + raise ValueError(msg) + + self.fp = fp + self.tck = tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)] + self.degrees = kx, ky + + +_spherefit_messages = _surfit_messages.copy() +_spherefit_messages[10] = """ +ERROR. On entry, the input data are controlled on validity. The following + restrictions must be satisfied: + -1<=iopt<=1, m>=2, ntest>=8 ,npest >=8, 00, i=1,...,m + lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m + kwrk >= m+(ntest-7)*(npest-7) + if iopt=-1: 8<=nt<=ntest , 9<=np<=npest + 0=0: s>=0 + if one of these conditions is found to be violated,control + is immediately repassed to the calling program. in that + case there is no approximation returned.""" +_spherefit_messages[-3] = """ +WARNING. The coefficients of the spline returned have been computed as the + minimal norm least-squares solution of a (numerically) rank + deficient system (deficiency=%i, rank=%i). Especially if the rank + deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large, + the results may be inaccurate. They could also seriously depend on + the value of eps.""" + + +class SphereBivariateSpline(_BivariateSplineBase): + """ + Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a + given set of data points (theta,phi,r). + + .. versionadded:: 0.11.0 + + See Also + -------- + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQUnivariateSpline : + a univariate spline using weighted least-squares fitting + """ + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + """ + Evaluate the spline or its derivatives at given positions. + + Parameters + ---------- + theta, phi : array_like + Input coordinates. + + If `grid` is False, evaluate the spline at points + ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard + Numpy broadcasting is obeyed. + + If `grid` is True: evaluate spline at the grid points + defined by the coordinate arrays theta, phi. The arrays + must be sorted to increasing order. + The ordering of axes is consistent with + ``np.meshgrid(..., indexing="ij")`` and inconsistent with the + default ordering ``np.meshgrid(..., indexing="xy")``. + dtheta : int, optional + Order of theta-derivative + + .. versionadded:: 0.14.0 + dphi : int + Order of phi-derivative + + .. versionadded:: 0.14.0 + grid : bool + Whether to evaluate the results on a grid spanned by the + input arrays, or at points specified by the input arrays. + + .. versionadded:: 0.14.0 + + Examples + -------- + + Suppose that we want to use splines to interpolate a bivariate function on a + sphere. The value of the function is known on a grid of longitudes and + colatitudes. + + >>> import numpy as np + >>> from scipy.interpolate import RectSphereBivariateSpline + >>> def f(theta, phi): + ... return np.sin(theta) * np.cos(phi) + + We evaluate the function on the grid. Note that the default indexing="xy" + of meshgrid would result in an unexpected (transposed) result after + interpolation. + + >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] + >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] + >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") + >>> zdata = f(thetagrid, phigrid) + + We next set up the interpolator and use it to evaluate the function + on a finer grid. + + >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) + >>> thetaarr_fine = np.linspace(0, np.pi, 200) + >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200) + >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine) + + Finally we plot the coarsly-sampled input data alongside the + finely-sampled interpolated data to check that they agree. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 2, 1) + >>> ax2 = fig.add_subplot(1, 2, 2) + >>> ax1.imshow(zdata) + >>> ax2.imshow(zdata_fine) + >>> plt.show() + """ + theta = np.asarray(theta) + phi = np.asarray(phi) + + if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi): + raise ValueError("requested theta out of bounds.") + + return _BivariateSplineBase.__call__(self, theta, phi, + dx=dtheta, dy=dphi, grid=grid) + + def ev(self, theta, phi, dtheta=0, dphi=0): + """ + Evaluate the spline at points + + Returns the interpolated value at ``(theta[i], phi[i]), + i=0,...,len(theta)-1``. + + Parameters + ---------- + theta, phi : array_like + Input coordinates. Standard Numpy broadcasting is obeyed. + The ordering of axes is consistent with + np.meshgrid(..., indexing="ij") and inconsistent with the + default ordering np.meshgrid(..., indexing="xy"). + dtheta : int, optional + Order of theta-derivative + + .. versionadded:: 0.14.0 + dphi : int, optional + Order of phi-derivative + + .. versionadded:: 0.14.0 + + Examples + -------- + Suppose that we want to use splines to interpolate a bivariate function on a + sphere. The value of the function is known on a grid of longitudes and + colatitudes. + + >>> import numpy as np + >>> from scipy.interpolate import RectSphereBivariateSpline + >>> def f(theta, phi): + ... return np.sin(theta) * np.cos(phi) + + We evaluate the function on the grid. Note that the default indexing="xy" + of meshgrid would result in an unexpected (transposed) result after + interpolation. + + >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1] + >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1] + >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij") + >>> zdata = f(thetagrid, phigrid) + + We next set up the interpolator and use it to evaluate the function + at points not on the original grid. + + >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata) + >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200) + >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200) + >>> zinterp = rsbs.ev(thetainterp, phiinterp) + + Finally we plot the original data for a diagonal slice through the + initial grid, and the spline approximation along the same slice. + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(1, 1, 1) + >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or") + >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b") + >>> plt.show() + """ + return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False) + + +class SmoothSphereBivariateSpline(SphereBivariateSpline): + """ + Smooth bivariate spline approximation in spherical coordinates. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + theta, phi, r : array_like + 1-D sequences of data points (order is not important). Coordinates + must be given in radians. Theta must lie within the interval + ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``. + w : array_like, optional + Positive 1-D sequence of weights. + s : float, optional + Positive smoothing factor defined for estimation condition: + ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s`` + Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an + estimate of the standard deviation of ``r[i]``. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the open + interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + For more information, see the FITPACK_ site about this function. + + .. _FITPACK: http://www.netlib.org/dierckx/sphere.f + + Examples + -------- + Suppose we have global data on a coarse grid (the input data does not + have to be on a grid): + + >>> import numpy as np + >>> theta = np.linspace(0., np.pi, 7) + >>> phi = np.linspace(0., 2*np.pi, 9) + >>> data = np.empty((theta.shape[0], phi.shape[0])) + >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0. + >>> data[1:-1,1], data[1:-1,-1] = 1., 1. + >>> data[1,1:-1], data[-2,1:-1] = 1., 1. + >>> data[2:-2,2], data[2:-2,-2] = 2., 2. + >>> data[2,2:-2], data[-3,2:-2] = 2., 2. + >>> data[3,3:-2] = 3. + >>> data = np.roll(data, 4, 1) + + We need to set up the interpolator object + + >>> lats, lons = np.meshgrid(theta, phi) + >>> from scipy.interpolate import SmoothSphereBivariateSpline + >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(), + ... data.T.ravel(), s=3.5) + + As a first test, we'll see what the algorithm returns when run on the + input coordinates + + >>> data_orig = lut(theta, phi) + + Finally we interpolate the data to a finer grid + + >>> fine_lats = np.linspace(0., np.pi, 70) + >>> fine_lons = np.linspace(0., 2 * np.pi, 90) + + >>> data_smth = lut(fine_lats, fine_lons) + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(131) + >>> ax1.imshow(data, interpolation='nearest') + >>> ax2 = fig.add_subplot(132) + >>> ax2.imshow(data_orig, interpolation='nearest') + >>> ax3 = fig.add_subplot(133) + >>> ax3.imshow(data_smth, interpolation='nearest') + >>> plt.show() + + """ + + def __init__(self, theta, phi, r, w=None, s=0., eps=1E-16): + + theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r) + + # input validation + if not ((0.0 <= theta).all() and (theta <= np.pi).all()): + raise ValueError('theta should be between [0, pi]') + if not ((0.0 <= phi).all() and (phi <= 2.0 * np.pi).all()): + raise ValueError('phi should be between [0, 2pi]') + if w is not None: + w = np.asarray(w) + if not (w >= 0.0).all(): + raise ValueError('w should be positive') + if not s >= 0.0: + raise ValueError('s should be positive') + if not 0.0 < eps < 1.0: + raise ValueError('eps should be between (0, 1)') + + nt_, tt_, np_, tp_, c, fp, ier = dfitpack.spherfit_smth(theta, phi, + r, w=w, s=s, + eps=eps) + if ier not in [0, -1, -2]: + message = _spherefit_messages.get(ier, 'ier=%s' % (ier)) + raise ValueError(message) + + self.fp = fp + self.tck = tt_[:nt_], tp_[:np_], c[:(nt_ - 4) * (np_ - 4)] + self.degrees = (3, 3) + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + + theta = np.asarray(theta) + phi = np.asarray(phi) + + if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi): + raise ValueError("requested phi out of bounds.") + + return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta, + dphi=dphi, grid=grid) + + +class LSQSphereBivariateSpline(SphereBivariateSpline): + """ + Weighted least-squares bivariate spline approximation in spherical + coordinates. + + Determines a smoothing bicubic spline according to a given + set of knots in the `theta` and `phi` directions. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + theta, phi, r : array_like + 1-D sequences of data points (order is not important). Coordinates + must be given in radians. Theta must lie within the interval + ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``. + tt, tp : array_like + Strictly ordered 1-D sequences of knots coordinates. + Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``. + w : array_like, optional + Positive 1-D sequence of weights, of the same length as `theta`, `phi` + and `r`. + eps : float, optional + A threshold for determining the effective rank of an over-determined + linear system of equations. `eps` should have a value within the + open interval ``(0, 1)``, the default is 1e-16. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + RectSphereBivariateSpline : + a bivariate spline over a rectangular mesh on a sphere + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + For more information, see the FITPACK_ site about this function. + + .. _FITPACK: http://www.netlib.org/dierckx/sphere.f + + Examples + -------- + Suppose we have global data on a coarse grid (the input data does not + have to be on a grid): + + >>> from scipy.interpolate import LSQSphereBivariateSpline + >>> import numpy as np + >>> import matplotlib.pyplot as plt + + >>> theta = np.linspace(0, np.pi, num=7) + >>> phi = np.linspace(0, 2*np.pi, num=9) + >>> data = np.empty((theta.shape[0], phi.shape[0])) + >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0. + >>> data[1:-1,1], data[1:-1,-1] = 1., 1. + >>> data[1,1:-1], data[-2,1:-1] = 1., 1. + >>> data[2:-2,2], data[2:-2,-2] = 2., 2. + >>> data[2,2:-2], data[-3,2:-2] = 2., 2. + >>> data[3,3:-2] = 3. + >>> data = np.roll(data, 4, 1) + + We need to set up the interpolator object. Here, we must also specify the + coordinates of the knots to use. + + >>> lats, lons = np.meshgrid(theta, phi) + >>> knotst, knotsp = theta.copy(), phi.copy() + >>> knotst[0] += .0001 + >>> knotst[-1] -= .0001 + >>> knotsp[0] += .0001 + >>> knotsp[-1] -= .0001 + >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(), + ... data.T.ravel(), knotst, knotsp) + + As a first test, we'll see what the algorithm returns when run on the + input coordinates + + >>> data_orig = lut(theta, phi) + + Finally we interpolate the data to a finer grid + + >>> fine_lats = np.linspace(0., np.pi, 70) + >>> fine_lons = np.linspace(0., 2*np.pi, 90) + >>> data_lsq = lut(fine_lats, fine_lons) + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(131) + >>> ax1.imshow(data, interpolation='nearest') + >>> ax2 = fig.add_subplot(132) + >>> ax2.imshow(data_orig, interpolation='nearest') + >>> ax3 = fig.add_subplot(133) + >>> ax3.imshow(data_lsq, interpolation='nearest') + >>> plt.show() + + """ + + def __init__(self, theta, phi, r, tt, tp, w=None, eps=1E-16): + + theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r) + tt, tp = np.asarray(tt), np.asarray(tp) + + if not ((0.0 <= theta).all() and (theta <= np.pi).all()): + raise ValueError('theta should be between [0, pi]') + if not ((0.0 <= phi).all() and (phi <= 2*np.pi).all()): + raise ValueError('phi should be between [0, 2pi]') + if not ((0.0 < tt).all() and (tt < np.pi).all()): + raise ValueError('tt should be between (0, pi)') + if not ((0.0 < tp).all() and (tp < 2*np.pi).all()): + raise ValueError('tp should be between (0, 2pi)') + if w is not None: + w = np.asarray(w) + if not (w >= 0.0).all(): + raise ValueError('w should be positive') + if not 0.0 < eps < 1.0: + raise ValueError('eps should be between (0, 1)') + + nt_, np_ = 8 + len(tt), 8 + len(tp) + tt_, tp_ = zeros((nt_,), float), zeros((np_,), float) + tt_[4:-4], tp_[4:-4] = tt, tp + tt_[-4:], tp_[-4:] = np.pi, 2. * np.pi + tt_, tp_, c, fp, ier = dfitpack.spherfit_lsq(theta, phi, r, tt_, tp_, + w=w, eps=eps) + if ier > 0: + message = _spherefit_messages.get(ier, 'ier=%s' % (ier)) + raise ValueError(message) + + self.fp = fp + self.tck = tt_, tp_, c + self.degrees = (3, 3) + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + + theta = np.asarray(theta) + phi = np.asarray(phi) + + if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi): + raise ValueError("requested phi out of bounds.") + + return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta, + dphi=dphi, grid=grid) + + +_spfit_messages = _surfit_messages.copy() +_spfit_messages[10] = """ +ERROR: on entry, the input data are controlled on validity + the following restrictions must be satisfied. + -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1, + -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0. + -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0. + mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8, + kwrk>=5+mu+mv+nuest+nvest, + lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest) + 0< u(i-1)=0: s>=0 + if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7 + if one of these conditions is found to be violated,control is + immediately repassed to the calling program. in that case there is no + approximation returned.""" + + +class RectSphereBivariateSpline(SphereBivariateSpline): + """ + Bivariate spline approximation over a rectangular mesh on a sphere. + + Can be used for smoothing data. + + .. versionadded:: 0.11.0 + + Parameters + ---------- + u : array_like + 1-D array of colatitude coordinates in strictly ascending order. + Coordinates must be given in radians and lie within the open interval + ``(0, pi)``. + v : array_like + 1-D array of longitude coordinates in strictly ascending order. + Coordinates must be given in radians. First element (``v[0]``) must lie + within the interval ``[-pi, pi)``. Last element (``v[-1]``) must satisfy + ``v[-1] <= v[0] + 2*pi``. + r : array_like + 2-D array of data with shape ``(u.size, v.size)``. + s : float, optional + Positive smoothing factor defined for estimation condition + (``s=0`` is for interpolation). + pole_continuity : bool or (bool, bool), optional + Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and + ``u=pi`` (``pole_continuity[1]``). The order of continuity at the pole + will be 1 or 0 when this is True or False, respectively. + Defaults to False. + pole_values : float or (float, float), optional + Data values at the poles ``u=0`` and ``u=pi``. Either the whole + parameter or each individual element can be None. Defaults to None. + pole_exact : bool or (bool, bool), optional + Data value exactness at the poles ``u=0`` and ``u=pi``. If True, the + value is considered to be the right function value, and it will be + fitted exactly. If False, the value will be considered to be a data + value just like the other data values. Defaults to False. + pole_flat : bool or (bool, bool), optional + For the poles at ``u=0`` and ``u=pi``, specify whether or not the + approximation has vanishing derivatives. Defaults to False. + + See Also + -------- + BivariateSpline : + a base class for bivariate splines. + UnivariateSpline : + a smooth univariate spline to fit a given set of data points. + SmoothBivariateSpline : + a smoothing bivariate spline through the given points + LSQBivariateSpline : + a bivariate spline using weighted least-squares fitting + SmoothSphereBivariateSpline : + a smoothing bivariate spline in spherical coordinates + LSQSphereBivariateSpline : + a bivariate spline in spherical coordinates using weighted + least-squares fitting + RectBivariateSpline : + a bivariate spline over a rectangular mesh. + bisplrep : + a function to find a bivariate B-spline representation of a surface + bisplev : + a function to evaluate a bivariate B-spline and its derivatives + + Notes + ----- + Currently, only the smoothing spline approximation (``iopt[0] = 0`` and + ``iopt[0] = 1`` in the FITPACK routine) is supported. The exact + least-squares spline approximation is not implemented yet. + + When actually performing the interpolation, the requested `v` values must + lie within the same length 2pi interval that the original `v` values were + chosen from. + + For more information, see the FITPACK_ site about this function. + + .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f + + Examples + -------- + Suppose we have global data on a coarse grid + + >>> import numpy as np + >>> lats = np.linspace(10, 170, 9) * np.pi / 180. + >>> lons = np.linspace(0, 350, 18) * np.pi / 180. + >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T, + ... np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T + + We want to interpolate it to a global one-degree grid + + >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180 + >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180 + >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons) + + We need to set up the interpolator object + + >>> from scipy.interpolate import RectSphereBivariateSpline + >>> lut = RectSphereBivariateSpline(lats, lons, data) + + Finally we interpolate the data. The `RectSphereBivariateSpline` object + only takes 1-D arrays as input, therefore we need to do some reshaping. + + >>> data_interp = lut.ev(new_lats.ravel(), + ... new_lons.ravel()).reshape((360, 180)).T + + Looking at the original and the interpolated data, one can see that the + interpolant reproduces the original data very well: + + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(211) + >>> ax1.imshow(data, interpolation='nearest') + >>> ax2 = fig.add_subplot(212) + >>> ax2.imshow(data_interp, interpolation='nearest') + >>> plt.show() + + Choosing the optimal value of ``s`` can be a delicate task. Recommended + values for ``s`` depend on the accuracy of the data values. If the user + has an idea of the statistical errors on the data, she can also find a + proper estimate for ``s``. By assuming that, if she specifies the + right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly + reproduces the function underlying the data, she can evaluate + ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``. + For example, if she knows that the statistical errors on her + ``r(i,j)``-values are not greater than 0.1, she may expect that a good + ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``. + + If nothing is known about the statistical error in ``r(i,j)``, ``s`` must + be determined by trial and error. The best is then to start with a very + large value of ``s`` (to determine the least-squares polynomial and the + corresponding upper bound ``fp0`` for ``s``) and then to progressively + decrease the value of ``s`` (say by a factor 10 in the beginning, i.e. + ``s = fp0 / 10, fp0 / 100, ...`` and more carefully as the approximation + shows more detail) to obtain closer fits. + + The interpolation results for different values of ``s`` give some insight + into this process: + + >>> fig2 = plt.figure() + >>> s = [3e9, 2e9, 1e9, 1e8] + >>> for idx, sval in enumerate(s, 1): + ... lut = RectSphereBivariateSpline(lats, lons, data, s=sval) + ... data_interp = lut.ev(new_lats.ravel(), + ... new_lons.ravel()).reshape((360, 180)).T + ... ax = fig2.add_subplot(2, 2, idx) + ... ax.imshow(data_interp, interpolation='nearest') + ... ax.set_title(f"s = {sval:g}") + >>> plt.show() + + """ + + def __init__(self, u, v, r, s=0., pole_continuity=False, pole_values=None, + pole_exact=False, pole_flat=False): + iopt = np.array([0, 0, 0], dtype=dfitpack_int) + ider = np.array([-1, 0, -1, 0], dtype=dfitpack_int) + if pole_values is None: + pole_values = (None, None) + elif isinstance(pole_values, (float, np.float32, np.float64)): + pole_values = (pole_values, pole_values) + if isinstance(pole_continuity, bool): + pole_continuity = (pole_continuity, pole_continuity) + if isinstance(pole_exact, bool): + pole_exact = (pole_exact, pole_exact) + if isinstance(pole_flat, bool): + pole_flat = (pole_flat, pole_flat) + + r0, r1 = pole_values + iopt[1:] = pole_continuity + if r0 is None: + ider[0] = -1 + else: + ider[0] = pole_exact[0] + + if r1 is None: + ider[2] = -1 + else: + ider[2] = pole_exact[1] + + ider[1], ider[3] = pole_flat + + u, v = np.ravel(u), np.ravel(v) + r = np.asarray(r) + + if not (0.0 < u[0] and u[-1] < np.pi): + raise ValueError('u should be between (0, pi)') + if not -np.pi <= v[0] < np.pi: + raise ValueError('v[0] should be between [-pi, pi)') + if not v[-1] <= v[0] + 2*np.pi: + raise ValueError('v[-1] should be v[0] + 2pi or less ') + + if not np.all(np.diff(u) > 0.0): + raise ValueError('u must be strictly increasing') + if not np.all(np.diff(v) > 0.0): + raise ValueError('v must be strictly increasing') + + if not u.size == r.shape[0]: + raise ValueError('u dimension of r must have same number of ' + 'elements as u') + if not v.size == r.shape[1]: + raise ValueError('v dimension of r must have same number of ' + 'elements as v') + + if pole_continuity[1] is False and pole_flat[1] is True: + raise ValueError('if pole_continuity is False, so must be ' + 'pole_flat') + if pole_continuity[0] is False and pole_flat[0] is True: + raise ValueError('if pole_continuity is False, so must be ' + 'pole_flat') + + if not s >= 0.0: + raise ValueError('s should be positive') + + r = np.ravel(r) + nu, tu, nv, tv, c, fp, ier = dfitpack.regrid_smth_spher(iopt, ider, + u.copy(), + v.copy(), + r.copy(), + r0, r1, s) + + if ier not in [0, -1, -2]: + msg = _spfit_messages.get(ier, 'ier=%s' % (ier)) + raise ValueError(msg) + + self.fp = fp + self.tck = tu[:nu], tv[:nv], c[:(nu - 4) * (nv-4)] + self.degrees = (3, 3) + self.v0 = v[0] + + def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True): + + theta = np.asarray(theta) + phi = np.asarray(phi) + + return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta, + dphi=dphi, grid=grid) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..9d9d460f52e7541721a61967750ca20896a5bfc8 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_interpolate.py @@ -0,0 +1,2473 @@ +__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly'] + +from math import prod +import warnings + +import numpy as np +from numpy import (array, transpose, searchsorted, atleast_1d, atleast_2d, + ravel, poly1d, asarray, intp) + +import scipy.special as spec +from scipy._lib._util import copy_if_needed +from scipy.special import comb + +from . import _fitpack_py +from . import dfitpack +from ._polyint import _Interpolator1D +from . import _ppoly +from .interpnd import _ndim_coords_from_arrays +from ._bsplines import make_interp_spline, BSpline + + +def lagrange(x, w): + r""" + Return a Lagrange interpolating polynomial. + + Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating + polynomial through the points ``(x, w)``. + + Warning: This implementation is numerically unstable. Do not expect to + be able to use more than about 20 points even if they are chosen optimally. + + Parameters + ---------- + x : array_like + `x` represents the x-coordinates of a set of datapoints. + w : array_like + `w` represents the y-coordinates of a set of datapoints, i.e., f(`x`). + + Returns + ------- + lagrange : `numpy.poly1d` instance + The Lagrange interpolating polynomial. + + Examples + -------- + Interpolate :math:`f(x) = x^3` by 3 points. + + >>> import numpy as np + >>> from scipy.interpolate import lagrange + >>> x = np.array([0, 1, 2]) + >>> y = x**3 + >>> poly = lagrange(x, y) + + Since there are only 3 points, Lagrange polynomial has degree 2. Explicitly, + it is given by + + .. math:: + + \begin{aligned} + L(x) &= 1\times \frac{x (x - 2)}{-1} + 8\times \frac{x (x-1)}{2} \\ + &= x (-2 + 3x) + \end{aligned} + + >>> from numpy.polynomial.polynomial import Polynomial + >>> Polynomial(poly.coef[::-1]).coef + array([ 0., -2., 3.]) + + >>> import matplotlib.pyplot as plt + >>> x_new = np.arange(0, 2.1, 0.1) + >>> plt.scatter(x, y, label='data') + >>> plt.plot(x_new, Polynomial(poly.coef[::-1])(x_new), label='Polynomial') + >>> plt.plot(x_new, 3*x_new**2 - 2*x_new + 0*x_new, + ... label=r"$3 x^2 - 2 x$", linestyle='-.') + >>> plt.legend() + >>> plt.show() + + """ + + M = len(x) + p = poly1d(0.0) + for j in range(M): + pt = poly1d(w[j]) + for k in range(M): + if k == j: + continue + fac = x[j]-x[k] + pt *= poly1d([1.0, -x[k]])/fac + p += pt + return p + + +# !! Need to find argument for keeping initialize. If it isn't +# !! found, get rid of it! + + +dep_mesg = """\ +`interp2d` is deprecated in SciPy 1.10 and will be removed in SciPy 1.14.0. + +For legacy code, nearly bug-for-bug compatible replacements are +`RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for +scattered 2D data. + +In new code, for regular grids use `RegularGridInterpolator` instead. +For scattered data, prefer `LinearNDInterpolator` or +`CloughTocher2DInterpolator`. + +For more details see +`https://scipy.github.io/devdocs/notebooks/interp_transition_guide.html` +""" + +class interp2d: + """ + interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, + fill_value=None) + + .. deprecated:: 1.10.0 + + `interp2d` is deprecated in SciPy 1.10 and will be removed in SciPy + 1.14.0. + + For legacy code, nearly bug-for-bug compatible replacements are + `RectBivariateSpline` on regular grids, and `bisplrep`/`bisplev` for + scattered 2D data. + + In new code, for regular grids use `RegularGridInterpolator` instead. + For scattered data, prefer `LinearNDInterpolator` or + `CloughTocher2DInterpolator`. + + For more details see + `https://scipy.github.io/devdocs/notebooks/interp_transition_guide.html + `_ + + + Interpolate over a 2-D grid. + + `x`, `y` and `z` are arrays of values used to approximate some function + f: ``z = f(x, y)`` which returns a scalar value `z`. This class returns a + function whose call method uses spline interpolation to find the value + of new points. + + If `x` and `y` represent a regular grid, consider using + `RectBivariateSpline`. + + If `z` is a vector value, consider using `interpn`. + + Note that calling `interp2d` with NaNs present in input values, or with + decreasing values in `x` an `y` results in undefined behaviour. + + Methods + ------- + __call__ + + Parameters + ---------- + x, y : array_like + Arrays defining the data point coordinates. + The data point coordinates need to be sorted by increasing order. + + If the points lie on a regular grid, `x` can specify the column + coordinates and `y` the row coordinates, for example:: + + >>> x = [0,1,2]; y = [0,3]; z = [[1,2,3], [4,5,6]] + + Otherwise, `x` and `y` must specify the full coordinates for each + point, for example:: + + >>> x = [0,1,2,0,1,2]; y = [0,0,0,3,3,3]; z = [1,4,2,5,3,6] + + If `x` and `y` are multidimensional, they are flattened before use. + z : array_like + The values of the function to interpolate at the data points. If + `z` is a multidimensional array, it is flattened before use assuming + Fortran-ordering (order='F'). The length of a flattened `z` array + is either len(`x`)*len(`y`) if `x` and `y` specify the column and + row coordinates or ``len(z) == len(x) == len(y)`` if `x` and `y` + specify coordinates for each point. + kind : {'linear', 'cubic', 'quintic'}, optional + The kind of spline interpolation to use. Default is 'linear'. + copy : bool, optional + If True, the class makes internal copies of x, y and z. + If False, references may be used. The default is to copy. + bounds_error : bool, optional + If True, when interpolated values are requested outside of the + domain of the input data (x,y), a ValueError is raised. + If False, then `fill_value` is used. + fill_value : number, optional + If provided, the value to use for points outside of the + interpolation domain. If omitted (None), values outside + the domain are extrapolated via nearest-neighbor extrapolation. + + See Also + -------- + RectBivariateSpline : + Much faster 2-D interpolation if your input data is on a grid + bisplrep, bisplev : + Spline interpolation based on FITPACK + BivariateSpline : a more recent wrapper of the FITPACK routines + interp1d : 1-D version of this function + RegularGridInterpolator : interpolation on a regular or rectilinear grid + in arbitrary dimensions. + interpn : Multidimensional interpolation on regular grids (wraps + `RegularGridInterpolator` and `RectBivariateSpline`). + + Notes + ----- + The minimum number of data points required along the interpolation + axis is ``(k+1)**2``, with k=1 for linear, k=3 for cubic and k=5 for + quintic interpolation. + + The interpolator is constructed by `bisplrep`, with a smoothing factor + of 0. If more control over smoothing is needed, `bisplrep` should be + used directly. + + The coordinates of the data points to interpolate `xnew` and `ynew` + have to be sorted by ascending order. + `interp2d` is legacy and is not + recommended for use in new code. New code should use + `RegularGridInterpolator` instead. + + Examples + -------- + Construct a 2-D grid and interpolate on it: + + >>> import numpy as np + >>> from scipy import interpolate + >>> x = np.arange(-5.01, 5.01, 0.25) + >>> y = np.arange(-5.01, 5.01, 0.25) + >>> xx, yy = np.meshgrid(x, y) + >>> z = np.sin(xx**2+yy**2) + >>> f = interpolate.interp2d(x, y, z, kind='cubic') + + Now use the obtained interpolation function and plot the result: + + >>> import matplotlib.pyplot as plt + >>> xnew = np.arange(-5.01, 5.01, 1e-2) + >>> ynew = np.arange(-5.01, 5.01, 1e-2) + >>> znew = f(xnew, ynew) + >>> plt.plot(x, z[0, :], 'ro-', xnew, znew[0, :], 'b-') + >>> plt.show() + """ + + def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, + fill_value=None): + warnings.warn(dep_mesg, DeprecationWarning, stacklevel=2) + + x = ravel(x) + y = ravel(y) + z = asarray(z) + + rectangular_grid = (z.size == len(x) * len(y)) + if rectangular_grid: + if z.ndim == 2: + if z.shape != (len(y), len(x)): + raise ValueError("When on a regular grid with x.size = m " + "and y.size = n, if z.ndim == 2, then z " + "must have shape (n, m)") + if not np.all(x[1:] >= x[:-1]): + j = np.argsort(x) + x = x[j] + z = z[:, j] + if not np.all(y[1:] >= y[:-1]): + j = np.argsort(y) + y = y[j] + z = z[j, :] + z = ravel(z.T) + else: + z = ravel(z) + if len(x) != len(y): + raise ValueError( + "x and y must have equal lengths for non rectangular grid") + if len(z) != len(x): + raise ValueError( + "Invalid length for input z for non rectangular grid") + + interpolation_types = {'linear': 1, 'cubic': 3, 'quintic': 5} + try: + kx = ky = interpolation_types[kind] + except KeyError as e: + raise ValueError( + f"Unsupported interpolation type {repr(kind)}, must be " + f"either of {', '.join(map(repr, interpolation_types))}." + ) from e + + if not rectangular_grid: + # TODO: surfit is really not meant for interpolation! + self.tck = _fitpack_py.bisplrep(x, y, z, kx=kx, ky=ky, s=0.0) + else: + nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth( + x, y, z, None, None, None, None, + kx=kx, ky=ky, s=0.0) + self.tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], + kx, ky) + + self.bounds_error = bounds_error + self.fill_value = fill_value + self.x, self.y, self.z = (array(a, copy=copy) for a in (x, y, z)) + + self.x_min, self.x_max = np.amin(x), np.amax(x) + self.y_min, self.y_max = np.amin(y), np.amax(y) + + def __call__(self, x, y, dx=0, dy=0, assume_sorted=False): + """Interpolate the function. + + Parameters + ---------- + x : 1-D array + x-coordinates of the mesh on which to interpolate. + y : 1-D array + y-coordinates of the mesh on which to interpolate. + dx : int >= 0, < kx + Order of partial derivatives in x. + dy : int >= 0, < ky + Order of partial derivatives in y. + assume_sorted : bool, optional + If False, values of `x` and `y` can be in any order and they are + sorted first. + If True, `x` and `y` have to be arrays of monotonically + increasing values. + + Returns + ------- + z : 2-D array with shape (len(y), len(x)) + The interpolated values. + """ + warnings.warn(dep_mesg, DeprecationWarning, stacklevel=2) + + x = atleast_1d(x) + y = atleast_1d(y) + + if x.ndim != 1 or y.ndim != 1: + raise ValueError("x and y should both be 1-D arrays") + + if not assume_sorted: + x = np.sort(x, kind="mergesort") + y = np.sort(y, kind="mergesort") + + if self.bounds_error or self.fill_value is not None: + out_of_bounds_x = (x < self.x_min) | (x > self.x_max) + out_of_bounds_y = (y < self.y_min) | (y > self.y_max) + + any_out_of_bounds_x = np.any(out_of_bounds_x) + any_out_of_bounds_y = np.any(out_of_bounds_y) + + if self.bounds_error and (any_out_of_bounds_x or any_out_of_bounds_y): + raise ValueError( + f"Values out of range; x must be in {(self.x_min, self.x_max)!r}, " + f"y in {(self.y_min, self.y_max)!r}" + ) + + z = _fitpack_py.bisplev(x, y, self.tck, dx, dy) + z = atleast_2d(z) + z = transpose(z) + + if self.fill_value is not None: + if any_out_of_bounds_x: + z[:, out_of_bounds_x] = self.fill_value + if any_out_of_bounds_y: + z[out_of_bounds_y, :] = self.fill_value + + if len(z) == 1: + z = z[0] + return array(z) + + +def _check_broadcast_up_to(arr_from, shape_to, name): + """Helper to check that arr_from broadcasts up to shape_to""" + shape_from = arr_from.shape + if len(shape_to) >= len(shape_from): + for t, f in zip(shape_to[::-1], shape_from[::-1]): + if f != 1 and f != t: + break + else: # all checks pass, do the upcasting that we need later + if arr_from.size != 1 and arr_from.shape != shape_to: + arr_from = np.ones(shape_to, arr_from.dtype) * arr_from + return arr_from.ravel() + # at least one check failed + raise ValueError(f'{name} argument must be able to broadcast up ' + f'to shape {shape_to} but had shape {shape_from}') + + +def _do_extrapolate(fill_value): + """Helper to check if fill_value == "extrapolate" without warnings""" + return (isinstance(fill_value, str) and + fill_value == 'extrapolate') + + +class interp1d(_Interpolator1D): + """ + Interpolate a 1-D function. + + .. legacy:: class + + For a guide to the intended replacements for `interp1d` see + :ref:`tutorial-interpolate_1Dsection`. + + `x` and `y` are arrays of values used to approximate some function f: + ``y = f(x)``. This class returns a function whose call method uses + interpolation to find the value of new points. + + Parameters + ---------- + x : (npoints, ) array_like + A 1-D array of real values. + y : (..., npoints, ...) array_like + A N-D array of real values. The length of `y` along the interpolation + axis must be equal to the length of `x`. Use the ``axis`` parameter + to select correct axis. Unlike other interpolators, the default + interpolation axis is the last axis of `y`. + kind : str or int, optional + Specifies the kind of interpolation as a string or as an integer + specifying the order of the spline interpolator to use. + The string has to be one of 'linear', 'nearest', 'nearest-up', 'zero', + 'slinear', 'quadratic', 'cubic', 'previous', or 'next'. 'zero', + 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of + zeroth, first, second or third order; 'previous' and 'next' simply + return the previous or next value of the point; 'nearest-up' and + 'nearest' differ when interpolating half-integers (e.g. 0.5, 1.5) + in that 'nearest-up' rounds up and 'nearest' rounds down. Default + is 'linear'. + axis : int, optional + Axis in the ``y`` array corresponding to the x-coordinate values. Unlike + other interpolators, defaults to ``axis=-1``. + copy : bool, optional + If ``True``, the class makes internal copies of x and y. If ``False``, + references to ``x`` and ``y`` are used if possible. The default is to copy. + bounds_error : bool, optional + If True, a ValueError is raised any time interpolation is attempted on + a value outside of the range of x (where extrapolation is + necessary). If False, out of bounds values are assigned `fill_value`. + By default, an error is raised unless ``fill_value="extrapolate"``. + fill_value : array-like or (array-like, array_like) or "extrapolate", optional + - if a ndarray (or float), this value will be used to fill in for + requested points outside of the data range. If not provided, then + the default is NaN. The array-like must broadcast properly to the + dimensions of the non-interpolation axes. + - If a two-element tuple, then the first element is used as a + fill value for ``x_new < x[0]`` and the second element is used for + ``x_new > x[-1]``. Anything that is not a 2-element tuple (e.g., + list or ndarray, regardless of shape) is taken to be a single + array-like argument meant to be used for both bounds as + ``below, above = fill_value, fill_value``. Using a two-element tuple + or ndarray requires ``bounds_error=False``. + + .. versionadded:: 0.17.0 + - If "extrapolate", then points outside the data range will be + extrapolated. + + .. versionadded:: 0.17.0 + assume_sorted : bool, optional + If False, values of `x` can be in any order and they are sorted first. + If True, `x` has to be an array of monotonically increasing values. + + Attributes + ---------- + fill_value + + Methods + ------- + __call__ + + See Also + -------- + splrep, splev + Spline interpolation/smoothing based on FITPACK. + UnivariateSpline : An object-oriented wrapper of the FITPACK routines. + interp2d : 2-D interpolation + + Notes + ----- + Calling `interp1d` with NaNs present in input values results in + undefined behaviour. + + Input values `x` and `y` must be convertible to `float` values like + `int` or `float`. + + If the values in `x` are not unique, the resulting behavior is + undefined and specific to the choice of `kind`, i.e., changing + `kind` will change the behavior for duplicates. + + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy import interpolate + >>> x = np.arange(0, 10) + >>> y = np.exp(-x/3.0) + >>> f = interpolate.interp1d(x, y) + + >>> xnew = np.arange(0, 9, 0.1) + >>> ynew = f(xnew) # use interpolation function returned by `interp1d` + >>> plt.plot(x, y, 'o', xnew, ynew, '-') + >>> plt.show() + """ + + def __init__(self, x, y, kind='linear', axis=-1, + copy=True, bounds_error=None, fill_value=np.nan, + assume_sorted=False): + """ Initialize a 1-D linear interpolation class.""" + _Interpolator1D.__init__(self, x, y, axis=axis) + + self.bounds_error = bounds_error # used by fill_value setter + + # `copy` keyword semantics changed in NumPy 2.0, once that is + # the minimum version this can use `copy=None`. + self.copy = copy + if not copy: + self.copy = copy_if_needed + + if kind in ['zero', 'slinear', 'quadratic', 'cubic']: + order = {'zero': 0, 'slinear': 1, + 'quadratic': 2, 'cubic': 3}[kind] + kind = 'spline' + elif isinstance(kind, int): + order = kind + kind = 'spline' + elif kind not in ('linear', 'nearest', 'nearest-up', 'previous', + 'next'): + raise NotImplementedError("%s is unsupported: Use fitpack " + "routines for other types." % kind) + x = array(x, copy=self.copy) + y = array(y, copy=self.copy) + + if not assume_sorted: + ind = np.argsort(x, kind="mergesort") + x = x[ind] + y = np.take(y, ind, axis=axis) + + if x.ndim != 1: + raise ValueError("the x array must have exactly one dimension.") + if y.ndim == 0: + raise ValueError("the y array must have at least one dimension.") + + # Force-cast y to a floating-point type, if it's not yet one + if not issubclass(y.dtype.type, np.inexact): + y = y.astype(np.float64) + + # Backward compatibility + self.axis = axis % y.ndim + + # Interpolation goes internally along the first axis + self.y = y + self._y = self._reshape_yi(self.y) + self.x = x + del y, x # clean up namespace to prevent misuse; use attributes + self._kind = kind + + # Adjust to interpolation kind; store reference to *unbound* + # interpolation methods, in order to avoid circular references to self + # stored in the bound instance methods, and therefore delayed garbage + # collection. See: https://docs.python.org/reference/datamodel.html + if kind in ('linear', 'nearest', 'nearest-up', 'previous', 'next'): + # Make a "view" of the y array that is rotated to the interpolation + # axis. + minval = 1 + if kind == 'nearest': + # Do division before addition to prevent possible integer + # overflow + self._side = 'left' + self.x_bds = self.x / 2.0 + self.x_bds = self.x_bds[1:] + self.x_bds[:-1] + + self._call = self.__class__._call_nearest + elif kind == 'nearest-up': + # Do division before addition to prevent possible integer + # overflow + self._side = 'right' + self.x_bds = self.x / 2.0 + self.x_bds = self.x_bds[1:] + self.x_bds[:-1] + + self._call = self.__class__._call_nearest + elif kind == 'previous': + # Side for np.searchsorted and index for clipping + self._side = 'left' + self._ind = 0 + # Move x by one floating point value to the left + self._x_shift = np.nextafter(self.x, -np.inf) + self._call = self.__class__._call_previousnext + if _do_extrapolate(fill_value): + self._check_and_update_bounds_error_for_extrapolation() + # assume y is sorted by x ascending order here. + fill_value = (np.nan, np.take(self.y, -1, axis)) + elif kind == 'next': + self._side = 'right' + self._ind = 1 + # Move x by one floating point value to the right + self._x_shift = np.nextafter(self.x, np.inf) + self._call = self.__class__._call_previousnext + if _do_extrapolate(fill_value): + self._check_and_update_bounds_error_for_extrapolation() + # assume y is sorted by x ascending order here. + fill_value = (np.take(self.y, 0, axis), np.nan) + else: + # Check if we can delegate to numpy.interp (2x-10x faster). + np_dtypes = (np.dtype(np.float64), np.dtype(int)) + cond = self.x.dtype in np_dtypes and self.y.dtype in np_dtypes + cond = cond and self.y.ndim == 1 + cond = cond and not _do_extrapolate(fill_value) + + if cond: + self._call = self.__class__._call_linear_np + else: + self._call = self.__class__._call_linear + else: + minval = order + 1 + + rewrite_nan = False + xx, yy = self.x, self._y + if order > 1: + # Quadratic or cubic spline. If input contains even a single + # nan, then the output is all nans. We cannot just feed data + # with nans to make_interp_spline because it calls LAPACK. + # So, we make up a bogus x and y with no nans and use it + # to get the correct shape of the output, which we then fill + # with nans. + # For slinear or zero order spline, we just pass nans through. + mask = np.isnan(self.x) + if mask.any(): + sx = self.x[~mask] + if sx.size == 0: + raise ValueError("`x` array is all-nan") + xx = np.linspace(np.nanmin(self.x), + np.nanmax(self.x), + len(self.x)) + rewrite_nan = True + if np.isnan(self._y).any(): + yy = np.ones_like(self._y) + rewrite_nan = True + + self._spline = make_interp_spline(xx, yy, k=order, + check_finite=False) + if rewrite_nan: + self._call = self.__class__._call_nan_spline + else: + self._call = self.__class__._call_spline + + if len(self.x) < minval: + raise ValueError("x and y arrays must have at " + "least %d entries" % minval) + + self.fill_value = fill_value # calls the setter, can modify bounds_err + + @property + def fill_value(self): + """The fill value.""" + # backwards compat: mimic a public attribute + return self._fill_value_orig + + @fill_value.setter + def fill_value(self, fill_value): + # extrapolation only works for nearest neighbor and linear methods + if _do_extrapolate(fill_value): + self._check_and_update_bounds_error_for_extrapolation() + self._extrapolate = True + else: + broadcast_shape = (self.y.shape[:self.axis] + + self.y.shape[self.axis + 1:]) + if len(broadcast_shape) == 0: + broadcast_shape = (1,) + # it's either a pair (_below_range, _above_range) or a single value + # for both above and below range + if isinstance(fill_value, tuple) and len(fill_value) == 2: + below_above = [np.asarray(fill_value[0]), + np.asarray(fill_value[1])] + names = ('fill_value (below)', 'fill_value (above)') + for ii in range(2): + below_above[ii] = _check_broadcast_up_to( + below_above[ii], broadcast_shape, names[ii]) + else: + fill_value = np.asarray(fill_value) + below_above = [_check_broadcast_up_to( + fill_value, broadcast_shape, 'fill_value')] * 2 + self._fill_value_below, self._fill_value_above = below_above + self._extrapolate = False + if self.bounds_error is None: + self.bounds_error = True + # backwards compat: fill_value was a public attr; make it writeable + self._fill_value_orig = fill_value + + def _check_and_update_bounds_error_for_extrapolation(self): + if self.bounds_error: + raise ValueError("Cannot extrapolate and raise " + "at the same time.") + self.bounds_error = False + + def _call_linear_np(self, x_new): + # Note that out-of-bounds values are taken care of in self._evaluate + return np.interp(x_new, self.x, self.y) + + def _call_linear(self, x_new): + # 2. Find where in the original data, the values to interpolate + # would be inserted. + # Note: If x_new[n] == x[m], then m is returned by searchsorted. + x_new_indices = searchsorted(self.x, x_new) + + # 3. Clip x_new_indices so that they are within the range of + # self.x indices and at least 1. Removes mis-interpolation + # of x_new[n] = x[0] + x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int) + + # 4. Calculate the slope of regions that each x_new value falls in. + lo = x_new_indices - 1 + hi = x_new_indices + + x_lo = self.x[lo] + x_hi = self.x[hi] + y_lo = self._y[lo] + y_hi = self._y[hi] + + # Note that the following two expressions rely on the specifics of the + # broadcasting semantics. + slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None] + + # 5. Calculate the actual value for each entry in x_new. + y_new = slope*(x_new - x_lo)[:, None] + y_lo + + return y_new + + def _call_nearest(self, x_new): + """ Find nearest neighbor interpolated y_new = f(x_new).""" + + # 2. Find where in the averaged data the values to interpolate + # would be inserted. + # Note: use side='left' (right) to searchsorted() to define the + # halfway point to be nearest to the left (right) neighbor + x_new_indices = searchsorted(self.x_bds, x_new, side=self._side) + + # 3. Clip x_new_indices so that they are within the range of x indices. + x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp) + + # 4. Calculate the actual value for each entry in x_new. + y_new = self._y[x_new_indices] + + return y_new + + def _call_previousnext(self, x_new): + """Use previous/next neighbor of x_new, y_new = f(x_new).""" + + # 1. Get index of left/right value + x_new_indices = searchsorted(self._x_shift, x_new, side=self._side) + + # 2. Clip x_new_indices so that they are within the range of x indices. + x_new_indices = x_new_indices.clip(1-self._ind, + len(self.x)-self._ind).astype(intp) + + # 3. Calculate the actual value for each entry in x_new. + y_new = self._y[x_new_indices+self._ind-1] + + return y_new + + def _call_spline(self, x_new): + return self._spline(x_new) + + def _call_nan_spline(self, x_new): + out = self._spline(x_new) + out[...] = np.nan + return out + + def _evaluate(self, x_new): + # 1. Handle values in x_new that are outside of x. Throw error, + # or return a list of mask array indicating the outofbounds values. + # The behavior is set by the bounds_error variable. + x_new = asarray(x_new) + y_new = self._call(self, x_new) + if not self._extrapolate: + below_bounds, above_bounds = self._check_bounds(x_new) + if len(y_new) > 0: + # Note fill_value must be broadcast up to the proper size + # and flattened to work here + y_new[below_bounds] = self._fill_value_below + y_new[above_bounds] = self._fill_value_above + return y_new + + def _check_bounds(self, x_new): + """Check the inputs for being in the bounds of the interpolated data. + + Parameters + ---------- + x_new : array + + Returns + ------- + out_of_bounds : bool array + The mask on x_new of values that are out of the bounds. + """ + + # If self.bounds_error is True, we raise an error if any x_new values + # fall outside the range of x. Otherwise, we return an array indicating + # which values are outside the boundary region. + below_bounds = x_new < self.x[0] + above_bounds = x_new > self.x[-1] + + if self.bounds_error and below_bounds.any(): + below_bounds_value = x_new[np.argmax(below_bounds)] + raise ValueError(f"A value ({below_bounds_value}) in x_new is below " + f"the interpolation range's minimum value ({self.x[0]}).") + if self.bounds_error and above_bounds.any(): + above_bounds_value = x_new[np.argmax(above_bounds)] + raise ValueError(f"A value ({above_bounds_value}) in x_new is above " + f"the interpolation range's maximum value ({self.x[-1]}).") + + # !! Should we emit a warning if some values are out of bounds? + # !! matlab does not. + return below_bounds, above_bounds + + +class _PPolyBase: + """Base class for piecewise polynomials.""" + __slots__ = ('c', 'x', 'extrapolate', 'axis') + + def __init__(self, c, x, extrapolate=None, axis=0): + self.c = np.asarray(c) + self.x = np.ascontiguousarray(x, dtype=np.float64) + + if extrapolate is None: + extrapolate = True + elif extrapolate != 'periodic': + extrapolate = bool(extrapolate) + self.extrapolate = extrapolate + + if self.c.ndim < 2: + raise ValueError("Coefficients array must be at least " + "2-dimensional.") + + if not (0 <= axis < self.c.ndim - 1): + raise ValueError(f"axis={axis} must be between 0 and {self.c.ndim-1}") + + self.axis = axis + if axis != 0: + # move the interpolation axis to be the first one in self.c + # More specifically, the target shape for self.c is (k, m, ...), + # and axis !=0 means that we have c.shape (..., k, m, ...) + # ^ + # axis + # So we roll two of them. + self.c = np.moveaxis(self.c, axis+1, 0) + self.c = np.moveaxis(self.c, axis+1, 0) + + if self.x.ndim != 1: + raise ValueError("x must be 1-dimensional") + if self.x.size < 2: + raise ValueError("at least 2 breakpoints are needed") + if self.c.ndim < 2: + raise ValueError("c must have at least 2 dimensions") + if self.c.shape[0] == 0: + raise ValueError("polynomial must be at least of order 0") + if self.c.shape[1] != self.x.size-1: + raise ValueError("number of coefficients != len(x)-1") + dx = np.diff(self.x) + if not (np.all(dx >= 0) or np.all(dx <= 0)): + raise ValueError("`x` must be strictly increasing or decreasing.") + + dtype = self._get_dtype(self.c.dtype) + self.c = np.ascontiguousarray(self.c, dtype=dtype) + + def _get_dtype(self, dtype): + if np.issubdtype(dtype, np.complexfloating) \ + or np.issubdtype(self.c.dtype, np.complexfloating): + return np.complex128 + else: + return np.float64 + + @classmethod + def construct_fast(cls, c, x, extrapolate=None, axis=0): + """ + Construct the piecewise polynomial without making checks. + + Takes the same parameters as the constructor. Input arguments + ``c`` and ``x`` must be arrays of the correct shape and type. The + ``c`` array can only be of dtypes float and complex, and ``x`` + array must have dtype float. + """ + self = object.__new__(cls) + self.c = c + self.x = x + self.axis = axis + if extrapolate is None: + extrapolate = True + self.extrapolate = extrapolate + return self + + def _ensure_c_contiguous(self): + """ + c and x may be modified by the user. The Cython code expects + that they are C contiguous. + """ + if not self.x.flags.c_contiguous: + self.x = self.x.copy() + if not self.c.flags.c_contiguous: + self.c = self.c.copy() + + def extend(self, c, x): + """ + Add additional breakpoints and coefficients to the polynomial. + + Parameters + ---------- + c : ndarray, size (k, m, ...) + Additional coefficients for polynomials in intervals. Note that + the first additional interval will be formed using one of the + ``self.x`` end points. + x : ndarray, size (m,) + Additional breakpoints. Must be sorted in the same order as + ``self.x`` and either to the right or to the left of the current + breakpoints. + """ + + c = np.asarray(c) + x = np.asarray(x) + + if c.ndim < 2: + raise ValueError("invalid dimensions for c") + if x.ndim != 1: + raise ValueError("invalid dimensions for x") + if x.shape[0] != c.shape[1]: + raise ValueError(f"Shapes of x {x.shape} and c {c.shape} are incompatible") + if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim: + raise ValueError("Shapes of c {} and self.c {} are incompatible" + .format(c.shape, self.c.shape)) + + if c.size == 0: + return + + dx = np.diff(x) + if not (np.all(dx >= 0) or np.all(dx <= 0)): + raise ValueError("`x` is not sorted.") + + if self.x[-1] >= self.x[0]: + if not x[-1] >= x[0]: + raise ValueError("`x` is in the different order " + "than `self.x`.") + + if x[0] >= self.x[-1]: + action = 'append' + elif x[-1] <= self.x[0]: + action = 'prepend' + else: + raise ValueError("`x` is neither on the left or on the right " + "from `self.x`.") + else: + if not x[-1] <= x[0]: + raise ValueError("`x` is in the different order " + "than `self.x`.") + + if x[0] <= self.x[-1]: + action = 'append' + elif x[-1] >= self.x[0]: + action = 'prepend' + else: + raise ValueError("`x` is neither on the left or on the right " + "from `self.x`.") + + dtype = self._get_dtype(c.dtype) + + k2 = max(c.shape[0], self.c.shape[0]) + c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:], + dtype=dtype) + + if action == 'append': + c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c + c2[k2-c.shape[0]:, self.c.shape[1]:] = c + self.x = np.r_[self.x, x] + elif action == 'prepend': + c2[k2-self.c.shape[0]:, :c.shape[1]] = c + c2[k2-c.shape[0]:, c.shape[1]:] = self.c + self.x = np.r_[x, self.x] + + self.c = c2 + + def __call__(self, x, nu=0, extrapolate=None): + """ + Evaluate the piecewise polynomial or its derivative. + + Parameters + ---------- + x : array_like + Points to evaluate the interpolant at. + nu : int, optional + Order of derivative to evaluate. Must be non-negative. + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. + If None (default), use `self.extrapolate`. + + Returns + ------- + y : array_like + Interpolated values. Shape is determined by replacing + the interpolation axis in the original array with the shape of x. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals are considered half-open, + ``[a, b)``, except for the last interval which is closed + ``[a, b]``. + """ + if extrapolate is None: + extrapolate = self.extrapolate + x = np.asarray(x) + x_shape, x_ndim = x.shape, x.ndim + x = np.ascontiguousarray(x.ravel(), dtype=np.float64) + + # With periodic extrapolation we map x to the segment + # [self.x[0], self.x[-1]]. + if extrapolate == 'periodic': + x = self.x[0] + (x - self.x[0]) % (self.x[-1] - self.x[0]) + extrapolate = False + + out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype) + self._ensure_c_contiguous() + self._evaluate(x, nu, extrapolate, out) + out = out.reshape(x_shape + self.c.shape[2:]) + if self.axis != 0: + # transpose to move the calculated values to the interpolation axis + l = list(range(out.ndim)) + l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:] + out = out.transpose(l) + return out + + +class PPoly(_PPolyBase): + """ + Piecewise polynomial in terms of coefficients and breakpoints + + The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the + local power basis:: + + S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1)) + + where ``k`` is the degree of the polynomial. + + Parameters + ---------- + c : ndarray, shape (k, m, ...) + Polynomial coefficients, order `k` and `m` intervals. + x : ndarray, shape (m+1,) + Polynomial breakpoints. Must be sorted in either increasing or + decreasing order. + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. If 'periodic', + periodic extrapolation is used. Default is True. + axis : int, optional + Interpolation axis. Default is zero. + + Attributes + ---------- + x : ndarray + Breakpoints. + c : ndarray + Coefficients of the polynomials. They are reshaped + to a 3-D array with the last dimension representing + the trailing dimensions of the original coefficient array. + axis : int + Interpolation axis. + + Methods + ------- + __call__ + derivative + antiderivative + integrate + solve + roots + extend + from_spline + from_bernstein_basis + construct_fast + + See also + -------- + BPoly : piecewise polynomials in the Bernstein basis + + Notes + ----- + High-order polynomials in the power basis can be numerically + unstable. Precision problems can start to appear for orders + larger than 20-30. + """ + + def _evaluate(self, x, nu, extrapolate, out): + _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, x, nu, bool(extrapolate), out) + + def derivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the derivative. + + Parameters + ---------- + nu : int, optional + Order of derivative to evaluate. Default is 1, i.e., compute the + first derivative. If negative, the antiderivative is returned. + + Returns + ------- + pp : PPoly + Piecewise polynomial of order k2 = k - n representing the derivative + of this polynomial. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals are considered half-open, + ``[a, b)``, except for the last interval which is closed + ``[a, b]``. + """ + if nu < 0: + return self.antiderivative(-nu) + + # reduce order + if nu == 0: + c2 = self.c.copy() + else: + c2 = self.c[:-nu, :].copy() + + if c2.shape[0] == 0: + # derivative of order 0 is zero + c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) + + # multiply by the correct rising factorials + factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu) + c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)] + + # construct a compatible polynomial + return self.construct_fast(c2, self.x, self.extrapolate, self.axis) + + def antiderivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the antiderivative. + + Antiderivative is also the indefinite integral of the function, + and derivative is its inverse operation. + + Parameters + ---------- + nu : int, optional + Order of antiderivative to evaluate. Default is 1, i.e., compute + the first integral. If negative, the derivative is returned. + + Returns + ------- + pp : PPoly + Piecewise polynomial of order k2 = k + n representing + the antiderivative of this polynomial. + + Notes + ----- + The antiderivative returned by this function is continuous and + continuously differentiable to order n-1, up to floating point + rounding error. + + If antiderivative is computed and ``self.extrapolate='periodic'``, + it will be set to False for the returned instance. This is done because + the antiderivative is no longer periodic and its correct evaluation + outside of the initially given x interval is difficult. + """ + if nu <= 0: + return self.derivative(-nu) + + c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:], + dtype=self.c.dtype) + c[:-nu] = self.c + + # divide by the correct rising factorials + factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu) + c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] + + # fix continuity of added degrees of freedom + self._ensure_c_contiguous() + _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1), + self.x, nu - 1) + + if self.extrapolate == 'periodic': + extrapolate = False + else: + extrapolate = self.extrapolate + + # construct a compatible polynomial + return self.construct_fast(c, self.x, extrapolate, self.axis) + + def integrate(self, a, b, extrapolate=None): + """ + Compute a definite integral over a piecewise polynomial. + + Parameters + ---------- + a : float + Lower integration bound + b : float + Upper integration bound + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. + If None (default), use `self.extrapolate`. + + Returns + ------- + ig : array_like + Definite integral of the piecewise polynomial over [a, b] + """ + if extrapolate is None: + extrapolate = self.extrapolate + + # Swap integration bounds if needed + sign = 1 + if b < a: + a, b = b, a + sign = -1 + + range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype) + self._ensure_c_contiguous() + + # Compute the integral. + if extrapolate == 'periodic': + # Split the integral into the part over period (can be several + # of them) and the remaining part. + + xs, xe = self.x[0], self.x[-1] + period = xe - xs + interval = b - a + n_periods, left = divmod(interval, period) + + if n_periods > 0: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, xs, xe, False, out=range_int) + range_int *= n_periods + else: + range_int.fill(0) + + # Map a to [xs, xe], b is always a + left. + a = xs + (a - xs) % period + b = a + left + + # If b <= xe then we need to integrate over [a, b], otherwise + # over [a, xe] and from xs to what is remained. + remainder_int = np.empty_like(range_int) + if b <= xe: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, a, b, False, out=remainder_int) + range_int += remainder_int + else: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, a, xe, False, out=remainder_int) + range_int += remainder_int + + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, xs, xs + left + a - xe, False, out=remainder_int) + range_int += remainder_int + else: + _ppoly.integrate( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, a, b, bool(extrapolate), out=range_int) + + # Return + range_int *= sign + return range_int.reshape(self.c.shape[2:]) + + def solve(self, y=0., discontinuity=True, extrapolate=None): + """ + Find real solutions of the equation ``pp(x) == y``. + + Parameters + ---------- + y : float, optional + Right-hand side. Default is zero. + discontinuity : bool, optional + Whether to report sign changes across discontinuities at + breakpoints as roots. + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to return roots from the polynomial + extrapolated based on first and last intervals, 'periodic' works + the same as False. If None (default), use `self.extrapolate`. + + Returns + ------- + roots : ndarray + Roots of the polynomial(s). + + If the PPoly object describes multiple polynomials, the + return value is an object array whose each element is an + ndarray containing the roots. + + Notes + ----- + This routine works only on real-valued polynomials. + + If the piecewise polynomial contains sections that are + identically zero, the root list will contain the start point + of the corresponding interval, followed by a ``nan`` value. + + If the polynomial is discontinuous across a breakpoint, and + there is a sign change across the breakpoint, this is reported + if the `discont` parameter is True. + + Examples + -------- + + Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals + ``[-2, 1], [1, 2]``: + + >>> import numpy as np + >>> from scipy.interpolate import PPoly + >>> pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2]) + >>> pp.solve() + array([-1., 1.]) + """ + if extrapolate is None: + extrapolate = self.extrapolate + + self._ensure_c_contiguous() + + if np.issubdtype(self.c.dtype, np.complexfloating): + raise ValueError("Root finding is only for " + "real-valued polynomials") + + y = float(y) + r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, y, bool(discontinuity), + bool(extrapolate)) + if self.c.ndim == 2: + return r[0] + else: + r2 = np.empty(prod(self.c.shape[2:]), dtype=object) + # this for-loop is equivalent to ``r2[...] = r``, but that's broken + # in NumPy 1.6.0 + for ii, root in enumerate(r): + r2[ii] = root + + return r2.reshape(self.c.shape[2:]) + + def roots(self, discontinuity=True, extrapolate=None): + """ + Find real roots of the piecewise polynomial. + + Parameters + ---------- + discontinuity : bool, optional + Whether to report sign changes across discontinuities at + breakpoints as roots. + extrapolate : {bool, 'periodic', None}, optional + If bool, determines whether to return roots from the polynomial + extrapolated based on first and last intervals, 'periodic' works + the same as False. If None (default), use `self.extrapolate`. + + Returns + ------- + roots : ndarray + Roots of the polynomial(s). + + If the PPoly object describes multiple polynomials, the + return value is an object array whose each element is an + ndarray containing the roots. + + See Also + -------- + PPoly.solve + """ + return self.solve(0, discontinuity, extrapolate) + + @classmethod + def from_spline(cls, tck, extrapolate=None): + """ + Construct a piecewise polynomial from a spline + + Parameters + ---------- + tck + A spline, as returned by `splrep` or a BSpline object. + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + + Examples + -------- + Construct an interpolating spline and convert it to a `PPoly` instance + + >>> import numpy as np + >>> from scipy.interpolate import splrep, PPoly + >>> x = np.linspace(0, 1, 11) + >>> y = np.sin(2*np.pi*x) + >>> tck = splrep(x, y, s=0) + >>> p = PPoly.from_spline(tck) + >>> isinstance(p, PPoly) + True + + Note that this function only supports 1D splines out of the box. + + If the ``tck`` object represents a parametric spline (e.g. constructed + by `splprep` or a `BSpline` with ``c.ndim > 1``), you will need to loop + over the dimensions manually. + + >>> from scipy.interpolate import splprep, splev + >>> t = np.linspace(0, 1, 11) + >>> x = np.sin(2*np.pi*t) + >>> y = np.cos(2*np.pi*t) + >>> (t, c, k), u = splprep([x, y], s=0) + + Note that ``c`` is a list of two arrays of length 11. + + >>> unew = np.arange(0, 1.01, 0.01) + >>> out = splev(unew, (t, c, k)) + + To convert this spline to the power basis, we convert each + component of the list of b-spline coefficients, ``c``, into the + corresponding cubic polynomial. + + >>> polys = [PPoly.from_spline((t, cj, k)) for cj in c] + >>> polys[0].c.shape + (4, 14) + + Note that the coefficients of the polynomials `polys` are in the + power basis and their dimensions reflect just that: here 4 is the order + (degree+1), and 14 is the number of intervals---which is nothing but + the length of the knot array of the original `tck` minus one. + + Optionally, we can stack the components into a single `PPoly` along + the third dimension: + + >>> cc = np.dstack([p.c for p in polys]) # has shape = (4, 14, 2) + >>> poly = PPoly(cc, polys[0].x) + >>> np.allclose(poly(unew).T, # note the transpose to match `splev` + ... out, atol=1e-15) + True + + """ + if isinstance(tck, BSpline): + t, c, k = tck.tck + if extrapolate is None: + extrapolate = tck.extrapolate + else: + t, c, k = tck + + cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype) + for m in range(k, -1, -1): + y = _fitpack_py.splev(t[:-1], tck, der=m) + cvals[k - m, :] = y/spec.gamma(m+1) + + return cls.construct_fast(cvals, t, extrapolate) + + @classmethod + def from_bernstein_basis(cls, bp, extrapolate=None): + """ + Construct a piecewise polynomial in the power basis + from a polynomial in Bernstein basis. + + Parameters + ---------- + bp : BPoly + A Bernstein basis polynomial, as created by BPoly + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + """ + if not isinstance(bp, BPoly): + raise TypeError(".from_bernstein_basis only accepts BPoly instances. " + "Got %s instead." % type(bp)) + + dx = np.diff(bp.x) + k = bp.c.shape[0] - 1 # polynomial order + + rest = (None,)*(bp.c.ndim-2) + + c = np.zeros_like(bp.c) + for a in range(k+1): + factor = (-1)**a * comb(k, a) * bp.c[a] + for s in range(a, k+1): + val = comb(k-a, s-a) * (-1)**s + c[k-s] += factor * val / dx[(slice(None),)+rest]**s + + if extrapolate is None: + extrapolate = bp.extrapolate + + return cls.construct_fast(c, bp.x, extrapolate, bp.axis) + + +class BPoly(_PPolyBase): + """Piecewise polynomial in terms of coefficients and breakpoints. + + The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the + Bernstein polynomial basis:: + + S = sum(c[a, i] * b(a, k; x) for a in range(k+1)), + + where ``k`` is the degree of the polynomial, and:: + + b(a, k; x) = binom(k, a) * t**a * (1 - t)**(k - a), + + with ``t = (x - x[i]) / (x[i+1] - x[i])`` and ``binom`` is the binomial + coefficient. + + Parameters + ---------- + c : ndarray, shape (k, m, ...) + Polynomial coefficients, order `k` and `m` intervals + x : ndarray, shape (m+1,) + Polynomial breakpoints. Must be sorted in either increasing or + decreasing order. + extrapolate : bool, optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. If 'periodic', + periodic extrapolation is used. Default is True. + axis : int, optional + Interpolation axis. Default is zero. + + Attributes + ---------- + x : ndarray + Breakpoints. + c : ndarray + Coefficients of the polynomials. They are reshaped + to a 3-D array with the last dimension representing + the trailing dimensions of the original coefficient array. + axis : int + Interpolation axis. + + Methods + ------- + __call__ + extend + derivative + antiderivative + integrate + construct_fast + from_power_basis + from_derivatives + + See also + -------- + PPoly : piecewise polynomials in the power basis + + Notes + ----- + Properties of Bernstein polynomials are well documented in the literature, + see for example [1]_ [2]_ [3]_. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Bernstein_polynomial + + .. [2] Kenneth I. Joy, Bernstein polynomials, + http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf + + .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems, + vol 2011, article ID 829546, :doi:`10.1155/2011/829543`. + + Examples + -------- + >>> from scipy.interpolate import BPoly + >>> x = [0, 1] + >>> c = [[1], [2], [3]] + >>> bp = BPoly(c, x) + + This creates a 2nd order polynomial + + .. math:: + + B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3 + \\times b_{2, 2}(x) \\\\ + = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2 + + """ # noqa: E501 + + def _evaluate(self, x, nu, extrapolate, out): + _ppoly.evaluate_bernstein( + self.c.reshape(self.c.shape[0], self.c.shape[1], -1), + self.x, x, nu, bool(extrapolate), out) + + def derivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the derivative. + + Parameters + ---------- + nu : int, optional + Order of derivative to evaluate. Default is 1, i.e., compute the + first derivative. If negative, the antiderivative is returned. + + Returns + ------- + bp : BPoly + Piecewise polynomial of order k - nu representing the derivative of + this polynomial. + + """ + if nu < 0: + return self.antiderivative(-nu) + + if nu > 1: + bp = self + for k in range(nu): + bp = bp.derivative() + return bp + + # reduce order + if nu == 0: + c2 = self.c.copy() + else: + # For a polynomial + # B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x), + # we use the fact that + # b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ), + # which leads to + # B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1} + # + # finally, for an interval [y, y + dy] with dy != 1, + # we need to correct for an extra power of dy + + rest = (None,)*(self.c.ndim-2) + + k = self.c.shape[0] - 1 + dx = np.diff(self.x)[(None, slice(None))+rest] + c2 = k * np.diff(self.c, axis=0) / dx + + if c2.shape[0] == 0: + # derivative of order 0 is zero + c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) + + # construct a compatible polynomial + return self.construct_fast(c2, self.x, self.extrapolate, self.axis) + + def antiderivative(self, nu=1): + """ + Construct a new piecewise polynomial representing the antiderivative. + + Parameters + ---------- + nu : int, optional + Order of antiderivative to evaluate. Default is 1, i.e., compute + the first integral. If negative, the derivative is returned. + + Returns + ------- + bp : BPoly + Piecewise polynomial of order k + nu representing the + antiderivative of this polynomial. + + Notes + ----- + If antiderivative is computed and ``self.extrapolate='periodic'``, + it will be set to False for the returned instance. This is done because + the antiderivative is no longer periodic and its correct evaluation + outside of the initially given x interval is difficult. + """ + if nu <= 0: + return self.derivative(-nu) + + if nu > 1: + bp = self + for k in range(nu): + bp = bp.antiderivative() + return bp + + # Construct the indefinite integrals on individual intervals + c, x = self.c, self.x + k = c.shape[0] + c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype) + + c2[1:, ...] = np.cumsum(c, axis=0) / k + delta = x[1:] - x[:-1] + c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)] + + # Now fix continuity: on the very first interval, take the integration + # constant to be zero; on an interval [x_j, x_{j+1}) with j>0, + # the integration constant is then equal to the jump of the `bp` at x_j. + # The latter is given by the coefficient of B_{n+1, n+1} + # *on the previous interval* (other B. polynomials are zero at the + # breakpoint). Finally, use the fact that BPs form a partition of unity. + c2[:,1:] += np.cumsum(c2[k, :], axis=0)[:-1] + + if self.extrapolate == 'periodic': + extrapolate = False + else: + extrapolate = self.extrapolate + + return self.construct_fast(c2, x, extrapolate, axis=self.axis) + + def integrate(self, a, b, extrapolate=None): + """ + Compute a definite integral over a piecewise polynomial. + + Parameters + ---------- + a : float + Lower integration bound + b : float + Upper integration bound + extrapolate : {bool, 'periodic', None}, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. If 'periodic', periodic + extrapolation is used. If None (default), use `self.extrapolate`. + + Returns + ------- + array_like + Definite integral of the piecewise polynomial over [a, b] + + """ + # XXX: can probably use instead the fact that + # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1) + ib = self.antiderivative() + if extrapolate is None: + extrapolate = self.extrapolate + + # ib.extrapolate shouldn't be 'periodic', it is converted to + # False for 'periodic. in antiderivative() call. + if extrapolate != 'periodic': + ib.extrapolate = extrapolate + + if extrapolate == 'periodic': + # Split the integral into the part over period (can be several + # of them) and the remaining part. + + # For simplicity and clarity convert to a <= b case. + if a <= b: + sign = 1 + else: + a, b = b, a + sign = -1 + + xs, xe = self.x[0], self.x[-1] + period = xe - xs + interval = b - a + n_periods, left = divmod(interval, period) + res = n_periods * (ib(xe) - ib(xs)) + + # Map a and b to [xs, xe]. + a = xs + (a - xs) % period + b = a + left + + # If b <= xe then we need to integrate over [a, b], otherwise + # over [a, xe] and from xs to what is remained. + if b <= xe: + res += ib(b) - ib(a) + else: + res += ib(xe) - ib(a) + ib(xs + left + a - xe) - ib(xs) + + return sign * res + else: + return ib(b) - ib(a) + + def extend(self, c, x): + k = max(self.c.shape[0], c.shape[0]) + self.c = self._raise_degree(self.c, k - self.c.shape[0]) + c = self._raise_degree(c, k - c.shape[0]) + return _PPolyBase.extend(self, c, x) + extend.__doc__ = _PPolyBase.extend.__doc__ + + @classmethod + def from_power_basis(cls, pp, extrapolate=None): + """ + Construct a piecewise polynomial in Bernstein basis + from a power basis polynomial. + + Parameters + ---------- + pp : PPoly + A piecewise polynomial in the power basis + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + """ + if not isinstance(pp, PPoly): + raise TypeError(".from_power_basis only accepts PPoly instances. " + "Got %s instead." % type(pp)) + + dx = np.diff(pp.x) + k = pp.c.shape[0] - 1 # polynomial order + + rest = (None,)*(pp.c.ndim-2) + + c = np.zeros_like(pp.c) + for a in range(k+1): + factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a) + for j in range(k-a, k+1): + c[j] += factor * comb(j, k-a) + + if extrapolate is None: + extrapolate = pp.extrapolate + + return cls.construct_fast(c, pp.x, extrapolate, pp.axis) + + @classmethod + def from_derivatives(cls, xi, yi, orders=None, extrapolate=None): + """Construct a piecewise polynomial in the Bernstein basis, + compatible with the specified values and derivatives at breakpoints. + + Parameters + ---------- + xi : array_like + sorted 1-D array of x-coordinates + yi : array_like or list of array_likes + ``yi[i][j]`` is the ``j``\\ th derivative known at ``xi[i]`` + orders : None or int or array_like of ints. Default: None. + Specifies the degree of local polynomials. If not None, some + derivatives are ignored. + extrapolate : bool or 'periodic', optional + If bool, determines whether to extrapolate to out-of-bounds points + based on first and last intervals, or to return NaNs. + If 'periodic', periodic extrapolation is used. Default is True. + + Notes + ----- + If ``k`` derivatives are specified at a breakpoint ``x``, the + constructed polynomial is exactly ``k`` times continuously + differentiable at ``x``, unless the ``order`` is provided explicitly. + In the latter case, the smoothness of the polynomial at + the breakpoint is controlled by the ``order``. + + Deduces the number of derivatives to match at each end + from ``order`` and the number of derivatives available. If + possible it uses the same number of derivatives from + each end; if the number is odd it tries to take the + extra one from y2. In any case if not enough derivatives + are available at one end or another it draws enough to + make up the total from the other end. + + If the order is too high and not enough derivatives are available, + an exception is raised. + + Examples + -------- + + >>> from scipy.interpolate import BPoly + >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]]) + + Creates a polynomial `f(x)` of degree 3, defined on `[0, 1]` + such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4` + + >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]]) + + Creates a piecewise polynomial `f(x)`, such that + `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`. + Based on the number of derivatives provided, the order of the + local polynomials is 2 on `[0, 1]` and 1 on `[1, 2]`. + Notice that no restriction is imposed on the derivatives at + ``x = 1`` and ``x = 2``. + + Indeed, the explicit form of the polynomial is:: + + f(x) = | x * (1 - x), 0 <= x < 1 + | 2 * (x - 1), 1 <= x <= 2 + + So that f'(1-0) = -1 and f'(1+0) = 2 + + """ + xi = np.asarray(xi) + if len(xi) != len(yi): + raise ValueError("xi and yi need to have the same length") + if np.any(xi[1:] - xi[:1] <= 0): + raise ValueError("x coordinates are not in increasing order") + + # number of intervals + m = len(xi) - 1 + + # global poly order is k-1, local orders are <=k and can vary + try: + k = max(len(yi[i]) + len(yi[i+1]) for i in range(m)) + except TypeError as e: + raise ValueError( + "Using a 1-D array for y? Please .reshape(-1, 1)." + ) from e + + if orders is None: + orders = [None] * m + else: + if isinstance(orders, (int, np.integer)): + orders = [orders] * m + k = max(k, max(orders)) + + if any(o <= 0 for o in orders): + raise ValueError("Orders must be positive.") + + c = [] + for i in range(m): + y1, y2 = yi[i], yi[i+1] + if orders[i] is None: + n1, n2 = len(y1), len(y2) + else: + n = orders[i]+1 + n1 = min(n//2, len(y1)) + n2 = min(n - n1, len(y2)) + n1 = min(n - n2, len(y2)) + if n1+n2 != n: + mesg = ("Point %g has %d derivatives, point %g" + " has %d derivatives, but order %d requested" % ( + xi[i], len(y1), xi[i+1], len(y2), orders[i])) + raise ValueError(mesg) + + if not (n1 <= len(y1) and n2 <= len(y2)): + raise ValueError("`order` input incompatible with" + " length y1 or y2.") + + b = BPoly._construct_from_derivatives(xi[i], xi[i+1], + y1[:n1], y2[:n2]) + if len(b) < k: + b = BPoly._raise_degree(b, k - len(b)) + c.append(b) + + c = np.asarray(c) + return cls(c.swapaxes(0, 1), xi, extrapolate) + + @staticmethod + def _construct_from_derivatives(xa, xb, ya, yb): + r"""Compute the coefficients of a polynomial in the Bernstein basis + given the values and derivatives at the edges. + + Return the coefficients of a polynomial in the Bernstein basis + defined on ``[xa, xb]`` and having the values and derivatives at the + endpoints `xa` and `xb` as specified by `ya` and `yb`. + The polynomial constructed is of the minimal possible degree, i.e., + if the lengths of `ya` and `yb` are `na` and `nb`, the degree + of the polynomial is ``na + nb - 1``. + + Parameters + ---------- + xa : float + Left-hand end point of the interval + xb : float + Right-hand end point of the interval + ya : array_like + Derivatives at `xa`. ``ya[0]`` is the value of the function, and + ``ya[i]`` for ``i > 0`` is the value of the ``i``\ th derivative. + yb : array_like + Derivatives at `xb`. + + Returns + ------- + array + coefficient array of a polynomial having specified derivatives + + Notes + ----- + This uses several facts from life of Bernstein basis functions. + First of all, + + .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1}) + + If B(x) is a linear combination of the form + + .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n}, + + then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}. + Iterating the latter one, one finds for the q-th derivative + + .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q}, + + with + + .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a} + + This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and + `c_q` are found one by one by iterating `q = 0, ..., na`. + + At ``x = xb`` it's the same with ``a = n - q``. + + """ + ya, yb = np.asarray(ya), np.asarray(yb) + if ya.shape[1:] != yb.shape[1:]: + raise ValueError('Shapes of ya {} and yb {} are incompatible' + .format(ya.shape, yb.shape)) + + dta, dtb = ya.dtype, yb.dtype + if (np.issubdtype(dta, np.complexfloating) or + np.issubdtype(dtb, np.complexfloating)): + dt = np.complex128 + else: + dt = np.float64 + + na, nb = len(ya), len(yb) + n = na + nb + + c = np.empty((na+nb,) + ya.shape[1:], dtype=dt) + + # compute coefficients of a polynomial degree na+nb-1 + # walk left-to-right + for q in range(0, na): + c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q + for j in range(0, q): + c[q] -= (-1)**(j+q) * comb(q, j) * c[j] + + # now walk right-to-left + for q in range(0, nb): + c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q + for j in range(0, q): + c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j] + + return c + + @staticmethod + def _raise_degree(c, d): + r"""Raise a degree of a polynomial in the Bernstein basis. + + Given the coefficients of a polynomial degree `k`, return (the + coefficients of) the equivalent polynomial of degree `k+d`. + + Parameters + ---------- + c : array_like + coefficient array, 1-D + d : integer + + Returns + ------- + array + coefficient array, 1-D array of length `c.shape[0] + d` + + Notes + ----- + This uses the fact that a Bernstein polynomial `b_{a, k}` can be + identically represented as a linear combination of polynomials of + a higher degree `k+d`: + + .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \ + comb(d, j) / comb(k+d, a+j) + + """ + if d == 0: + return c + + k = c.shape[0] - 1 + out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype) + + for a in range(c.shape[0]): + f = c[a] * comb(k, a) + for j in range(d+1): + out[a+j] += f * comb(d, j) / comb(k+d, a+j) + return out + + +class NdPPoly: + """ + Piecewise tensor product polynomial + + The value at point ``xp = (x', y', z', ...)`` is evaluated by first + computing the interval indices `i` such that:: + + x[0][i[0]] <= x' < x[0][i[0]+1] + x[1][i[1]] <= y' < x[1][i[1]+1] + ... + + and then computing:: + + S = sum(c[k0-m0-1,...,kn-mn-1,i[0],...,i[n]] + * (xp[0] - x[0][i[0]])**m0 + * ... + * (xp[n] - x[n][i[n]])**mn + for m0 in range(k[0]+1) + ... + for mn in range(k[n]+1)) + + where ``k[j]`` is the degree of the polynomial in dimension j. This + representation is the piecewise multivariate power basis. + + Parameters + ---------- + c : ndarray, shape (k0, ..., kn, m0, ..., mn, ...) + Polynomial coefficients, with polynomial order `kj` and + `mj+1` intervals for each dimension `j`. + x : ndim-tuple of ndarrays, shapes (mj+1,) + Polynomial breakpoints for each dimension. These must be + sorted in increasing order. + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. Default: True. + + Attributes + ---------- + x : tuple of ndarrays + Breakpoints. + c : ndarray + Coefficients of the polynomials. + + Methods + ------- + __call__ + derivative + antiderivative + integrate + integrate_1d + construct_fast + + See also + -------- + PPoly : piecewise polynomials in 1D + + Notes + ----- + High-order polynomials in the power basis can be numerically + unstable. + + """ + + def __init__(self, c, x, extrapolate=None): + self.x = tuple(np.ascontiguousarray(v, dtype=np.float64) for v in x) + self.c = np.asarray(c) + if extrapolate is None: + extrapolate = True + self.extrapolate = bool(extrapolate) + + ndim = len(self.x) + if any(v.ndim != 1 for v in self.x): + raise ValueError("x arrays must all be 1-dimensional") + if any(v.size < 2 for v in self.x): + raise ValueError("x arrays must all contain at least 2 points") + if c.ndim < 2*ndim: + raise ValueError("c must have at least 2*len(x) dimensions") + if any(np.any(v[1:] - v[:-1] < 0) for v in self.x): + raise ValueError("x-coordinates are not in increasing order") + if any(a != b.size - 1 for a, b in zip(c.shape[ndim:2*ndim], self.x)): + raise ValueError("x and c do not agree on the number of intervals") + + dtype = self._get_dtype(self.c.dtype) + self.c = np.ascontiguousarray(self.c, dtype=dtype) + + @classmethod + def construct_fast(cls, c, x, extrapolate=None): + """ + Construct the piecewise polynomial without making checks. + + Takes the same parameters as the constructor. Input arguments + ``c`` and ``x`` must be arrays of the correct shape and type. The + ``c`` array can only be of dtypes float and complex, and ``x`` + array must have dtype float. + + """ + self = object.__new__(cls) + self.c = c + self.x = x + if extrapolate is None: + extrapolate = True + self.extrapolate = extrapolate + return self + + def _get_dtype(self, dtype): + if np.issubdtype(dtype, np.complexfloating) \ + or np.issubdtype(self.c.dtype, np.complexfloating): + return np.complex128 + else: + return np.float64 + + def _ensure_c_contiguous(self): + if not self.c.flags.c_contiguous: + self.c = self.c.copy() + if not isinstance(self.x, tuple): + self.x = tuple(self.x) + + def __call__(self, x, nu=None, extrapolate=None): + """ + Evaluate the piecewise polynomial or its derivative + + Parameters + ---------- + x : array-like + Points to evaluate the interpolant at. + nu : tuple, optional + Orders of derivatives to evaluate. Each must be non-negative. + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. + + Returns + ------- + y : array-like + Interpolated values. Shape is determined by replacing + the interpolation axis in the original array with the shape of x. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals are considered half-open, + ``[a, b)``, except for the last interval which is closed + ``[a, b]``. + + """ + if extrapolate is None: + extrapolate = self.extrapolate + else: + extrapolate = bool(extrapolate) + + ndim = len(self.x) + + x = _ndim_coords_from_arrays(x) + x_shape = x.shape + x = np.ascontiguousarray(x.reshape(-1, x.shape[-1]), dtype=np.float64) + + if nu is None: + nu = np.zeros((ndim,), dtype=np.intc) + else: + nu = np.asarray(nu, dtype=np.intc) + if nu.ndim != 1 or nu.shape[0] != ndim: + raise ValueError("invalid number of derivative orders nu") + + dim1 = prod(self.c.shape[:ndim]) + dim2 = prod(self.c.shape[ndim:2*ndim]) + dim3 = prod(self.c.shape[2*ndim:]) + ks = np.array(self.c.shape[:ndim], dtype=np.intc) + + out = np.empty((x.shape[0], dim3), dtype=self.c.dtype) + self._ensure_c_contiguous() + + _ppoly.evaluate_nd(self.c.reshape(dim1, dim2, dim3), + self.x, + ks, + x, + nu, + bool(extrapolate), + out) + + return out.reshape(x_shape[:-1] + self.c.shape[2*ndim:]) + + def _derivative_inplace(self, nu, axis): + """ + Compute 1-D derivative along a selected dimension in-place + May result to non-contiguous c array. + """ + if nu < 0: + return self._antiderivative_inplace(-nu, axis) + + ndim = len(self.x) + axis = axis % ndim + + # reduce order + if nu == 0: + # noop + return + else: + sl = [slice(None)]*ndim + sl[axis] = slice(None, -nu, None) + c2 = self.c[tuple(sl)] + + if c2.shape[axis] == 0: + # derivative of order 0 is zero + shp = list(c2.shape) + shp[axis] = 1 + c2 = np.zeros(shp, dtype=c2.dtype) + + # multiply by the correct rising factorials + factor = spec.poch(np.arange(c2.shape[axis], 0, -1), nu) + sl = [None]*c2.ndim + sl[axis] = slice(None) + c2 *= factor[tuple(sl)] + + self.c = c2 + + def _antiderivative_inplace(self, nu, axis): + """ + Compute 1-D antiderivative along a selected dimension + May result to non-contiguous c array. + """ + if nu <= 0: + return self._derivative_inplace(-nu, axis) + + ndim = len(self.x) + axis = axis % ndim + + perm = list(range(ndim)) + perm[0], perm[axis] = perm[axis], perm[0] + perm = perm + list(range(ndim, self.c.ndim)) + + c = self.c.transpose(perm) + + c2 = np.zeros((c.shape[0] + nu,) + c.shape[1:], + dtype=c.dtype) + c2[:-nu] = c + + # divide by the correct rising factorials + factor = spec.poch(np.arange(c.shape[0], 0, -1), nu) + c2[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] + + # fix continuity of added degrees of freedom + perm2 = list(range(c2.ndim)) + perm2[1], perm2[ndim+axis] = perm2[ndim+axis], perm2[1] + + c2 = c2.transpose(perm2) + c2 = c2.copy() + _ppoly.fix_continuity(c2.reshape(c2.shape[0], c2.shape[1], -1), + self.x[axis], nu-1) + + c2 = c2.transpose(perm2) + c2 = c2.transpose(perm) + + # Done + self.c = c2 + + def derivative(self, nu): + """ + Construct a new piecewise polynomial representing the derivative. + + Parameters + ---------- + nu : ndim-tuple of int + Order of derivatives to evaluate for each dimension. + If negative, the antiderivative is returned. + + Returns + ------- + pp : NdPPoly + Piecewise polynomial of orders (k[0] - nu[0], ..., k[n] - nu[n]) + representing the derivative of this polynomial. + + Notes + ----- + Derivatives are evaluated piecewise for each polynomial + segment, even if the polynomial is not differentiable at the + breakpoints. The polynomial intervals in each dimension are + considered half-open, ``[a, b)``, except for the last interval + which is closed ``[a, b]``. + + """ + p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) + + for axis, n in enumerate(nu): + p._derivative_inplace(n, axis) + + p._ensure_c_contiguous() + return p + + def antiderivative(self, nu): + """ + Construct a new piecewise polynomial representing the antiderivative. + + Antiderivative is also the indefinite integral of the function, + and derivative is its inverse operation. + + Parameters + ---------- + nu : ndim-tuple of int + Order of derivatives to evaluate for each dimension. + If negative, the derivative is returned. + + Returns + ------- + pp : PPoly + Piecewise polynomial of order k2 = k + n representing + the antiderivative of this polynomial. + + Notes + ----- + The antiderivative returned by this function is continuous and + continuously differentiable to order n-1, up to floating point + rounding error. + + """ + p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) + + for axis, n in enumerate(nu): + p._antiderivative_inplace(n, axis) + + p._ensure_c_contiguous() + return p + + def integrate_1d(self, a, b, axis, extrapolate=None): + r""" + Compute NdPPoly representation for one dimensional definite integral + + The result is a piecewise polynomial representing the integral: + + .. math:: + + p(y, z, ...) = \int_a^b dx\, p(x, y, z, ...) + + where the dimension integrated over is specified with the + `axis` parameter. + + Parameters + ---------- + a, b : float + Lower and upper bound for integration. + axis : int + Dimension over which to compute the 1-D integrals + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. + + Returns + ------- + ig : NdPPoly or array-like + Definite integral of the piecewise polynomial over [a, b]. + If the polynomial was 1D, an array is returned, + otherwise, an NdPPoly object. + + """ + if extrapolate is None: + extrapolate = self.extrapolate + else: + extrapolate = bool(extrapolate) + + ndim = len(self.x) + axis = int(axis) % ndim + + # reuse 1-D integration routines + c = self.c + swap = list(range(c.ndim)) + swap.insert(0, swap[axis]) + del swap[axis + 1] + swap.insert(1, swap[ndim + axis]) + del swap[ndim + axis + 1] + + c = c.transpose(swap) + p = PPoly.construct_fast(c.reshape(c.shape[0], c.shape[1], -1), + self.x[axis], + extrapolate=extrapolate) + out = p.integrate(a, b, extrapolate=extrapolate) + + # Construct result + if ndim == 1: + return out.reshape(c.shape[2:]) + else: + c = out.reshape(c.shape[2:]) + x = self.x[:axis] + self.x[axis+1:] + return self.construct_fast(c, x, extrapolate=extrapolate) + + def integrate(self, ranges, extrapolate=None): + """ + Compute a definite integral over a piecewise polynomial. + + Parameters + ---------- + ranges : ndim-tuple of 2-tuples float + Sequence of lower and upper bounds for each dimension, + ``[(a[0], b[0]), ..., (a[ndim-1], b[ndim-1])]`` + extrapolate : bool, optional + Whether to extrapolate to out-of-bounds points based on first + and last intervals, or to return NaNs. + + Returns + ------- + ig : array_like + Definite integral of the piecewise polynomial over + [a[0], b[0]] x ... x [a[ndim-1], b[ndim-1]] + + """ + + ndim = len(self.x) + + if extrapolate is None: + extrapolate = self.extrapolate + else: + extrapolate = bool(extrapolate) + + if not hasattr(ranges, '__len__') or len(ranges) != ndim: + raise ValueError("Range not a sequence of correct length") + + self._ensure_c_contiguous() + + # Reuse 1D integration routine + c = self.c + for n, (a, b) in enumerate(ranges): + swap = list(range(c.ndim)) + swap.insert(1, swap[ndim - n]) + del swap[ndim - n + 1] + + c = c.transpose(swap) + + p = PPoly.construct_fast(c, self.x[n], extrapolate=extrapolate) + out = p.integrate(a, b, extrapolate=extrapolate) + c = out.reshape(c.shape[2:]) + + return c diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_pade.py b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_pade.py new file mode 100644 index 0000000000000000000000000000000000000000..387ef11dde5d3ace8a15324058c10fa31899c92c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_pade.py @@ -0,0 +1,67 @@ +from numpy import zeros, asarray, eye, poly1d, hstack, r_ +from scipy import linalg + +__all__ = ["pade"] + +def pade(an, m, n=None): + """ + Return Pade approximation to a polynomial as the ratio of two polynomials. + + Parameters + ---------- + an : (N,) array_like + Taylor series coefficients. + m : int + The order of the returned approximating polynomial `q`. + n : int, optional + The order of the returned approximating polynomial `p`. By default, + the order is ``len(an)-1-m``. + + Returns + ------- + p, q : Polynomial class + The Pade approximation of the polynomial defined by `an` is + ``p(x)/q(x)``. + + Examples + -------- + >>> import numpy as np + >>> from scipy.interpolate import pade + >>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0] + >>> p, q = pade(e_exp, 2) + + >>> e_exp.reverse() + >>> e_poly = np.poly1d(e_exp) + + Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)`` + + >>> e_poly(1) + 2.7166666666666668 + + >>> p(1)/q(1) + 2.7179487179487181 + + """ + an = asarray(an) + if n is None: + n = len(an) - 1 - m + if n < 0: + raise ValueError("Order of q must be smaller than len(an)-1.") + if n < 0: + raise ValueError("Order of p must be greater than 0.") + N = m + n + if N > len(an)-1: + raise ValueError("Order of q+p must be smaller than len(an).") + an = an[:N+1] + Akj = eye(N+1, n+1, dtype=an.dtype) + Bkj = zeros((N+1, m), dtype=an.dtype) + for row in range(1, m+1): + Bkj[row,:row] = -(an[:row])[::-1] + for row in range(m+1, N+1): + Bkj[row,:] = -(an[row-m:row])[::-1] + C = hstack((Akj, Bkj)) + pq = linalg.solve(C, an) + p = pq[:n+1] + q = r_[1.0, pq[n+1:]] + return poly1d(p[::-1]), poly1d(q[::-1]) + diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_ppoly.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_ppoly.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d7e6dc6fe7e7a2a5b8b47df5ea2137fcbe52399f Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_ppoly.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f263c29ee3af68162a16a451be60848110a31552 Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py new file mode 100644 index 0000000000000000000000000000000000000000..c4848053e4d9791144483a213fe6040ef214c1e3 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/fitpack2.py @@ -0,0 +1,38 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BivariateSpline', + 'InterpolatedUnivariateSpline', + 'LSQBivariateSpline', + 'LSQSphereBivariateSpline', + 'LSQUnivariateSpline', + 'RectBivariateSpline', + 'RectSphereBivariateSpline', + 'SmoothBivariateSpline', + 'SmoothSphereBivariateSpline', + 'SphereBivariateSpline', + 'UnivariateSpline', + 'array', + 'concatenate', + 'dfitpack', + 'dfitpack_int', + 'diff', + 'ones', + 'ravel', + 'zeros', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="fitpack2", + private_modules=["_fitpack2"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/interpnd.cpython-310-x86_64-linux-gnu.so b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/interpnd.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1b8adc9819fc31d9adc2b8c814382d562f50e7ab Binary files /dev/null and b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/interpnd.cpython-310-x86_64-linux-gnu.so differ diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/interpolate.py b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/interpolate.py new file mode 100644 index 0000000000000000000000000000000000000000..3c6ae3398fa036a923ab7ed0ddaf63c2d73fe559 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/interpolate.py @@ -0,0 +1,44 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BPoly', + 'BSpline', + 'NdPPoly', + 'PPoly', + 'RectBivariateSpline', + 'RegularGridInterpolator', + 'array', + 'asarray', + 'atleast_1d', + 'atleast_2d', + 'comb', + 'dfitpack', + 'interp1d', + 'interp2d', + 'interpn', + 'intp', + 'itertools', + 'lagrange', + 'make_interp_spline', + 'poly1d', + 'prod', + 'ravel', + 'searchsorted', + 'spec', + 'transpose', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="interpolate", + private_modules=["_interpolate", "fitpack2", "_rgi"], + all=__all__, attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/polyint.py b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/polyint.py new file mode 100644 index 0000000000000000000000000000000000000000..dbdae2e90934e5b2c351a7add76d132413e47ee2 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/interpolate/polyint.py @@ -0,0 +1,26 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.interpolate` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'BarycentricInterpolator', + 'KroghInterpolator', + 'approximate_taylor_polynomial', + 'barycentric_interpolate', + 'factorial', + 'float_factorial', + 'krogh_interpolate', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="interpolate", module="polyint", + private_modules=["_polyint"], all=__all__, + attribute=name) diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/optimize.pxd b/env-llmeval/lib/python3.10/site-packages/scipy/optimize.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2402eeb020d34ad8b82e287e32545423911ff66c --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/optimize.pxd @@ -0,0 +1 @@ +from .optimize cimport cython_optimize diff --git a/env-llmeval/lib/python3.10/site-packages/scipy/special.pxd b/env-llmeval/lib/python3.10/site-packages/scipy/special.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1daa9fb379572aac4bc9b6d74330a18c5c52bf79 --- /dev/null +++ b/env-llmeval/lib/python3.10/site-packages/scipy/special.pxd @@ -0,0 +1 @@ +from scipy.special cimport cython_special