applied-ai-018 commited on
Commit
c92a408
·
verified ·
1 Parent(s): 24f0ed7

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__init__.py +0 -0
  2. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/_async_client.py +0 -0
  5. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__init__.py +132 -0
  6. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/base.py +149 -0
  7. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_text.py +105 -0
  8. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/summarization.py +46 -0
  9. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_generation.py +139 -0
  10. llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/visual_question_answering.py +53 -0
  11. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py +128 -0
  12. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py +397 -0
  13. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py +66 -0
  14. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_fixes.py +94 -0
  15. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_git_credential.py +121 -0
  16. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_http.py +319 -0
  17. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py +52 -0
  18. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_paths.py +130 -0
  19. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_subprocess.py +143 -0
  20. llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py +118 -0
  21. llmeval-env/lib/python3.10/site-packages/numexpr-2.10.0.dist-info/LICENSE.txt +21 -0
  22. llmeval-env/lib/python3.10/site-packages/scipy/cluster/__pycache__/__init__.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/scipy/cluster/__pycache__/vq.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/scipy/datasets/__init__.py +90 -0
  28. llmeval-env/lib/python3.10/site-packages/scipy/datasets/_download_all.py +57 -0
  29. llmeval-env/lib/python3.10/site-packages/scipy/datasets/_fetchers.py +220 -0
  30. llmeval-env/lib/python3.10/site-packages/scipy/datasets/_registry.py +26 -0
  31. llmeval-env/lib/python3.10/site-packages/scipy/datasets/_utils.py +81 -0
  32. llmeval-env/lib/python3.10/site-packages/scipy/signal/_arraytools.py +264 -0
  33. llmeval-env/lib/python3.10/site-packages/scipy/signal/_czt.py +575 -0
  34. llmeval-env/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py +1301 -0
  35. llmeval-env/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py +533 -0
  36. llmeval-env/lib/python3.10/site-packages/scipy/signal/_ltisys.py +0 -0
  37. llmeval-env/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py +139 -0
  38. llmeval-env/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py +357 -0
  39. llmeval-env/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py +1676 -0
  40. llmeval-env/lib/python3.10/site-packages/scipy/signal/_signaltools.py +0 -0
  41. llmeval-env/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so +0 -0
  42. llmeval-env/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so +0 -0
  43. llmeval-env/lib/python3.10/site-packages/scipy/signal/_upfirdn.py +216 -0
  44. llmeval-env/lib/python3.10/site-packages/scipy/signal/_upfirdn_apply.cpython-310-x86_64-linux-gnu.so +0 -0
  45. llmeval-env/lib/python3.10/site-packages/scipy/signal/_waveforms.py +672 -0
  46. llmeval-env/lib/python3.10/site-packages/scipy/signal/_wavelets.py +556 -0
  47. llmeval-env/lib/python3.10/site-packages/scipy/signal/bsplines.py +23 -0
  48. llmeval-env/lib/python3.10/site-packages/scipy/signal/filter_design.py +34 -0
  49. llmeval-env/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py +22 -0
  50. llmeval-env/lib/python3.10/site-packages/scipy/signal/lti_conversion.py +21 -0
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (209 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-310.pyc ADDED
Binary file (102 kB). View file
 
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/_async_client.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/__init__.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is auto-generated by `utils/generate_inference_types.py`.
2
+ # Do not modify it manually.
3
+ #
4
+ # ruff: noqa: F401
5
+
6
+ from .audio_classification import (
7
+ AudioClassificationInput,
8
+ AudioClassificationOutputElement,
9
+ AudioClassificationParameters,
10
+ )
11
+ from .audio_to_audio import AudioToAudioInput, AudioToAudioOutputElement
12
+ from .automatic_speech_recognition import (
13
+ AutomaticSpeechRecognitionGenerationParameters,
14
+ AutomaticSpeechRecognitionInput,
15
+ AutomaticSpeechRecognitionOutput,
16
+ AutomaticSpeechRecognitionOutputChunk,
17
+ AutomaticSpeechRecognitionParameters,
18
+ )
19
+ from .base import BaseInferenceType
20
+ from .chat_completion import (
21
+ ChatCompletionInput,
22
+ ChatCompletionInputFunctionDefinition,
23
+ ChatCompletionInputMessage,
24
+ ChatCompletionInputTool,
25
+ ChatCompletionInputToolCall,
26
+ ChatCompletionInputToolTypeClass,
27
+ ChatCompletionOutput,
28
+ ChatCompletionOutputComplete,
29
+ ChatCompletionOutputFunctionDefinition,
30
+ ChatCompletionOutputLogprob,
31
+ ChatCompletionOutputLogprobs,
32
+ ChatCompletionOutputMessage,
33
+ ChatCompletionOutputToolCall,
34
+ ChatCompletionOutputTopLogprob,
35
+ ChatCompletionOutputUsage,
36
+ ChatCompletionStreamOutput,
37
+ ChatCompletionStreamOutputChoice,
38
+ ChatCompletionStreamOutputDelta,
39
+ ChatCompletionStreamOutputDeltaToolCall,
40
+ ChatCompletionStreamOutputFunction,
41
+ ChatCompletionStreamOutputLogprob,
42
+ ChatCompletionStreamOutputLogprobs,
43
+ ChatCompletionStreamOutputTopLogprob,
44
+ )
45
+ from .depth_estimation import DepthEstimationInput, DepthEstimationOutput
46
+ from .document_question_answering import (
47
+ DocumentQuestionAnsweringInput,
48
+ DocumentQuestionAnsweringInputData,
49
+ DocumentQuestionAnsweringOutputElement,
50
+ DocumentQuestionAnsweringParameters,
51
+ )
52
+ from .feature_extraction import FeatureExtractionInput
53
+ from .fill_mask import FillMaskInput, FillMaskOutputElement, FillMaskParameters
54
+ from .image_classification import (
55
+ ImageClassificationInput,
56
+ ImageClassificationOutputElement,
57
+ ImageClassificationParameters,
58
+ )
59
+ from .image_segmentation import ImageSegmentationInput, ImageSegmentationOutputElement, ImageSegmentationParameters
60
+ from .image_to_image import ImageToImageInput, ImageToImageOutput, ImageToImageParameters, ImageToImageTargetSize
61
+ from .image_to_text import ImageToTextGenerationParameters, ImageToTextInput, ImageToTextOutput, ImageToTextParameters
62
+ from .object_detection import (
63
+ ObjectDetectionBoundingBox,
64
+ ObjectDetectionInput,
65
+ ObjectDetectionOutputElement,
66
+ ObjectDetectionParameters,
67
+ )
68
+ from .question_answering import (
69
+ QuestionAnsweringInput,
70
+ QuestionAnsweringInputData,
71
+ QuestionAnsweringOutputElement,
72
+ QuestionAnsweringParameters,
73
+ )
74
+ from .sentence_similarity import SentenceSimilarityInput, SentenceSimilarityInputData
75
+ from .summarization import SummarizationGenerationParameters, SummarizationInput, SummarizationOutput
76
+ from .table_question_answering import (
77
+ TableQuestionAnsweringInput,
78
+ TableQuestionAnsweringInputData,
79
+ TableQuestionAnsweringOutputElement,
80
+ )
81
+ from .text2text_generation import Text2TextGenerationInput, Text2TextGenerationOutput, Text2TextGenerationParameters
82
+ from .text_classification import TextClassificationInput, TextClassificationOutputElement, TextClassificationParameters
83
+ from .text_generation import (
84
+ TextGenerationInput,
85
+ TextGenerationInputGenerateParameters,
86
+ TextGenerationInputGrammarType,
87
+ TextGenerationOutput,
88
+ TextGenerationOutputBestOfSequence,
89
+ TextGenerationOutputDetails,
90
+ TextGenerationOutputPrefillToken,
91
+ TextGenerationOutputToken,
92
+ TextGenerationStreamOutput,
93
+ TextGenerationStreamOutputStreamDetails,
94
+ TextGenerationStreamOutputToken,
95
+ )
96
+ from .text_to_audio import TextToAudioGenerationParameters, TextToAudioInput, TextToAudioOutput, TextToAudioParameters
97
+ from .text_to_image import TextToImageInput, TextToImageOutput, TextToImageParameters, TextToImageTargetSize
98
+ from .token_classification import (
99
+ TokenClassificationInput,
100
+ TokenClassificationOutputElement,
101
+ TokenClassificationParameters,
102
+ )
103
+ from .translation import TranslationGenerationParameters, TranslationInput, TranslationOutput
104
+ from .video_classification import (
105
+ VideoClassificationInput,
106
+ VideoClassificationOutputElement,
107
+ VideoClassificationParameters,
108
+ )
109
+ from .visual_question_answering import (
110
+ VisualQuestionAnsweringInput,
111
+ VisualQuestionAnsweringInputData,
112
+ VisualQuestionAnsweringOutputElement,
113
+ VisualQuestionAnsweringParameters,
114
+ )
115
+ from .zero_shot_classification import (
116
+ ZeroShotClassificationInput,
117
+ ZeroShotClassificationInputData,
118
+ ZeroShotClassificationOutputElement,
119
+ ZeroShotClassificationParameters,
120
+ )
121
+ from .zero_shot_image_classification import (
122
+ ZeroShotImageClassificationInput,
123
+ ZeroShotImageClassificationInputData,
124
+ ZeroShotImageClassificationOutputElement,
125
+ ZeroShotImageClassificationParameters,
126
+ )
127
+ from .zero_shot_object_detection import (
128
+ ZeroShotObjectDetectionBoundingBox,
129
+ ZeroShotObjectDetectionInput,
130
+ ZeroShotObjectDetectionInputData,
131
+ ZeroShotObjectDetectionOutputElement,
132
+ )
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/base.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Contains a base class for all inference types."""
15
+
16
+ import inspect
17
+ import json
18
+ import warnings
19
+ from dataclasses import asdict, dataclass
20
+ from typing import Any, Dict, List, Type, TypeVar, Union, get_args
21
+
22
+
23
+ T = TypeVar("T", bound="BaseInferenceType")
24
+
25
+
26
+ @dataclass
27
+ class BaseInferenceType(dict):
28
+ """Base class for all inference types.
29
+
30
+ Object is a dataclass and a dict for backward compatibility but plan is to remove the dict part in the future.
31
+
32
+ Handle parsing from dict, list and json strings in a permissive way to ensure future-compatibility (e.g. all fields
33
+ are made optional, and non-expected fields are added as dict attributes).
34
+ """
35
+
36
+ @classmethod
37
+ def parse_obj_as_list(cls: Type[T], data: Union[bytes, str, List, Dict]) -> List[T]:
38
+ """Alias to parse server response and return a single instance.
39
+
40
+ See `parse_obj` for more details.
41
+ """
42
+ output = cls.parse_obj(data)
43
+ if not isinstance(output, list):
44
+ raise ValueError(f"Invalid input data for {cls}. Expected a list, but got {type(output)}.")
45
+ return output
46
+
47
+ @classmethod
48
+ def parse_obj_as_instance(cls: Type[T], data: Union[bytes, str, List, Dict]) -> T:
49
+ """Alias to parse server response and return a single instance.
50
+
51
+ See `parse_obj` for more details.
52
+ """
53
+ output = cls.parse_obj(data)
54
+ if isinstance(output, list):
55
+ raise ValueError(f"Invalid input data for {cls}. Expected a single instance, but got a list.")
56
+ return output
57
+
58
+ @classmethod
59
+ def parse_obj(cls: Type[T], data: Union[bytes, str, List, Dict]) -> Union[List[T], T]:
60
+ """Parse server response as a dataclass or list of dataclasses.
61
+
62
+ To enable future-compatibility, we want to handle cases where the server return more fields than expected.
63
+ In such cases, we don't want to raise an error but still create the dataclass object. Remaining fields are
64
+ added as dict attributes.
65
+ """
66
+ # Parse server response (from bytes)
67
+ if isinstance(data, bytes):
68
+ data = data.decode()
69
+ if isinstance(data, str):
70
+ data = json.loads(data)
71
+
72
+ # If a list, parse each item individually
73
+ if isinstance(data, List):
74
+ return [cls.parse_obj(d) for d in data] # type: ignore [misc]
75
+
76
+ # At this point, we expect a dict
77
+ if not isinstance(data, dict):
78
+ raise ValueError(f"Invalid data type: {type(data)}")
79
+
80
+ init_values = {}
81
+ other_values = {}
82
+ for key, value in data.items():
83
+ key = normalize_key(key)
84
+ if key in cls.__dataclass_fields__ and cls.__dataclass_fields__[key].init:
85
+ if isinstance(value, dict) or isinstance(value, list):
86
+ field_type = cls.__dataclass_fields__[key].type
87
+
88
+ # if `field_type` is a `BaseInferenceType`, parse it
89
+ if inspect.isclass(field_type) and issubclass(field_type, BaseInferenceType):
90
+ value = field_type.parse_obj(value)
91
+
92
+ # otherwise, recursively parse nested dataclasses (if possible)
93
+ # `get_args` returns handle Union and Optional for us
94
+ else:
95
+ expected_types = get_args(field_type)
96
+ for expected_type in expected_types:
97
+ if getattr(expected_type, "_name", None) == "List":
98
+ expected_type = get_args(expected_type)[
99
+ 0
100
+ ] # assume same type for all items in the list
101
+ if inspect.isclass(expected_type) and issubclass(expected_type, BaseInferenceType):
102
+ value = expected_type.parse_obj(value)
103
+ break
104
+ init_values[key] = value
105
+ else:
106
+ other_values[key] = value
107
+
108
+ # Make all missing fields default to None
109
+ # => ensure that dataclass initialization will never fail even if the server does not return all fields.
110
+ for key in cls.__dataclass_fields__:
111
+ if key not in init_values:
112
+ init_values[key] = None
113
+
114
+ # Initialize dataclass with expected values
115
+ item = cls(**init_values)
116
+
117
+ # Add remaining fields as dict attributes
118
+ item.update(other_values)
119
+ return item
120
+
121
+ def __post_init__(self):
122
+ self.update(asdict(self))
123
+
124
+ def __setitem__(self, __key: Any, __value: Any) -> None:
125
+ # Hacky way to keep dataclass values in sync when dict is updated
126
+ super().__setitem__(__key, __value)
127
+ if __key in self.__dataclass_fields__ and getattr(self, __key, None) != __value:
128
+ self.__setattr__(__key, __value)
129
+ return
130
+
131
+ def __setattr__(self, __name: str, __value: Any) -> None:
132
+ # Hacky way to keep dict values is sync when dataclass is updated
133
+ super().__setattr__(__name, __value)
134
+ if self.get(__name) != __value:
135
+ self[__name] = __value
136
+ return
137
+
138
+ def __getitem__(self, __key: Any) -> Any:
139
+ warnings.warn(
140
+ f"Accessing '{self.__class__.__name__}' values through dict is deprecated and "
141
+ "will be removed from version '0.25'. Use dataclass attributes instead.",
142
+ FutureWarning,
143
+ )
144
+ return super().__getitem__(__key)
145
+
146
+
147
+ def normalize_key(key: str) -> str:
148
+ # e.g "content-type" -> "content_type", "Accept" -> "accept"
149
+ return key.replace("-", "_").replace(" ", "_").lower()
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/image_to_text.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal, Optional, Union
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ EarlyStoppingEnum = Literal["never"]
13
+
14
+
15
+ @dataclass
16
+ class ImageToTextGenerationParameters(BaseInferenceType):
17
+ """Parametrization of the text generation process
18
+ Ad-hoc parametrization of the text generation process
19
+ """
20
+
21
+ do_sample: Optional[bool] = None
22
+ """Whether to use sampling instead of greedy decoding when generating new tokens."""
23
+ early_stopping: Optional[Union[bool, "EarlyStoppingEnum"]] = None
24
+ """Controls the stopping condition for beam-based methods."""
25
+ epsilon_cutoff: Optional[float] = None
26
+ """If set to float strictly between 0 and 1, only tokens with a conditional probability
27
+ greater than epsilon_cutoff will be sampled. In the paper, suggested values range from
28
+ 3e-4 to 9e-4, depending on the size of the model. See [Truncation Sampling as Language
29
+ Model Desmoothing](https://hf.co/papers/2210.15191) for more details.
30
+ """
31
+ eta_cutoff: Optional[float] = None
32
+ """Eta sampling is a hybrid of locally typical sampling and epsilon sampling. If set to
33
+ float strictly between 0 and 1, a token is only considered if it is greater than either
34
+ eta_cutoff or sqrt(eta_cutoff) * exp(-entropy(softmax(next_token_logits))). The latter
35
+ term is intuitively the expected next token probability, scaled by sqrt(eta_cutoff). In
36
+ the paper, suggested values range from 3e-4 to 2e-3, depending on the size of the model.
37
+ See [Truncation Sampling as Language Model Desmoothing](https://hf.co/papers/2210.15191)
38
+ for more details.
39
+ """
40
+ max_length: Optional[int] = None
41
+ """The maximum length (in tokens) of the generated text, including the input."""
42
+ max_new_tokens: Optional[int] = None
43
+ """The maximum number of tokens to generate. Takes precedence over maxLength."""
44
+ min_length: Optional[int] = None
45
+ """The minimum length (in tokens) of the generated text, including the input."""
46
+ min_new_tokens: Optional[int] = None
47
+ """The minimum number of tokens to generate. Takes precedence over maxLength."""
48
+ num_beam_groups: Optional[int] = None
49
+ """Number of groups to divide num_beams into in order to ensure diversity among different
50
+ groups of beams. See [this paper](https://hf.co/papers/1610.02424) for more details.
51
+ """
52
+ num_beams: Optional[int] = None
53
+ """Number of beams to use for beam search."""
54
+ penalty_alpha: Optional[float] = None
55
+ """The value balances the model confidence and the degeneration penalty in contrastive
56
+ search decoding.
57
+ """
58
+ temperature: Optional[float] = None
59
+ """The value used to modulate the next token probabilities."""
60
+ top_k: Optional[int] = None
61
+ """The number of highest probability vocabulary tokens to keep for top-k-filtering."""
62
+ top_p: Optional[float] = None
63
+ """If set to float < 1, only the smallest set of most probable tokens with probabilities
64
+ that add up to top_p or higher are kept for generation.
65
+ """
66
+ typical_p: Optional[float] = None
67
+ """Local typicality measures how similar the conditional probability of predicting a target
68
+ token next is to the expected conditional probability of predicting a random token next,
69
+ given the partial text already generated. If set to float < 1, the smallest set of the
70
+ most locally typical tokens with probabilities that add up to typical_p or higher are
71
+ kept for generation. See [this paper](https://hf.co/papers/2202.00666) for more details.
72
+ """
73
+ use_cache: Optional[bool] = None
74
+ """Whether the model should use the past last key/values attentions to speed up decoding"""
75
+
76
+
77
+ @dataclass
78
+ class ImageToTextParameters(BaseInferenceType):
79
+ """Additional inference parameters
80
+ Additional inference parameters for Image To Text
81
+ """
82
+
83
+ generate: Optional[ImageToTextGenerationParameters] = None
84
+ """Parametrization of the text generation process"""
85
+ max_new_tokens: Optional[int] = None
86
+ """The amount of maximum tokens to generate."""
87
+
88
+
89
+ @dataclass
90
+ class ImageToTextInput(BaseInferenceType):
91
+ """Inputs for Image To Text inference"""
92
+
93
+ inputs: Any
94
+ """The input image data"""
95
+ parameters: Optional[ImageToTextParameters] = None
96
+ """Additional inference parameters"""
97
+
98
+
99
+ @dataclass
100
+ class ImageToTextOutput(BaseInferenceType):
101
+ """Outputs of inference for the Image To Text task"""
102
+
103
+ generated_text: Any
104
+ image_to_text_output_generated_text: Optional[str] = None
105
+ """The generated text."""
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/summarization.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Dict, Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ SummarizationGenerationTruncationStrategy = Literal["do_not_truncate", "longest_first", "only_first", "only_second"]
13
+
14
+
15
+ @dataclass
16
+ class SummarizationGenerationParameters(BaseInferenceType):
17
+ """Additional inference parameters
18
+ Additional inference parameters for Text2text Generation
19
+ """
20
+
21
+ clean_up_tokenization_spaces: Optional[bool] = None
22
+ """Whether to clean up the potential extra spaces in the text output."""
23
+ generate_parameters: Optional[Dict[str, Any]] = None
24
+ """Additional parametrization of the text generation algorithm"""
25
+ truncation: Optional["SummarizationGenerationTruncationStrategy"] = None
26
+ """The truncation strategy to use"""
27
+
28
+
29
+ @dataclass
30
+ class SummarizationInput(BaseInferenceType):
31
+ """Inputs for Summarization inference
32
+ Inputs for Text2text Generation inference
33
+ """
34
+
35
+ inputs: str
36
+ """The input text data"""
37
+ parameters: Optional[SummarizationGenerationParameters] = None
38
+ """Additional inference parameters"""
39
+
40
+
41
+ @dataclass
42
+ class SummarizationOutput(BaseInferenceType):
43
+ """Outputs of inference for the Summarization task"""
44
+
45
+ summary_text: str
46
+ """The summarized text."""
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/text_generation.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, List, Literal, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ TypeEnum = Literal["json", "regex"]
13
+
14
+
15
+ @dataclass
16
+ class TextGenerationInputGrammarType(BaseInferenceType):
17
+ type: "TypeEnum"
18
+ value: Any
19
+ """A string that represents a [JSON Schema](https://json-schema.org/).
20
+ JSON Schema is a declarative language that allows to annotate JSON documents
21
+ with types and descriptions.
22
+ """
23
+
24
+
25
+ @dataclass
26
+ class TextGenerationInputGenerateParameters(BaseInferenceType):
27
+ best_of: Optional[int] = None
28
+ decoder_input_details: Optional[bool] = None
29
+ details: Optional[bool] = None
30
+ do_sample: Optional[bool] = None
31
+ frequency_penalty: Optional[float] = None
32
+ grammar: Optional[TextGenerationInputGrammarType] = None
33
+ max_new_tokens: Optional[int] = None
34
+ repetition_penalty: Optional[float] = None
35
+ return_full_text: Optional[bool] = None
36
+ seed: Optional[int] = None
37
+ stop: Optional[List[str]] = None
38
+ temperature: Optional[float] = None
39
+ top_k: Optional[int] = None
40
+ top_n_tokens: Optional[int] = None
41
+ top_p: Optional[float] = None
42
+ truncate: Optional[int] = None
43
+ typical_p: Optional[float] = None
44
+ watermark: Optional[bool] = None
45
+
46
+
47
+ @dataclass
48
+ class TextGenerationInput(BaseInferenceType):
49
+ """Text Generation Input.
50
+ Auto-generated from TGI specs.
51
+ For more details, check out
52
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
53
+ """
54
+
55
+ inputs: str
56
+ parameters: Optional[TextGenerationInputGenerateParameters] = None
57
+ stream: Optional[bool] = None
58
+
59
+
60
+ TextGenerationOutputFinishReason = Literal["length", "eos_token", "stop_sequence"]
61
+
62
+
63
+ @dataclass
64
+ class TextGenerationOutputPrefillToken(BaseInferenceType):
65
+ id: int
66
+ logprob: float
67
+ text: str
68
+
69
+
70
+ @dataclass
71
+ class TextGenerationOutputToken(BaseInferenceType):
72
+ id: int
73
+ logprob: float
74
+ special: bool
75
+ text: str
76
+
77
+
78
+ @dataclass
79
+ class TextGenerationOutputBestOfSequence(BaseInferenceType):
80
+ finish_reason: "TextGenerationOutputFinishReason"
81
+ generated_text: str
82
+ generated_tokens: int
83
+ prefill: List[TextGenerationOutputPrefillToken]
84
+ tokens: List[TextGenerationOutputToken]
85
+ seed: Optional[int] = None
86
+ top_tokens: Optional[List[List[TextGenerationOutputToken]]] = None
87
+
88
+
89
+ @dataclass
90
+ class TextGenerationOutputDetails(BaseInferenceType):
91
+ finish_reason: "TextGenerationOutputFinishReason"
92
+ generated_tokens: int
93
+ prefill: List[TextGenerationOutputPrefillToken]
94
+ tokens: List[TextGenerationOutputToken]
95
+ best_of_sequences: Optional[List[TextGenerationOutputBestOfSequence]] = None
96
+ seed: Optional[int] = None
97
+ top_tokens: Optional[List[List[TextGenerationOutputToken]]] = None
98
+
99
+
100
+ @dataclass
101
+ class TextGenerationOutput(BaseInferenceType):
102
+ """Text Generation Output.
103
+ Auto-generated from TGI specs.
104
+ For more details, check out
105
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
106
+ """
107
+
108
+ generated_text: str
109
+ details: Optional[TextGenerationOutputDetails] = None
110
+
111
+
112
+ @dataclass
113
+ class TextGenerationStreamOutputStreamDetails(BaseInferenceType):
114
+ finish_reason: "TextGenerationOutputFinishReason"
115
+ generated_tokens: int
116
+ seed: Optional[int] = None
117
+
118
+
119
+ @dataclass
120
+ class TextGenerationStreamOutputToken(BaseInferenceType):
121
+ id: int
122
+ logprob: float
123
+ special: bool
124
+ text: str
125
+
126
+
127
+ @dataclass
128
+ class TextGenerationStreamOutput(BaseInferenceType):
129
+ """Text Generation Stream Output.
130
+ Auto-generated from TGI specs.
131
+ For more details, check out
132
+ https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-tgi-import.ts.
133
+ """
134
+
135
+ index: int
136
+ token: TextGenerationStreamOutputToken
137
+ details: Optional[TextGenerationStreamOutputStreamDetails] = None
138
+ generated_text: Optional[str] = None
139
+ top_tokens: Optional[List[TextGenerationStreamOutputToken]] = None
llmeval-env/lib/python3.10/site-packages/huggingface_hub/inference/_generated/types/visual_question_answering.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Inference code generated from the JSON schema spec in @huggingface/tasks.
2
+ #
3
+ # See:
4
+ # - script: https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/scripts/inference-codegen.ts
5
+ # - specs: https://github.com/huggingface/huggingface.js/tree/main/packages/tasks/src/tasks.
6
+ from dataclasses import dataclass
7
+ from typing import Any, Optional
8
+
9
+ from .base import BaseInferenceType
10
+
11
+
12
+ @dataclass
13
+ class VisualQuestionAnsweringInputData(BaseInferenceType):
14
+ """One (image, question) pair to answer"""
15
+
16
+ image: Any
17
+ """The image."""
18
+ question: Any
19
+ """The question to answer based on the image."""
20
+
21
+
22
+ @dataclass
23
+ class VisualQuestionAnsweringParameters(BaseInferenceType):
24
+ """Additional inference parameters
25
+ Additional inference parameters for Visual Question Answering
26
+ """
27
+
28
+ top_k: Optional[int] = None
29
+ """The number of answers to return (will be chosen by order of likelihood). Note that we
30
+ return less than topk answers if there are not enough options available within the
31
+ context.
32
+ """
33
+
34
+
35
+ @dataclass
36
+ class VisualQuestionAnsweringInput(BaseInferenceType):
37
+ """Inputs for Visual Question Answering inference"""
38
+
39
+ inputs: VisualQuestionAnsweringInputData
40
+ """One (image, question) pair to answer"""
41
+ parameters: Optional[VisualQuestionAnsweringParameters] = None
42
+ """Additional inference parameters"""
43
+
44
+
45
+ @dataclass
46
+ class VisualQuestionAnsweringOutputElement(BaseInferenceType):
47
+ """Outputs of inference for the Visual Question Answering task"""
48
+
49
+ label: Any
50
+ score: float
51
+ """The associated score / probability"""
52
+ answer: Optional[str] = None
53
+ """The answer to the question"""
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/__init__.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License
16
+
17
+ # ruff: noqa: F401
18
+
19
+ from huggingface_hub.errors import (
20
+ HFValidationError,
21
+ LocalTokenNotFoundError,
22
+ NotASafetensorsRepoError,
23
+ OfflineModeIsEnabled,
24
+ SafetensorsParsingError,
25
+ )
26
+
27
+ from . import tqdm as _tqdm # _tqdm is the module
28
+ from ._cache_assets import cached_assets_path
29
+ from ._cache_manager import (
30
+ CachedFileInfo,
31
+ CachedRepoInfo,
32
+ CachedRevisionInfo,
33
+ CacheNotFound,
34
+ CorruptedCacheException,
35
+ DeleteCacheStrategy,
36
+ HFCacheInfo,
37
+ scan_cache_dir,
38
+ )
39
+ from ._chunk_utils import chunk_iterable
40
+ from ._datetime import parse_datetime
41
+ from ._errors import (
42
+ BadRequestError,
43
+ DisabledRepoError,
44
+ EntryNotFoundError,
45
+ FileMetadataError,
46
+ GatedRepoError,
47
+ HfHubHTTPError,
48
+ LocalEntryNotFoundError,
49
+ RepositoryNotFoundError,
50
+ RevisionNotFoundError,
51
+ hf_raise_for_status,
52
+ )
53
+ from ._experimental import experimental
54
+ from ._fixes import SoftTemporaryDirectory, WeakFileLock, yaml_dump
55
+ from ._git_credential import list_credential_helpers, set_git_credential, unset_git_credential
56
+ from ._headers import build_hf_headers, get_token_to_send
57
+ from ._hf_folder import HfFolder
58
+ from ._http import (
59
+ configure_http_backend,
60
+ fix_hf_endpoint_in_url,
61
+ get_session,
62
+ http_backoff,
63
+ reset_sessions,
64
+ )
65
+ from ._pagination import paginate
66
+ from ._paths import DEFAULT_IGNORE_PATTERNS, FORBIDDEN_FOLDERS, filter_repo_objects
67
+ from ._runtime import (
68
+ dump_environment_info,
69
+ get_aiohttp_version,
70
+ get_fastai_version,
71
+ get_fastapi_version,
72
+ get_fastcore_version,
73
+ get_gradio_version,
74
+ get_graphviz_version,
75
+ get_hf_hub_version,
76
+ get_hf_transfer_version,
77
+ get_jinja_version,
78
+ get_minijinja_version,
79
+ get_numpy_version,
80
+ get_pillow_version,
81
+ get_pydantic_version,
82
+ get_pydot_version,
83
+ get_python_version,
84
+ get_tensorboard_version,
85
+ get_tf_version,
86
+ get_torch_version,
87
+ is_aiohttp_available,
88
+ is_fastai_available,
89
+ is_fastapi_available,
90
+ is_fastcore_available,
91
+ is_google_colab,
92
+ is_gradio_available,
93
+ is_graphviz_available,
94
+ is_hf_transfer_available,
95
+ is_jinja_available,
96
+ is_minijinja_available,
97
+ is_notebook,
98
+ is_numpy_available,
99
+ is_package_available,
100
+ is_pillow_available,
101
+ is_pydantic_available,
102
+ is_pydot_available,
103
+ is_safetensors_available,
104
+ is_tensorboard_available,
105
+ is_tf_available,
106
+ is_torch_available,
107
+ )
108
+ from ._safetensors import (
109
+ SafetensorsFileMetadata,
110
+ SafetensorsRepoMetadata,
111
+ TensorInfo,
112
+ )
113
+ from ._subprocess import capture_output, run_interactive_subprocess, run_subprocess
114
+ from ._telemetry import send_telemetry
115
+ from ._token import get_token
116
+ from ._typing import is_jsonable
117
+ from ._validators import (
118
+ smoothly_deprecate_use_auth_token,
119
+ validate_hf_hub_args,
120
+ validate_repo_id,
121
+ )
122
+ from .tqdm import (
123
+ are_progress_bars_disabled,
124
+ disable_progress_bars,
125
+ enable_progress_bars,
126
+ tqdm,
127
+ tqdm_stream_file,
128
+ )
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_errors.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from typing import Optional
3
+
4
+ from requests import HTTPError, Response
5
+
6
+ from ._fixes import JSONDecodeError
7
+
8
+
9
+ REPO_API_REGEX = re.compile(
10
+ r"""
11
+ # staging or production endpoint
12
+ ^https://[^/]+
13
+ (
14
+ # on /api/repo_type/repo_id
15
+ /api/(models|datasets|spaces)/(.+)
16
+ |
17
+ # or /repo_id/resolve/revision/...
18
+ /(.+)/resolve/(.+)
19
+ )
20
+ """,
21
+ flags=re.VERBOSE,
22
+ )
23
+
24
+
25
+ class FileMetadataError(OSError):
26
+ """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
27
+
28
+ Inherits from `OSError` for backward compatibility.
29
+ """
30
+
31
+
32
+ class HfHubHTTPError(HTTPError):
33
+ """
34
+ HTTPError to inherit from for any custom HTTP Error raised in HF Hub.
35
+
36
+ Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is
37
+ sent back by the server, it will be added to the error message.
38
+
39
+ Added details:
40
+ - Request id from "X-Request-Id" header if exists.
41
+ - Server error message from the header "X-Error-Message".
42
+ - Server error message if we can found one in the response body.
43
+
44
+ Example:
45
+ ```py
46
+ import requests
47
+ from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
48
+
49
+ response = get_session().post(...)
50
+ try:
51
+ hf_raise_for_status(response)
52
+ except HfHubHTTPError as e:
53
+ print(str(e)) # formatted message
54
+ e.request_id, e.server_message # details returned by server
55
+
56
+ # Complete the error message with additional information once it's raised
57
+ e.append_to_message("\n`create_commit` expects the repository to exist.")
58
+ raise
59
+ ```
60
+ """
61
+
62
+ request_id: Optional[str] = None
63
+ server_message: Optional[str] = None
64
+
65
+ def __init__(self, message: str, response: Optional[Response] = None):
66
+ # Parse server information if any.
67
+ if response is not None:
68
+ self.request_id = response.headers.get("X-Request-Id")
69
+ try:
70
+ server_data = response.json()
71
+ except JSONDecodeError:
72
+ server_data = {}
73
+
74
+ # Retrieve server error message from multiple sources
75
+ server_message_from_headers = response.headers.get("X-Error-Message")
76
+ server_message_from_body = server_data.get("error")
77
+ server_multiple_messages_from_body = "\n".join(
78
+ error["message"] for error in server_data.get("errors", []) if "message" in error
79
+ )
80
+
81
+ # Concatenate error messages
82
+ _server_message = ""
83
+ if server_message_from_headers is not None: # from headers
84
+ _server_message += server_message_from_headers + "\n"
85
+ if server_message_from_body is not None: # from body "error"
86
+ if isinstance(server_message_from_body, list):
87
+ server_message_from_body = "\n".join(server_message_from_body)
88
+ if server_message_from_body not in _server_message:
89
+ _server_message += server_message_from_body + "\n"
90
+ if server_multiple_messages_from_body is not None: # from body "errors"
91
+ if server_multiple_messages_from_body not in _server_message:
92
+ _server_message += server_multiple_messages_from_body + "\n"
93
+ _server_message = _server_message.strip()
94
+
95
+ # Set message to `HfHubHTTPError` (if any)
96
+ if _server_message != "":
97
+ self.server_message = _server_message
98
+
99
+ super().__init__(
100
+ _format_error_message(
101
+ message,
102
+ request_id=self.request_id,
103
+ server_message=self.server_message,
104
+ ),
105
+ response=response, # type: ignore
106
+ request=response.request if response is not None else None, # type: ignore
107
+ )
108
+
109
+ def append_to_message(self, additional_message: str) -> None:
110
+ """Append additional information to the `HfHubHTTPError` initial message."""
111
+ self.args = (self.args[0] + additional_message,) + self.args[1:]
112
+
113
+
114
+ class RepositoryNotFoundError(HfHubHTTPError):
115
+ """
116
+ Raised when trying to access a hf.co URL with an invalid repository name, or
117
+ with a private repo name the user does not have access to.
118
+
119
+ Example:
120
+
121
+ ```py
122
+ >>> from huggingface_hub import model_info
123
+ >>> model_info("<non_existent_repository>")
124
+ (...)
125
+ huggingface_hub.utils._errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
126
+
127
+ Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
128
+ Please make sure you specified the correct `repo_id` and `repo_type`.
129
+ If the repo is private, make sure you are authenticated.
130
+ Invalid username or password.
131
+ ```
132
+ """
133
+
134
+
135
+ class GatedRepoError(RepositoryNotFoundError):
136
+ """
137
+ Raised when trying to access a gated repository for which the user is not on the
138
+ authorized list.
139
+
140
+ Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
141
+
142
+ Example:
143
+
144
+ ```py
145
+ >>> from huggingface_hub import model_info
146
+ >>> model_info("<gated_repository>")
147
+ (...)
148
+ huggingface_hub.utils._errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
149
+
150
+ Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
151
+ Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
152
+ Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
153
+ ```
154
+ """
155
+
156
+
157
+ class DisabledRepoError(HfHubHTTPError):
158
+ """
159
+ Raised when trying to access a repository that has been disabled by its author.
160
+
161
+ Example:
162
+
163
+ ```py
164
+ >>> from huggingface_hub import dataset_info
165
+ >>> dataset_info("laion/laion-art")
166
+ (...)
167
+ huggingface_hub.utils._errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
168
+
169
+ Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
170
+ Access to this resource is disabled.
171
+ ```
172
+ """
173
+
174
+
175
+ class RevisionNotFoundError(HfHubHTTPError):
176
+ """
177
+ Raised when trying to access a hf.co URL with a valid repository but an invalid
178
+ revision.
179
+
180
+ Example:
181
+
182
+ ```py
183
+ >>> from huggingface_hub import hf_hub_download
184
+ >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
185
+ (...)
186
+ huggingface_hub.utils._errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
187
+
188
+ Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
189
+ ```
190
+ """
191
+
192
+
193
+ class EntryNotFoundError(HfHubHTTPError):
194
+ """
195
+ Raised when trying to access a hf.co URL with a valid repository and revision
196
+ but an invalid filename.
197
+
198
+ Example:
199
+
200
+ ```py
201
+ >>> from huggingface_hub import hf_hub_download
202
+ >>> hf_hub_download('bert-base-cased', '<non-existent-file>')
203
+ (...)
204
+ huggingface_hub.utils._errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
205
+
206
+ Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
207
+ ```
208
+ """
209
+
210
+
211
+ class LocalEntryNotFoundError(EntryNotFoundError, FileNotFoundError, ValueError):
212
+ """
213
+ Raised when trying to access a file or snapshot that is not on the disk when network is
214
+ disabled or unavailable (connection issue). The entry may exist on the Hub.
215
+
216
+ Note: `ValueError` type is to ensure backward compatibility.
217
+ Note: `LocalEntryNotFoundError` derives from `HTTPError` because of `EntryNotFoundError`
218
+ even when it is not a network issue.
219
+
220
+ Example:
221
+
222
+ ```py
223
+ >>> from huggingface_hub import hf_hub_download
224
+ >>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
225
+ (...)
226
+ huggingface_hub.utils._errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.
227
+ ```
228
+ """
229
+
230
+ def __init__(self, message: str):
231
+ super().__init__(message, response=None)
232
+
233
+
234
+ class BadRequestError(HfHubHTTPError, ValueError):
235
+ """
236
+ Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
237
+
238
+ Example:
239
+
240
+ ```py
241
+ >>> resp = requests.post("hf.co/api/check", ...)
242
+ >>> hf_raise_for_status(resp, endpoint_name="check")
243
+ huggingface_hub.utils._errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
244
+ ```
245
+ """
246
+
247
+
248
+ def hf_raise_for_status(response: Response, endpoint_name: Optional[str] = None) -> None:
249
+ """
250
+ Internal version of `response.raise_for_status()` that will refine a
251
+ potential HTTPError. Raised exception will be an instance of `HfHubHTTPError`.
252
+
253
+ This helper is meant to be the unique method to raise_for_status when making a call
254
+ to the Hugging Face Hub.
255
+
256
+ Example:
257
+ ```py
258
+ import requests
259
+ from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
260
+
261
+ response = get_session().post(...)
262
+ try:
263
+ hf_raise_for_status(response)
264
+ except HfHubHTTPError as e:
265
+ print(str(e)) # formatted message
266
+ e.request_id, e.server_message # details returned by server
267
+
268
+ # Complete the error message with additional information once it's raised
269
+ e.append_to_message("\n`create_commit` expects the repository to exist.")
270
+ raise
271
+ ```
272
+
273
+ Args:
274
+ response (`Response`):
275
+ Response from the server.
276
+ endpoint_name (`str`, *optional*):
277
+ Name of the endpoint that has been called. If provided, the error message
278
+ will be more complete.
279
+
280
+ <Tip warning={true}>
281
+
282
+ Raises when the request has failed:
283
+
284
+ - [`~utils.RepositoryNotFoundError`]
285
+ If the repository to download from cannot be found. This may be because it
286
+ doesn't exist, because `repo_type` is not set correctly, or because the repo
287
+ is `private` and you do not have access.
288
+ - [`~utils.GatedRepoError`]
289
+ If the repository exists but is gated and the user is not on the authorized
290
+ list.
291
+ - [`~utils.RevisionNotFoundError`]
292
+ If the repository exists but the revision couldn't be find.
293
+ - [`~utils.EntryNotFoundError`]
294
+ If the repository exists but the entry (e.g. the requested file) couldn't be
295
+ find.
296
+ - [`~utils.BadRequestError`]
297
+ If request failed with a HTTP 400 BadRequest error.
298
+ - [`~utils.HfHubHTTPError`]
299
+ If request failed for a reason not listed above.
300
+
301
+ </Tip>
302
+ """
303
+ try:
304
+ response.raise_for_status()
305
+ except HTTPError as e:
306
+ error_code = response.headers.get("X-Error-Code")
307
+ error_message = response.headers.get("X-Error-Message")
308
+
309
+ if error_code == "RevisionNotFound":
310
+ message = f"{response.status_code} Client Error." + "\n\n" + f"Revision Not Found for url: {response.url}."
311
+ raise RevisionNotFoundError(message, response) from e
312
+
313
+ elif error_code == "EntryNotFound":
314
+ message = f"{response.status_code} Client Error." + "\n\n" + f"Entry Not Found for url: {response.url}."
315
+ raise EntryNotFoundError(message, response) from e
316
+
317
+ elif error_code == "GatedRepo":
318
+ message = (
319
+ f"{response.status_code} Client Error." + "\n\n" + f"Cannot access gated repo for url {response.url}."
320
+ )
321
+ raise GatedRepoError(message, response) from e
322
+
323
+ elif error_message == "Access to this resource is disabled.":
324
+ message = (
325
+ f"{response.status_code} Client Error."
326
+ + "\n\n"
327
+ + f"Cannot access repository for url {response.url}."
328
+ + "\n"
329
+ + "Access to this resource is disabled."
330
+ )
331
+ raise DisabledRepoError(message, response) from e
332
+
333
+ elif error_code == "RepoNotFound" or (
334
+ response.status_code == 401
335
+ and response.request is not None
336
+ and response.request.url is not None
337
+ and REPO_API_REGEX.search(response.request.url) is not None
338
+ ):
339
+ # 401 is misleading as it is returned for:
340
+ # - private and gated repos if user is not authenticated
341
+ # - missing repos
342
+ # => for now, we process them as `RepoNotFound` anyway.
343
+ # See https://gist.github.com/Wauplin/46c27ad266b15998ce56a6603796f0b9
344
+ message = (
345
+ f"{response.status_code} Client Error."
346
+ + "\n\n"
347
+ + f"Repository Not Found for url: {response.url}."
348
+ + "\nPlease make sure you specified the correct `repo_id` and"
349
+ " `repo_type`.\nIf you are trying to access a private or gated repo,"
350
+ " make sure you are authenticated."
351
+ )
352
+ raise RepositoryNotFoundError(message, response) from e
353
+
354
+ elif response.status_code == 400:
355
+ message = (
356
+ f"\n\nBad request for {endpoint_name} endpoint:" if endpoint_name is not None else "\n\nBad request:"
357
+ )
358
+ raise BadRequestError(message, response=response) from e
359
+
360
+ elif response.status_code == 403:
361
+ message = (
362
+ f"\n\n{response.status_code} Forbidden: {error_message}."
363
+ + f"\nCannot access content at: {response.url}."
364
+ + "\nIf you are trying to create or update content,"
365
+ + "make sure you have a token with the `write` role."
366
+ )
367
+ raise HfHubHTTPError(message, response=response) from e
368
+
369
+ # Convert `HTTPError` into a `HfHubHTTPError` to display request information
370
+ # as well (request id and/or server error message)
371
+ raise HfHubHTTPError(str(e), response=response) from e
372
+
373
+
374
+ def _format_error_message(message: str, request_id: Optional[str], server_message: Optional[str]) -> str:
375
+ """
376
+ Format the `HfHubHTTPError` error message based on initial message and information
377
+ returned by the server.
378
+
379
+ Used when initializing `HfHubHTTPError`.
380
+ """
381
+ # Add message from response body
382
+ if server_message is not None and len(server_message) > 0 and server_message.lower() not in message.lower():
383
+ if "\n\n" in message:
384
+ message += "\n" + server_message
385
+ else:
386
+ message += "\n\n" + server_message
387
+
388
+ # Add Request ID
389
+ if request_id is not None and str(request_id).lower() not in message.lower():
390
+ request_id_message = f" (Request ID: {request_id})"
391
+ if "\n" in message:
392
+ newline_index = message.index("\n")
393
+ message = message[:newline_index] + request_id_message + message[newline_index:]
394
+ else:
395
+ message += request_id_message
396
+
397
+ return message
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_experimental.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to flag a feature as "experimental" in Huggingface Hub."""
16
+
17
+ import warnings
18
+ from functools import wraps
19
+ from typing import Callable
20
+
21
+ from .. import constants
22
+
23
+
24
+ def experimental(fn: Callable) -> Callable:
25
+ """Decorator to flag a feature as experimental.
26
+
27
+ An experimental feature trigger a warning when used as it might be subject to breaking changes in the future.
28
+ Warnings can be disabled by setting the environment variable `HF_EXPERIMENTAL_WARNING` to `0`.
29
+
30
+ Args:
31
+ fn (`Callable`):
32
+ The function to flag as experimental.
33
+
34
+ Returns:
35
+ `Callable`: The decorated function.
36
+
37
+ Example:
38
+
39
+ ```python
40
+ >>> from huggingface_hub.utils import experimental
41
+
42
+ >>> @experimental
43
+ ... def my_function():
44
+ ... print("Hello world!")
45
+
46
+ >>> my_function()
47
+ UserWarning: 'my_function' is experimental and might be subject to breaking changes in the future. You can disable
48
+ this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment variable.
49
+ Hello world!
50
+ ```
51
+ """
52
+ # For classes, put the "experimental" around the "__new__" method => __new__ will be removed in warning message
53
+ name = fn.__qualname__[: -len(".__new__")] if fn.__qualname__.endswith(".__new__") else fn.__qualname__
54
+
55
+ @wraps(fn)
56
+ def _inner_fn(*args, **kwargs):
57
+ if not constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING:
58
+ warnings.warn(
59
+ f"'{name}' is experimental and might be subject to breaking changes in the future."
60
+ " You can disable this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment"
61
+ " variable.",
62
+ UserWarning,
63
+ )
64
+ return fn(*args, **kwargs)
65
+
66
+ return _inner_fn
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_fixes.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # JSONDecodeError was introduced in requests=2.27 released in 2022.
2
+ # This allows us to support older requests for users
3
+ # More information: https://github.com/psf/requests/pull/5856
4
+ try:
5
+ from requests import JSONDecodeError # type: ignore # noqa: F401
6
+ except ImportError:
7
+ try:
8
+ from simplejson import JSONDecodeError # type: ignore # noqa: F401
9
+ except ImportError:
10
+ from json import JSONDecodeError # type: ignore # noqa: F401
11
+ import contextlib
12
+ import os
13
+ import shutil
14
+ import stat
15
+ import tempfile
16
+ from functools import partial
17
+ from pathlib import Path
18
+ from typing import Callable, Generator, Optional, Union
19
+
20
+ import yaml
21
+ from filelock import BaseFileLock, FileLock
22
+
23
+
24
+ # Wrap `yaml.dump` to set `allow_unicode=True` by default.
25
+ #
26
+ # Example:
27
+ # ```py
28
+ # >>> yaml.dump({"emoji": "👀", "some unicode": "日本か"})
29
+ # 'emoji: "\\U0001F440"\nsome unicode: "\\u65E5\\u672C\\u304B"\n'
30
+ #
31
+ # >>> yaml_dump({"emoji": "👀", "some unicode": "日本か"})
32
+ # 'emoji: "👀"\nsome unicode: "日本か"\n'
33
+ # ```
34
+ yaml_dump: Callable[..., str] = partial(yaml.dump, stream=None, allow_unicode=True) # type: ignore
35
+
36
+
37
+ @contextlib.contextmanager
38
+ def SoftTemporaryDirectory(
39
+ suffix: Optional[str] = None,
40
+ prefix: Optional[str] = None,
41
+ dir: Optional[Union[Path, str]] = None,
42
+ **kwargs,
43
+ ) -> Generator[Path, None, None]:
44
+ """
45
+ Context manager to create a temporary directory and safely delete it.
46
+
47
+ If tmp directory cannot be deleted normally, we set the WRITE permission and retry.
48
+ If cleanup still fails, we give up but don't raise an exception. This is equivalent
49
+ to `tempfile.TemporaryDirectory(..., ignore_cleanup_errors=True)` introduced in
50
+ Python 3.10.
51
+
52
+ See https://www.scivision.dev/python-tempfile-permission-error-windows/.
53
+ """
54
+ tmpdir = tempfile.TemporaryDirectory(prefix=prefix, suffix=suffix, dir=dir, **kwargs)
55
+ yield Path(tmpdir.name).resolve()
56
+
57
+ try:
58
+ # First once with normal cleanup
59
+ shutil.rmtree(tmpdir.name)
60
+ except Exception:
61
+ # If failed, try to set write permission and retry
62
+ try:
63
+ shutil.rmtree(tmpdir.name, onerror=_set_write_permission_and_retry)
64
+ except Exception:
65
+ pass
66
+
67
+ # And finally, cleanup the tmpdir.
68
+ # If it fails again, give up but do not throw error
69
+ try:
70
+ tmpdir.cleanup()
71
+ except Exception:
72
+ pass
73
+
74
+
75
+ def _set_write_permission_and_retry(func, path, excinfo):
76
+ os.chmod(path, stat.S_IWRITE)
77
+ func(path)
78
+
79
+
80
+ @contextlib.contextmanager
81
+ def WeakFileLock(lock_file: Union[str, Path]) -> Generator[BaseFileLock, None, None]:
82
+ """A filelock that won't raise an exception if release fails."""
83
+ lock = FileLock(lock_file)
84
+ lock.acquire()
85
+
86
+ yield lock
87
+
88
+ try:
89
+ return lock.release()
90
+ except OSError:
91
+ try:
92
+ Path(lock_file).unlink()
93
+ except OSError:
94
+ pass
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_git_credential.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to manage Git credentials."""
16
+
17
+ import re
18
+ import subprocess
19
+ from typing import List, Optional
20
+
21
+ from ..constants import ENDPOINT
22
+ from ._subprocess import run_interactive_subprocess, run_subprocess
23
+
24
+
25
+ GIT_CREDENTIAL_REGEX = re.compile(
26
+ r"""
27
+ ^\s* # start of line
28
+ credential\.helper # credential.helper value
29
+ \s*=\s* # separator
30
+ (\w+) # the helper name (group 1)
31
+ (\s|$) # whitespace or end of line
32
+ """,
33
+ flags=re.MULTILINE | re.IGNORECASE | re.VERBOSE,
34
+ )
35
+
36
+
37
+ def list_credential_helpers(folder: Optional[str] = None) -> List[str]:
38
+ """Return the list of git credential helpers configured.
39
+
40
+ See https://git-scm.com/docs/gitcredentials.
41
+
42
+ Credentials are saved in all configured helpers (store, cache, macOS keychain,...).
43
+ Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential.
44
+
45
+ Args:
46
+ folder (`str`, *optional*):
47
+ The folder in which to check the configured helpers.
48
+ """
49
+ try:
50
+ output = run_subprocess("git config --list", folder=folder).stdout
51
+ parsed = _parse_credential_output(output)
52
+ return parsed
53
+ except subprocess.CalledProcessError as exc:
54
+ raise EnvironmentError(exc.stderr)
55
+
56
+
57
+ def set_git_credential(token: str, username: str = "hf_user", folder: Optional[str] = None) -> None:
58
+ """Save a username/token pair in git credential for HF Hub registry.
59
+
60
+ Credentials are saved in all configured helpers (store, cache, macOS keychain,...).
61
+ Calls "`git credential approve`" internally. See https://git-scm.com/docs/git-credential.
62
+
63
+ Args:
64
+ username (`str`, defaults to `"hf_user"`):
65
+ A git username. Defaults to `"hf_user"`, the default user used in the Hub.
66
+ token (`str`, defaults to `"hf_user"`):
67
+ A git password. In practice, the User Access Token for the Hub.
68
+ See https://huggingface.co/settings/tokens.
69
+ folder (`str`, *optional*):
70
+ The folder in which to check the configured helpers.
71
+ """
72
+ with run_interactive_subprocess("git credential approve", folder=folder) as (
73
+ stdin,
74
+ _,
75
+ ):
76
+ stdin.write(f"url={ENDPOINT}\nusername={username.lower()}\npassword={token}\n\n")
77
+ stdin.flush()
78
+
79
+
80
+ def unset_git_credential(username: str = "hf_user", folder: Optional[str] = None) -> None:
81
+ """Erase credentials from git credential for HF Hub registry.
82
+
83
+ Credentials are erased from the configured helpers (store, cache, macOS
84
+ keychain,...), if any. If `username` is not provided, any credential configured for
85
+ HF Hub endpoint is erased.
86
+ Calls "`git credential erase`" internally. See https://git-scm.com/docs/git-credential.
87
+
88
+ Args:
89
+ username (`str`, defaults to `"hf_user"`):
90
+ A git username. Defaults to `"hf_user"`, the default user used in the Hub.
91
+ folder (`str`, *optional*):
92
+ The folder in which to check the configured helpers.
93
+ """
94
+ with run_interactive_subprocess("git credential reject", folder=folder) as (
95
+ stdin,
96
+ _,
97
+ ):
98
+ standard_input = f"url={ENDPOINT}\n"
99
+ if username is not None:
100
+ standard_input += f"username={username.lower()}\n"
101
+ standard_input += "\n"
102
+
103
+ stdin.write(standard_input)
104
+ stdin.flush()
105
+
106
+
107
+ def _parse_credential_output(output: str) -> List[str]:
108
+ """Parse the output of `git credential fill` to extract the password.
109
+
110
+ Args:
111
+ output (`str`):
112
+ The output of `git credential fill`.
113
+ """
114
+ # NOTE: If user has set an helper for a custom URL, it will not we caught here.
115
+ # Example: `credential.https://huggingface.co.helper=store`
116
+ # See: https://github.com/huggingface/huggingface_hub/pull/1138#discussion_r1013324508
117
+ return sorted( # Sort for nice printing
118
+ set( # Might have some duplicates
119
+ match[0] for match in GIT_CREDENTIAL_REGEX.findall(output)
120
+ )
121
+ )
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_http.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to handle HTTP requests in Huggingface Hub."""
16
+
17
+ import io
18
+ import os
19
+ import threading
20
+ import time
21
+ import uuid
22
+ from functools import lru_cache
23
+ from http import HTTPStatus
24
+ from typing import Callable, Optional, Tuple, Type, Union
25
+
26
+ import requests
27
+ from requests import Response
28
+ from requests.adapters import HTTPAdapter
29
+ from requests.models import PreparedRequest
30
+
31
+ from huggingface_hub.errors import OfflineModeIsEnabled
32
+
33
+ from .. import constants
34
+ from . import logging
35
+ from ._typing import HTTP_METHOD_T
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ # Both headers are used by the Hub to debug failed requests.
41
+ # `X_AMZN_TRACE_ID` is better as it also works to debug on Cloudfront and ALB.
42
+ # If `X_AMZN_TRACE_ID` is set, the Hub will use it as well.
43
+ X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"
44
+ X_REQUEST_ID = "x-request-id"
45
+
46
+
47
+ class UniqueRequestIdAdapter(HTTPAdapter):
48
+ X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"
49
+
50
+ def add_headers(self, request, **kwargs):
51
+ super().add_headers(request, **kwargs)
52
+
53
+ # Add random request ID => easier for server-side debug
54
+ if X_AMZN_TRACE_ID not in request.headers:
55
+ request.headers[X_AMZN_TRACE_ID] = request.headers.get(X_REQUEST_ID) or str(uuid.uuid4())
56
+
57
+ # Add debug log
58
+ has_token = str(request.headers.get("authorization", "")).startswith("Bearer hf_")
59
+ logger.debug(
60
+ f"Request {request.headers[X_AMZN_TRACE_ID]}: {request.method} {request.url} (authenticated: {has_token})"
61
+ )
62
+
63
+ def send(self, request: PreparedRequest, *args, **kwargs) -> Response:
64
+ """Catch any RequestException to append request id to the error message for debugging."""
65
+ try:
66
+ return super().send(request, *args, **kwargs)
67
+ except requests.RequestException as e:
68
+ request_id = request.headers.get(X_AMZN_TRACE_ID)
69
+ if request_id is not None:
70
+ # Taken from https://stackoverflow.com/a/58270258
71
+ e.args = (*e.args, f"(Request ID: {request_id})")
72
+ raise
73
+
74
+
75
+ class OfflineAdapter(HTTPAdapter):
76
+ def send(self, request: PreparedRequest, *args, **kwargs) -> Response:
77
+ raise OfflineModeIsEnabled(
78
+ f"Cannot reach {request.url}: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable."
79
+ )
80
+
81
+
82
+ def _default_backend_factory() -> requests.Session:
83
+ session = requests.Session()
84
+ if constants.HF_HUB_OFFLINE:
85
+ session.mount("http://", OfflineAdapter())
86
+ session.mount("https://", OfflineAdapter())
87
+ else:
88
+ session.mount("http://", UniqueRequestIdAdapter())
89
+ session.mount("https://", UniqueRequestIdAdapter())
90
+ return session
91
+
92
+
93
+ BACKEND_FACTORY_T = Callable[[], requests.Session]
94
+ _GLOBAL_BACKEND_FACTORY: BACKEND_FACTORY_T = _default_backend_factory
95
+
96
+
97
+ def configure_http_backend(backend_factory: BACKEND_FACTORY_T = _default_backend_factory) -> None:
98
+ """
99
+ Configure the HTTP backend by providing a `backend_factory`. Any HTTP calls made by `huggingface_hub` will use a
100
+ Session object instantiated by this factory. This can be useful if you are running your scripts in a specific
101
+ environment requiring custom configuration (e.g. custom proxy or certifications).
102
+
103
+ Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
104
+ `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
105
+ set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
106
+ calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.
107
+
108
+ See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.
109
+
110
+ Example:
111
+ ```py
112
+ import requests
113
+ from huggingface_hub import configure_http_backend, get_session
114
+
115
+ # Create a factory function that returns a Session with configured proxies
116
+ def backend_factory() -> requests.Session:
117
+ session = requests.Session()
118
+ session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
119
+ return session
120
+
121
+ # Set it as the default session factory
122
+ configure_http_backend(backend_factory=backend_factory)
123
+
124
+ # In practice, this is mostly done internally in `huggingface_hub`
125
+ session = get_session()
126
+ ```
127
+ """
128
+ global _GLOBAL_BACKEND_FACTORY
129
+ _GLOBAL_BACKEND_FACTORY = backend_factory
130
+ reset_sessions()
131
+
132
+
133
+ def get_session() -> requests.Session:
134
+ """
135
+ Get a `requests.Session` object, using the session factory from the user.
136
+
137
+ Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
138
+ `huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
139
+ set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
140
+ calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.
141
+
142
+ See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.
143
+
144
+ Example:
145
+ ```py
146
+ import requests
147
+ from huggingface_hub import configure_http_backend, get_session
148
+
149
+ # Create a factory function that returns a Session with configured proxies
150
+ def backend_factory() -> requests.Session:
151
+ session = requests.Session()
152
+ session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
153
+ return session
154
+
155
+ # Set it as the default session factory
156
+ configure_http_backend(backend_factory=backend_factory)
157
+
158
+ # In practice, this is mostly done internally in `huggingface_hub`
159
+ session = get_session()
160
+ ```
161
+ """
162
+ return _get_session_from_cache(process_id=os.getpid(), thread_id=threading.get_ident())
163
+
164
+
165
+ def reset_sessions() -> None:
166
+ """Reset the cache of sessions.
167
+
168
+ Mostly used internally when sessions are reconfigured or an SSLError is raised.
169
+ See [`configure_http_backend`] for more details.
170
+ """
171
+ _get_session_from_cache.cache_clear()
172
+
173
+
174
+ @lru_cache
175
+ def _get_session_from_cache(process_id: int, thread_id: int) -> requests.Session:
176
+ """
177
+ Create a new session per thread using global factory. Using LRU cache (maxsize 128) to avoid memory leaks when
178
+ using thousands of threads. Cache is cleared when `configure_http_backend` is called.
179
+ """
180
+ return _GLOBAL_BACKEND_FACTORY()
181
+
182
+
183
+ def http_backoff(
184
+ method: HTTP_METHOD_T,
185
+ url: str,
186
+ *,
187
+ max_retries: int = 5,
188
+ base_wait_time: float = 1,
189
+ max_wait_time: float = 8,
190
+ retry_on_exceptions: Union[Type[Exception], Tuple[Type[Exception], ...]] = (
191
+ requests.Timeout,
192
+ requests.ConnectionError,
193
+ ),
194
+ retry_on_status_codes: Union[int, Tuple[int, ...]] = HTTPStatus.SERVICE_UNAVAILABLE,
195
+ **kwargs,
196
+ ) -> Response:
197
+ """Wrapper around requests to retry calls on an endpoint, with exponential backoff.
198
+
199
+ Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...)
200
+ and/or on specific status codes (ex: service unavailable). If the call failed more
201
+ than `max_retries`, the exception is thrown or `raise_for_status` is called on the
202
+ response object.
203
+
204
+ Re-implement mechanisms from the `backoff` library to avoid adding an external
205
+ dependencies to `hugging_face_hub`. See https://github.com/litl/backoff.
206
+
207
+ Args:
208
+ method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`):
209
+ HTTP method to perform.
210
+ url (`str`):
211
+ The URL of the resource to fetch.
212
+ max_retries (`int`, *optional*, defaults to `5`):
213
+ Maximum number of retries, defaults to 5 (no retries).
214
+ base_wait_time (`float`, *optional*, defaults to `1`):
215
+ Duration (in seconds) to wait before retrying the first time.
216
+ Wait time between retries then grows exponentially, capped by
217
+ `max_wait_time`.
218
+ max_wait_time (`float`, *optional*, defaults to `8`):
219
+ Maximum duration (in seconds) to wait before retrying.
220
+ retry_on_exceptions (`Type[Exception]` or `Tuple[Type[Exception]]`, *optional*):
221
+ Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types.
222
+ By default, retry on `requests.Timeout` and `requests.ConnectionError`.
223
+ retry_on_status_codes (`int` or `Tuple[int]`, *optional*, defaults to `503`):
224
+ Define on which status codes the request must be retried. By default, only
225
+ HTTP 503 Service Unavailable is retried.
226
+ **kwargs (`dict`, *optional*):
227
+ kwargs to pass to `requests.request`.
228
+
229
+ Example:
230
+ ```
231
+ >>> from huggingface_hub.utils import http_backoff
232
+
233
+ # Same usage as "requests.request".
234
+ >>> response = http_backoff("GET", "https://www.google.com")
235
+ >>> response.raise_for_status()
236
+
237
+ # If you expect a Gateway Timeout from time to time
238
+ >>> http_backoff("PUT", upload_url, data=data, retry_on_status_codes=504)
239
+ >>> response.raise_for_status()
240
+ ```
241
+
242
+ <Tip warning={true}>
243
+
244
+ When using `requests` it is possible to stream data by passing an iterator to the
245
+ `data` argument. On http backoff this is a problem as the iterator is not reset
246
+ after a failed call. This issue is mitigated for file objects or any IO streams
247
+ by saving the initial position of the cursor (with `data.tell()`) and resetting the
248
+ cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff
249
+ will fail. If this is a hard constraint for you, please let us know by opening an
250
+ issue on [Github](https://github.com/huggingface/huggingface_hub).
251
+
252
+ </Tip>
253
+ """
254
+ if isinstance(retry_on_exceptions, type): # Tuple from single exception type
255
+ retry_on_exceptions = (retry_on_exceptions,)
256
+
257
+ if isinstance(retry_on_status_codes, int): # Tuple from single status code
258
+ retry_on_status_codes = (retry_on_status_codes,)
259
+
260
+ nb_tries = 0
261
+ sleep_time = base_wait_time
262
+
263
+ # If `data` is used and is a file object (or any IO), it will be consumed on the
264
+ # first HTTP request. We need to save the initial position so that the full content
265
+ # of the file is re-sent on http backoff. See warning tip in docstring.
266
+ io_obj_initial_pos = None
267
+ if "data" in kwargs and isinstance(kwargs["data"], io.IOBase):
268
+ io_obj_initial_pos = kwargs["data"].tell()
269
+
270
+ session = get_session()
271
+ while True:
272
+ nb_tries += 1
273
+ try:
274
+ # If `data` is used and is a file object (or any IO), set back cursor to
275
+ # initial position.
276
+ if io_obj_initial_pos is not None:
277
+ kwargs["data"].seek(io_obj_initial_pos)
278
+
279
+ # Perform request and return if status_code is not in the retry list.
280
+ response = session.request(method=method, url=url, **kwargs)
281
+ if response.status_code not in retry_on_status_codes:
282
+ return response
283
+
284
+ # Wrong status code returned (HTTP 503 for instance)
285
+ logger.warning(f"HTTP Error {response.status_code} thrown while requesting {method} {url}")
286
+ if nb_tries > max_retries:
287
+ response.raise_for_status() # Will raise uncaught exception
288
+ # We return response to avoid infinite loop in the corner case where the
289
+ # user ask for retry on a status code that doesn't raise_for_status.
290
+ return response
291
+
292
+ except retry_on_exceptions as err:
293
+ logger.warning(f"'{err}' thrown while requesting {method} {url}")
294
+
295
+ if isinstance(err, requests.ConnectionError):
296
+ reset_sessions() # In case of SSLError it's best to reset the shared requests.Session objects
297
+
298
+ if nb_tries > max_retries:
299
+ raise err
300
+
301
+ # Sleep for X seconds
302
+ logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].")
303
+ time.sleep(sleep_time)
304
+
305
+ # Update sleep time for next retry
306
+ sleep_time = min(max_wait_time, sleep_time * 2) # Exponential backoff
307
+
308
+
309
+ def fix_hf_endpoint_in_url(url: str, endpoint: Optional[str]) -> str:
310
+ """Replace the default endpoint in a URL by a custom one.
311
+
312
+ This is useful when using a proxy and the Hugging Face Hub returns a URL with the default endpoint.
313
+ """
314
+ endpoint = endpoint or constants.ENDPOINT
315
+ # check if a proxy has been set => if yes, update the returned URL to use the proxy
316
+ if endpoint not in (None, constants._HF_DEFAULT_ENDPOINT, constants._HF_DEFAULT_STAGING_ENDPOINT):
317
+ url = url.replace(constants._HF_DEFAULT_ENDPOINT, endpoint)
318
+ url = url.replace(constants._HF_DEFAULT_STAGING_ENDPOINT, endpoint)
319
+ return url
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_pagination.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to handle pagination on Huggingface Hub."""
16
+
17
+ from typing import Dict, Iterable, Optional
18
+
19
+ import requests
20
+
21
+ from . import get_session, hf_raise_for_status, logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ def paginate(path: str, params: Dict, headers: Dict) -> Iterable:
28
+ """Fetch a list of models/datasets/spaces and paginate through results.
29
+
30
+ This is using the same "Link" header format as GitHub.
31
+ See:
32
+ - https://requests.readthedocs.io/en/latest/api/#requests.Response.links
33
+ - https://docs.github.com/en/rest/guides/traversing-with-pagination#link-header
34
+ """
35
+ session = get_session()
36
+ r = session.get(path, params=params, headers=headers)
37
+ hf_raise_for_status(r)
38
+ yield from r.json()
39
+
40
+ # Follow pages
41
+ # Next link already contains query params
42
+ next_page = _get_next_page(r)
43
+ while next_page is not None:
44
+ logger.debug(f"Pagination detected. Requesting next page: {next_page}")
45
+ r = session.get(next_page, headers=headers)
46
+ hf_raise_for_status(r)
47
+ yield from r.json()
48
+ next_page = _get_next_page(r)
49
+
50
+
51
+ def _get_next_page(response: requests.Response) -> Optional[str]:
52
+ return response.links.get("next", {}).get("url")
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_paths.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022-present, the HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Contains utilities to handle paths in Huggingface Hub."""
16
+
17
+ from fnmatch import fnmatch
18
+ from pathlib import Path
19
+ from typing import Callable, Generator, Iterable, List, Optional, TypeVar, Union
20
+
21
+
22
+ T = TypeVar("T")
23
+
24
+ # Always ignore `.git` and `.huggingface` folders in commits
25
+ DEFAULT_IGNORE_PATTERNS = [
26
+ ".git",
27
+ ".git/*",
28
+ "*/.git",
29
+ "**/.git/**",
30
+ ".huggingface",
31
+ ".huggingface/*",
32
+ "*/.huggingface",
33
+ "**/.huggingface/**",
34
+ ]
35
+ # Forbidden to commit these folders
36
+ FORBIDDEN_FOLDERS = [".git", ".huggingface"]
37
+
38
+
39
+ def filter_repo_objects(
40
+ items: Iterable[T],
41
+ *,
42
+ allow_patterns: Optional[Union[List[str], str]] = None,
43
+ ignore_patterns: Optional[Union[List[str], str]] = None,
44
+ key: Optional[Callable[[T], str]] = None,
45
+ ) -> Generator[T, None, None]:
46
+ """Filter repo objects based on an allowlist and a denylist.
47
+
48
+ Input must be a list of paths (`str` or `Path`) or a list of arbitrary objects.
49
+ In the later case, `key` must be provided and specifies a function of one argument
50
+ that is used to extract a path from each element in iterable.
51
+
52
+ Patterns are Unix shell-style wildcards which are NOT regular expressions. See
53
+ https://docs.python.org/3/library/fnmatch.html for more details.
54
+
55
+ Args:
56
+ items (`Iterable`):
57
+ List of items to filter.
58
+ allow_patterns (`str` or `List[str]`, *optional*):
59
+ Patterns constituting the allowlist. If provided, item paths must match at
60
+ least one pattern from the allowlist.
61
+ ignore_patterns (`str` or `List[str]`, *optional*):
62
+ Patterns constituting the denylist. If provided, item paths must not match
63
+ any patterns from the denylist.
64
+ key (`Callable[[T], str]`, *optional*):
65
+ Single-argument function to extract a path from each item. If not provided,
66
+ the `items` must already be `str` or `Path`.
67
+
68
+ Returns:
69
+ Filtered list of objects, as a generator.
70
+
71
+ Raises:
72
+ :class:`ValueError`:
73
+ If `key` is not provided and items are not `str` or `Path`.
74
+
75
+ Example usage with paths:
76
+ ```python
77
+ >>> # Filter only PDFs that are not hidden.
78
+ >>> list(filter_repo_objects(
79
+ ... ["aaa.PDF", "bbb.jpg", ".ccc.pdf", ".ddd.png"],
80
+ ... allow_patterns=["*.pdf"],
81
+ ... ignore_patterns=[".*"],
82
+ ... ))
83
+ ["aaa.pdf"]
84
+ ```
85
+
86
+ Example usage with objects:
87
+ ```python
88
+ >>> list(filter_repo_objects(
89
+ ... [
90
+ ... CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf")
91
+ ... CommitOperationAdd(path_or_fileobj="/tmp/bbb.jpg", path_in_repo="bbb.jpg")
92
+ ... CommitOperationAdd(path_or_fileobj="/tmp/.ccc.pdf", path_in_repo=".ccc.pdf")
93
+ ... CommitOperationAdd(path_or_fileobj="/tmp/.ddd.png", path_in_repo=".ddd.png")
94
+ ... ],
95
+ ... allow_patterns=["*.pdf"],
96
+ ... ignore_patterns=[".*"],
97
+ ... key=lambda x: x.repo_in_path
98
+ ... ))
99
+ [CommitOperationAdd(path_or_fileobj="/tmp/aaa.pdf", path_in_repo="aaa.pdf")]
100
+ ```
101
+ """
102
+ if isinstance(allow_patterns, str):
103
+ allow_patterns = [allow_patterns]
104
+
105
+ if isinstance(ignore_patterns, str):
106
+ ignore_patterns = [ignore_patterns]
107
+
108
+ if key is None:
109
+
110
+ def _identity(item: T) -> str:
111
+ if isinstance(item, str):
112
+ return item
113
+ if isinstance(item, Path):
114
+ return str(item)
115
+ raise ValueError(f"Please provide `key` argument in `filter_repo_objects`: `{item}` is not a string.")
116
+
117
+ key = _identity # Items must be `str` or `Path`, otherwise raise ValueError
118
+
119
+ for item in items:
120
+ path = key(item)
121
+
122
+ # Skip if there's an allowlist and path doesn't match any
123
+ if allow_patterns is not None and not any(fnmatch(path, r) for r in allow_patterns):
124
+ continue
125
+
126
+ # Skip if there's a denylist and path matches any
127
+ if ignore_patterns is not None and any(fnmatch(path, r) for r in ignore_patterns):
128
+ continue
129
+
130
+ yield item
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_subprocess.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # coding=utf-8
3
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License
16
+ """Contains utilities to easily handle subprocesses in `huggingface_hub`."""
17
+
18
+ import os
19
+ import subprocess
20
+ import sys
21
+ from contextlib import contextmanager
22
+ from io import StringIO
23
+ from pathlib import Path
24
+ from typing import IO, Generator, List, Optional, Tuple, Union
25
+
26
+ from .logging import get_logger
27
+
28
+
29
+ logger = get_logger(__name__)
30
+
31
+
32
+ @contextmanager
33
+ def capture_output() -> Generator[StringIO, None, None]:
34
+ """Capture output that is printed to terminal.
35
+
36
+ Taken from https://stackoverflow.com/a/34738440
37
+
38
+ Example:
39
+ ```py
40
+ >>> with capture_output() as output:
41
+ ... print("hello world")
42
+ >>> assert output.getvalue() == "hello world\n"
43
+ ```
44
+ """
45
+ output = StringIO()
46
+ previous_output = sys.stdout
47
+ sys.stdout = output
48
+ yield output
49
+ sys.stdout = previous_output
50
+
51
+
52
+ def run_subprocess(
53
+ command: Union[str, List[str]],
54
+ folder: Optional[Union[str, Path]] = None,
55
+ check=True,
56
+ **kwargs,
57
+ ) -> subprocess.CompletedProcess:
58
+ """
59
+ Method to run subprocesses. Calling this will capture the `stderr` and `stdout`,
60
+ please call `subprocess.run` manually in case you would like for them not to
61
+ be captured.
62
+
63
+ Args:
64
+ command (`str` or `List[str]`):
65
+ The command to execute as a string or list of strings.
66
+ folder (`str`, *optional*):
67
+ The folder in which to run the command. Defaults to current working
68
+ directory (from `os.getcwd()`).
69
+ check (`bool`, *optional*, defaults to `True`):
70
+ Setting `check` to `True` will raise a `subprocess.CalledProcessError`
71
+ when the subprocess has a non-zero exit code.
72
+ kwargs (`Dict[str]`):
73
+ Keyword arguments to be passed to the `subprocess.run` underlying command.
74
+
75
+ Returns:
76
+ `subprocess.CompletedProcess`: The completed process.
77
+ """
78
+ if isinstance(command, str):
79
+ command = command.split()
80
+
81
+ if isinstance(folder, Path):
82
+ folder = str(folder)
83
+
84
+ return subprocess.run(
85
+ command,
86
+ stderr=subprocess.PIPE,
87
+ stdout=subprocess.PIPE,
88
+ check=check,
89
+ encoding="utf-8",
90
+ errors="replace", # if not utf-8, replace char by �
91
+ cwd=folder or os.getcwd(),
92
+ **kwargs,
93
+ )
94
+
95
+
96
+ @contextmanager
97
+ def run_interactive_subprocess(
98
+ command: Union[str, List[str]],
99
+ folder: Optional[Union[str, Path]] = None,
100
+ **kwargs,
101
+ ) -> Generator[Tuple[IO[str], IO[str]], None, None]:
102
+ """Run a subprocess in an interactive mode in a context manager.
103
+
104
+ Args:
105
+ command (`str` or `List[str]`):
106
+ The command to execute as a string or list of strings.
107
+ folder (`str`, *optional*):
108
+ The folder in which to run the command. Defaults to current working
109
+ directory (from `os.getcwd()`).
110
+ kwargs (`Dict[str]`):
111
+ Keyword arguments to be passed to the `subprocess.run` underlying command.
112
+
113
+ Returns:
114
+ `Tuple[IO[str], IO[str]]`: A tuple with `stdin` and `stdout` to interact
115
+ with the process (input and output are utf-8 encoded).
116
+
117
+ Example:
118
+ ```python
119
+ with _interactive_subprocess("git credential-store get") as (stdin, stdout):
120
+ # Write to stdin
121
+ stdin.write("url=hf.co\nusername=obama\n".encode("utf-8"))
122
+ stdin.flush()
123
+
124
+ # Read from stdout
125
+ output = stdout.read().decode("utf-8")
126
+ ```
127
+ """
128
+ if isinstance(command, str):
129
+ command = command.split()
130
+
131
+ with subprocess.Popen(
132
+ command,
133
+ stdin=subprocess.PIPE,
134
+ stdout=subprocess.PIPE,
135
+ stderr=subprocess.STDOUT,
136
+ encoding="utf-8",
137
+ errors="replace", # if not utf-8, replace char by �
138
+ cwd=folder or os.getcwd(),
139
+ **kwargs,
140
+ ) as process:
141
+ assert process.stdin is not None, "subprocess is opened as subprocess.PIPE"
142
+ assert process.stdout is not None, "subprocess is opened as subprocess.PIPE"
143
+ yield process.stdin, process.stdout
llmeval-env/lib/python3.10/site-packages/huggingface_hub/utils/_telemetry.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from queue import Queue
2
+ from threading import Lock, Thread
3
+ from typing import Dict, Optional, Union
4
+ from urllib.parse import quote
5
+
6
+ from .. import constants, logging
7
+ from . import build_hf_headers, get_session, hf_raise_for_status
8
+
9
+
10
+ logger = logging.get_logger(__name__)
11
+
12
+ # Telemetry is sent by a separate thread to avoid blocking the main thread.
13
+ # A daemon thread is started once and consume tasks from the _TELEMETRY_QUEUE.
14
+ # If the thread stops for some reason -shouldn't happen-, we restart a new one.
15
+ _TELEMETRY_THREAD: Optional[Thread] = None
16
+ _TELEMETRY_THREAD_LOCK = Lock() # Lock to avoid starting multiple threads in parallel
17
+ _TELEMETRY_QUEUE: Queue = Queue()
18
+
19
+
20
+ def send_telemetry(
21
+ topic: str,
22
+ *,
23
+ library_name: Optional[str] = None,
24
+ library_version: Optional[str] = None,
25
+ user_agent: Union[Dict, str, None] = None,
26
+ ) -> None:
27
+ """
28
+ Sends telemetry that helps tracking usage of different HF libraries.
29
+
30
+ This usage data helps us debug issues and prioritize new features. However, we understand that not everyone wants
31
+ to share additional information, and we respect your privacy. You can disable telemetry collection by setting the
32
+ `HF_HUB_DISABLE_TELEMETRY=1` as environment variable. Telemetry is also disabled in offline mode (i.e. when setting
33
+ `HF_HUB_OFFLINE=1`).
34
+
35
+ Telemetry collection is run in a separate thread to minimize impact for the user.
36
+
37
+ Args:
38
+ topic (`str`):
39
+ Name of the topic that is monitored. The topic is directly used to build the URL. If you want to monitor
40
+ subtopics, just use "/" separation. Examples: "gradio", "transformers/examples",...
41
+ library_name (`str`, *optional*):
42
+ The name of the library that is making the HTTP request. Will be added to the user-agent header.
43
+ library_version (`str`, *optional*):
44
+ The version of the library that is making the HTTP request. Will be added to the user-agent header.
45
+ user_agent (`str`, `dict`, *optional*):
46
+ The user agent info in the form of a dictionary or a single string. It will be completed with information about the installed packages.
47
+
48
+ Example:
49
+ ```py
50
+ >>> from huggingface_hub.utils import send_telemetry
51
+
52
+ # Send telemetry without library information
53
+ >>> send_telemetry("ping")
54
+
55
+ # Send telemetry to subtopic with library information
56
+ >>> send_telemetry("gradio/local_link", library_name="gradio", library_version="3.22.1")
57
+
58
+ # Send telemetry with additional data
59
+ >>> send_telemetry(
60
+ ... topic="examples",
61
+ ... library_name="transformers",
62
+ ... library_version="4.26.0",
63
+ ... user_agent={"pipeline": "text_classification", "framework": "flax"},
64
+ ... )
65
+ ```
66
+ """
67
+ if constants.HF_HUB_OFFLINE or constants.HF_HUB_DISABLE_TELEMETRY:
68
+ return
69
+
70
+ _start_telemetry_thread() # starts thread only if doesn't exist yet
71
+ _TELEMETRY_QUEUE.put(
72
+ {"topic": topic, "library_name": library_name, "library_version": library_version, "user_agent": user_agent}
73
+ )
74
+
75
+
76
+ def _start_telemetry_thread():
77
+ """Start a daemon thread to consume tasks from the telemetry queue.
78
+
79
+ If the thread is interrupted, start a new one.
80
+ """
81
+ with _TELEMETRY_THREAD_LOCK: # avoid to start multiple threads if called concurrently
82
+ global _TELEMETRY_THREAD
83
+ if _TELEMETRY_THREAD is None or not _TELEMETRY_THREAD.is_alive():
84
+ _TELEMETRY_THREAD = Thread(target=_telemetry_worker, daemon=True)
85
+ _TELEMETRY_THREAD.start()
86
+
87
+
88
+ def _telemetry_worker():
89
+ """Wait for a task and consume it."""
90
+ while True:
91
+ kwargs = _TELEMETRY_QUEUE.get()
92
+ _send_telemetry_in_thread(**kwargs)
93
+ _TELEMETRY_QUEUE.task_done()
94
+
95
+
96
+ def _send_telemetry_in_thread(
97
+ topic: str,
98
+ *,
99
+ library_name: Optional[str] = None,
100
+ library_version: Optional[str] = None,
101
+ user_agent: Union[Dict, str, None] = None,
102
+ ) -> None:
103
+ """Contains the actual data sending data to the Hub."""
104
+ path = "/".join(quote(part) for part in topic.split("/") if len(part) > 0)
105
+ try:
106
+ r = get_session().head(
107
+ f"{constants.ENDPOINT}/api/telemetry/{path}",
108
+ headers=build_hf_headers(
109
+ token=False, # no need to send a token for telemetry
110
+ library_name=library_name,
111
+ library_version=library_version,
112
+ user_agent=user_agent,
113
+ ),
114
+ )
115
+ hf_raise_for_status(r)
116
+ except Exception as e:
117
+ # We don't want to error in case of connection errors of any kind.
118
+ logger.debug(f"Error while sending telemetry: {e}")
llmeval-env/lib/python3.10/site-packages/numexpr-2.10.0.dist-info/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2007,2008 David M. Cooke <[email protected]>
2
+ Copyright (c) 2009,2010 Francesc Alted <[email protected]>
3
+ Copyright (c) 2011- See AUTHORS.txt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
llmeval-env/lib/python3.10/site-packages/scipy/cluster/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-310.pyc ADDED
Binary file (131 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/cluster/__pycache__/vq.cpython-310.pyc ADDED
Binary file (28.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/hierarchy_test_data.cpython-310.pyc ADDED
Binary file (4.69 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/cluster/tests/__pycache__/test_vq.cpython-310.pyc ADDED
Binary file (17 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/datasets/__init__.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ================================
3
+ Datasets (:mod:`scipy.datasets`)
4
+ ================================
5
+
6
+ .. currentmodule:: scipy.datasets
7
+
8
+ Dataset Methods
9
+ ===============
10
+
11
+ .. autosummary::
12
+ :toctree: generated/
13
+
14
+ ascent
15
+ face
16
+ electrocardiogram
17
+
18
+ Utility Methods
19
+ ===============
20
+
21
+ .. autosummary::
22
+ :toctree: generated/
23
+
24
+ download_all -- Download all the dataset files to specified path.
25
+ clear_cache -- Clear cached dataset directory.
26
+
27
+
28
+ Usage of Datasets
29
+ =================
30
+
31
+ SciPy dataset methods can be simply called as follows: ``'<dataset-name>()'``
32
+ This downloads the dataset files over the network once, and saves the cache,
33
+ before returning a `numpy.ndarray` object representing the dataset.
34
+
35
+ Note that the return data structure and data type might be different for
36
+ different dataset methods. For a more detailed example on usage, please look
37
+ into the particular dataset method documentation above.
38
+
39
+
40
+ How dataset retrieval and storage works
41
+ =======================================
42
+
43
+ SciPy dataset files are stored within individual github repositories under the
44
+ SciPy GitHub organization, following a naming convention as
45
+ ``'dataset-<name>'``, for example `scipy.datasets.face` files live at
46
+ https://github.com/scipy/dataset-face. The `scipy.datasets` submodule utilizes
47
+ and depends on `Pooch <https://www.fatiando.org/pooch/latest/>`_, a Python
48
+ package built to simplify fetching data files. Pooch uses these repos to
49
+ retrieve the respective dataset files when calling the dataset function.
50
+
51
+ A registry of all the datasets, essentially a mapping of filenames with their
52
+ SHA256 hash and repo urls are maintained, which Pooch uses to handle and verify
53
+ the downloads on function call. After downloading the dataset once, the files
54
+ are saved in the system cache directory under ``'scipy-data'``.
55
+
56
+ Dataset cache locations may vary on different platforms.
57
+
58
+ For macOS::
59
+
60
+ '~/Library/Caches/scipy-data'
61
+
62
+ For Linux and other Unix-like platforms::
63
+
64
+ '~/.cache/scipy-data' # or the value of the XDG_CACHE_HOME env var, if defined
65
+
66
+ For Windows::
67
+
68
+ 'C:\\Users\\<user>\\AppData\\Local\\<AppAuthor>\\scipy-data\\Cache'
69
+
70
+
71
+ In environments with constrained network connectivity for various security
72
+ reasons or on systems without continuous internet connections, one may manually
73
+ load the cache of the datasets by placing the contents of the dataset repo in
74
+ the above mentioned cache directory to avoid fetching dataset errors without
75
+ the internet connectivity.
76
+
77
+ """
78
+
79
+
80
+ from ._fetchers import face, ascent, electrocardiogram
81
+ from ._download_all import download_all
82
+ from ._utils import clear_cache
83
+
84
+ __all__ = ['ascent', 'electrocardiogram', 'face',
85
+ 'download_all', 'clear_cache']
86
+
87
+
88
+ from scipy._lib._testutils import PytestTester
89
+ test = PytestTester(__name__)
90
+ del PytestTester
llmeval-env/lib/python3.10/site-packages/scipy/datasets/_download_all.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Platform independent script to download all the
3
+ `scipy.datasets` module data files.
4
+ This doesn't require a full scipy build.
5
+
6
+ Run: python _download_all.py <download_dir>
7
+ """
8
+
9
+ import argparse
10
+ try:
11
+ import pooch
12
+ except ImportError:
13
+ pooch = None
14
+
15
+
16
+ if __package__ is None or __package__ == '':
17
+ # Running as python script, use absolute import
18
+ import _registry # type: ignore
19
+ else:
20
+ # Running as python module, use relative import
21
+ from . import _registry
22
+
23
+
24
+ def download_all(path=None):
25
+ """
26
+ Utility method to download all the dataset files
27
+ for `scipy.datasets` module.
28
+
29
+ Parameters
30
+ ----------
31
+ path : str, optional
32
+ Directory path to download all the dataset files.
33
+ If None, default to the system cache_dir detected by pooch.
34
+ """
35
+ if pooch is None:
36
+ raise ImportError("Missing optional dependency 'pooch' required "
37
+ "for scipy.datasets module. Please use pip or "
38
+ "conda to install 'pooch'.")
39
+ if path is None:
40
+ path = pooch.os_cache('scipy-data')
41
+ for dataset_name, dataset_hash in _registry.registry.items():
42
+ pooch.retrieve(url=_registry.registry_urls[dataset_name],
43
+ known_hash=dataset_hash,
44
+ fname=dataset_name, path=path)
45
+
46
+
47
+ def main():
48
+ parser = argparse.ArgumentParser(description='Download SciPy data files.')
49
+ parser.add_argument("path", nargs='?', type=str,
50
+ default=pooch.os_cache('scipy-data'),
51
+ help="Directory path to download all the data files.")
52
+ args = parser.parse_args()
53
+ download_all(args.path)
54
+
55
+
56
+ if __name__ == "__main__":
57
+ main()
llmeval-env/lib/python3.10/site-packages/scipy/datasets/_fetchers.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy import array, frombuffer, load
2
+ from ._registry import registry, registry_urls
3
+
4
+ try:
5
+ import pooch
6
+ except ImportError:
7
+ pooch = None
8
+ data_fetcher = None
9
+ else:
10
+ data_fetcher = pooch.create(
11
+ # Use the default cache folder for the operating system
12
+ # Pooch uses appdirs (https://github.com/ActiveState/appdirs) to
13
+ # select an appropriate directory for the cache on each platform.
14
+ path=pooch.os_cache("scipy-data"),
15
+
16
+ # The remote data is on Github
17
+ # base_url is a required param, even though we override this
18
+ # using individual urls in the registry.
19
+ base_url="https://github.com/scipy/",
20
+ registry=registry,
21
+ urls=registry_urls
22
+ )
23
+
24
+
25
+ def fetch_data(dataset_name, data_fetcher=data_fetcher):
26
+ if data_fetcher is None:
27
+ raise ImportError("Missing optional dependency 'pooch' required "
28
+ "for scipy.datasets module. Please use pip or "
29
+ "conda to install 'pooch'.")
30
+ # The "fetch" method returns the full path to the downloaded data file.
31
+ return data_fetcher.fetch(dataset_name)
32
+
33
+
34
+ def ascent():
35
+ """
36
+ Get an 8-bit grayscale bit-depth, 512 x 512 derived image for easy
37
+ use in demos.
38
+
39
+ The image is derived from accent-to-the-top.jpg at
40
+ http://www.public-domain-image.com/people-public-domain-images-pictures/
41
+
42
+ Parameters
43
+ ----------
44
+ None
45
+
46
+ Returns
47
+ -------
48
+ ascent : ndarray
49
+ convenient image to use for testing and demonstration
50
+
51
+ Examples
52
+ --------
53
+ >>> import scipy.datasets
54
+ >>> ascent = scipy.datasets.ascent()
55
+ >>> ascent.shape
56
+ (512, 512)
57
+ >>> ascent.max()
58
+ 255
59
+
60
+ >>> import matplotlib.pyplot as plt
61
+ >>> plt.gray()
62
+ >>> plt.imshow(ascent)
63
+ >>> plt.show()
64
+
65
+ """
66
+ import pickle
67
+
68
+ # The file will be downloaded automatically the first time this is run,
69
+ # returning the path to the downloaded file. Afterwards, Pooch finds
70
+ # it in the local cache and doesn't repeat the download.
71
+ fname = fetch_data("ascent.dat")
72
+ # Now we just need to load it with our standard Python tools.
73
+ with open(fname, 'rb') as f:
74
+ ascent = array(pickle.load(f))
75
+ return ascent
76
+
77
+
78
+ def electrocardiogram():
79
+ """
80
+ Load an electrocardiogram as an example for a 1-D signal.
81
+
82
+ The returned signal is a 5 minute long electrocardiogram (ECG), a medical
83
+ recording of the heart's electrical activity, sampled at 360 Hz.
84
+
85
+ Returns
86
+ -------
87
+ ecg : ndarray
88
+ The electrocardiogram in millivolt (mV) sampled at 360 Hz.
89
+
90
+ Notes
91
+ -----
92
+ The provided signal is an excerpt (19:35 to 24:35) from the `record 208`_
93
+ (lead MLII) provided by the MIT-BIH Arrhythmia Database [1]_ on
94
+ PhysioNet [2]_. The excerpt includes noise induced artifacts, typical
95
+ heartbeats as well as pathological changes.
96
+
97
+ .. _record 208: https://physionet.org/physiobank/database/html/mitdbdir/records.htm#208
98
+
99
+ .. versionadded:: 1.1.0
100
+
101
+ References
102
+ ----------
103
+ .. [1] Moody GB, Mark RG. The impact of the MIT-BIH Arrhythmia Database.
104
+ IEEE Eng in Med and Biol 20(3):45-50 (May-June 2001).
105
+ (PMID: 11446209); :doi:`10.13026/C2F305`
106
+ .. [2] Goldberger AL, Amaral LAN, Glass L, Hausdorff JM, Ivanov PCh,
107
+ Mark RG, Mietus JE, Moody GB, Peng C-K, Stanley HE. PhysioBank,
108
+ PhysioToolkit, and PhysioNet: Components of a New Research Resource
109
+ for Complex Physiologic Signals. Circulation 101(23):e215-e220;
110
+ :doi:`10.1161/01.CIR.101.23.e215`
111
+
112
+ Examples
113
+ --------
114
+ >>> from scipy.datasets import electrocardiogram
115
+ >>> ecg = electrocardiogram()
116
+ >>> ecg
117
+ array([-0.245, -0.215, -0.185, ..., -0.405, -0.395, -0.385])
118
+ >>> ecg.shape, ecg.mean(), ecg.std()
119
+ ((108000,), -0.16510875, 0.5992473991177294)
120
+
121
+ As stated the signal features several areas with a different morphology.
122
+ E.g., the first few seconds show the electrical activity of a heart in
123
+ normal sinus rhythm as seen below.
124
+
125
+ >>> import numpy as np
126
+ >>> import matplotlib.pyplot as plt
127
+ >>> fs = 360
128
+ >>> time = np.arange(ecg.size) / fs
129
+ >>> plt.plot(time, ecg)
130
+ >>> plt.xlabel("time in s")
131
+ >>> plt.ylabel("ECG in mV")
132
+ >>> plt.xlim(9, 10.2)
133
+ >>> plt.ylim(-1, 1.5)
134
+ >>> plt.show()
135
+
136
+ After second 16, however, the first premature ventricular contractions,
137
+ also called extrasystoles, appear. These have a different morphology
138
+ compared to typical heartbeats. The difference can easily be observed
139
+ in the following plot.
140
+
141
+ >>> plt.plot(time, ecg)
142
+ >>> plt.xlabel("time in s")
143
+ >>> plt.ylabel("ECG in mV")
144
+ >>> plt.xlim(46.5, 50)
145
+ >>> plt.ylim(-2, 1.5)
146
+ >>> plt.show()
147
+
148
+ At several points large artifacts disturb the recording, e.g.:
149
+
150
+ >>> plt.plot(time, ecg)
151
+ >>> plt.xlabel("time in s")
152
+ >>> plt.ylabel("ECG in mV")
153
+ >>> plt.xlim(207, 215)
154
+ >>> plt.ylim(-2, 3.5)
155
+ >>> plt.show()
156
+
157
+ Finally, examining the power spectrum reveals that most of the biosignal is
158
+ made up of lower frequencies. At 60 Hz the noise induced by the mains
159
+ electricity can be clearly observed.
160
+
161
+ >>> from scipy.signal import welch
162
+ >>> f, Pxx = welch(ecg, fs=fs, nperseg=2048, scaling="spectrum")
163
+ >>> plt.semilogy(f, Pxx)
164
+ >>> plt.xlabel("Frequency in Hz")
165
+ >>> plt.ylabel("Power spectrum of the ECG in mV**2")
166
+ >>> plt.xlim(f[[0, -1]])
167
+ >>> plt.show()
168
+ """
169
+ fname = fetch_data("ecg.dat")
170
+ with load(fname) as file:
171
+ ecg = file["ecg"].astype(int) # np.uint16 -> int
172
+ # Convert raw output of ADC to mV: (ecg - adc_zero) / adc_gain
173
+ ecg = (ecg - 1024) / 200.0
174
+ return ecg
175
+
176
+
177
+ def face(gray=False):
178
+ """
179
+ Get a 1024 x 768, color image of a raccoon face.
180
+
181
+ raccoon-procyon-lotor.jpg at http://www.public-domain-image.com
182
+
183
+ Parameters
184
+ ----------
185
+ gray : bool, optional
186
+ If True return 8-bit grey-scale image, otherwise return a color image
187
+
188
+ Returns
189
+ -------
190
+ face : ndarray
191
+ image of a raccoon face
192
+
193
+ Examples
194
+ --------
195
+ >>> import scipy.datasets
196
+ >>> face = scipy.datasets.face()
197
+ >>> face.shape
198
+ (768, 1024, 3)
199
+ >>> face.max()
200
+ 255
201
+ >>> face.dtype
202
+ dtype('uint8')
203
+
204
+ >>> import matplotlib.pyplot as plt
205
+ >>> plt.gray()
206
+ >>> plt.imshow(face)
207
+ >>> plt.show()
208
+
209
+ """
210
+ import bz2
211
+ fname = fetch_data("face.dat")
212
+ with open(fname, 'rb') as f:
213
+ rawdata = f.read()
214
+ face_data = bz2.decompress(rawdata)
215
+ face = frombuffer(face_data, dtype='uint8')
216
+ face.shape = (768, 1024, 3)
217
+ if gray is True:
218
+ face = (0.21 * face[:, :, 0] + 0.71 * face[:, :, 1] +
219
+ 0.07 * face[:, :, 2]).astype('uint8')
220
+ return face
llmeval-env/lib/python3.10/site-packages/scipy/datasets/_registry.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ##########################################################################
2
+ # This file serves as the dataset registry for SciPy Datasets SubModule.
3
+ ##########################################################################
4
+
5
+
6
+ # To generate the SHA256 hash, use the command
7
+ # openssl sha256 <filename>
8
+ registry = {
9
+ "ascent.dat": "03ce124c1afc880f87b55f6b061110e2e1e939679184f5614e38dacc6c1957e2",
10
+ "ecg.dat": "f20ad3365fb9b7f845d0e5c48b6fe67081377ee466c3a220b7f69f35c8958baf",
11
+ "face.dat": "9d8b0b4d081313e2b485748c770472e5a95ed1738146883d84c7030493e82886"
12
+ }
13
+
14
+ registry_urls = {
15
+ "ascent.dat": "https://raw.githubusercontent.com/scipy/dataset-ascent/main/ascent.dat",
16
+ "ecg.dat": "https://raw.githubusercontent.com/scipy/dataset-ecg/main/ecg.dat",
17
+ "face.dat": "https://raw.githubusercontent.com/scipy/dataset-face/main/face.dat"
18
+ }
19
+
20
+ # dataset method mapping with their associated filenames
21
+ # <method_name> : ["filename1", "filename2", ...]
22
+ method_files_map = {
23
+ "ascent": ["ascent.dat"],
24
+ "electrocardiogram": ["ecg.dat"],
25
+ "face": ["face.dat"]
26
+ }
llmeval-env/lib/python3.10/site-packages/scipy/datasets/_utils.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from ._registry import method_files_map
4
+
5
+ try:
6
+ import platformdirs
7
+ except ImportError:
8
+ platformdirs = None # type: ignore[assignment]
9
+
10
+
11
+ def _clear_cache(datasets, cache_dir=None, method_map=None):
12
+ if method_map is None:
13
+ # Use SciPy Datasets method map
14
+ method_map = method_files_map
15
+ if cache_dir is None:
16
+ # Use default cache_dir path
17
+ if platformdirs is None:
18
+ # platformdirs is pooch dependency
19
+ raise ImportError("Missing optional dependency 'pooch' required "
20
+ "for scipy.datasets module. Please use pip or "
21
+ "conda to install 'pooch'.")
22
+ cache_dir = platformdirs.user_cache_dir("scipy-data")
23
+
24
+ if not os.path.exists(cache_dir):
25
+ print(f"Cache Directory {cache_dir} doesn't exist. Nothing to clear.")
26
+ return
27
+
28
+ if datasets is None:
29
+ print(f"Cleaning the cache directory {cache_dir}!")
30
+ shutil.rmtree(cache_dir)
31
+ else:
32
+ if not isinstance(datasets, (list, tuple)):
33
+ # single dataset method passed should be converted to list
34
+ datasets = [datasets, ]
35
+ for dataset in datasets:
36
+ assert callable(dataset)
37
+ dataset_name = dataset.__name__ # Name of the dataset method
38
+ if dataset_name not in method_map:
39
+ raise ValueError(f"Dataset method {dataset_name} doesn't "
40
+ "exist. Please check if the passed dataset "
41
+ "is a subset of the following dataset "
42
+ f"methods: {list(method_map.keys())}")
43
+
44
+ data_files = method_map[dataset_name]
45
+ data_filepaths = [os.path.join(cache_dir, file)
46
+ for file in data_files]
47
+ for data_filepath in data_filepaths:
48
+ if os.path.exists(data_filepath):
49
+ print("Cleaning the file "
50
+ f"{os.path.split(data_filepath)[1]} "
51
+ f"for dataset {dataset_name}")
52
+ os.remove(data_filepath)
53
+ else:
54
+ print(f"Path {data_filepath} doesn't exist. "
55
+ "Nothing to clear.")
56
+
57
+
58
+ def clear_cache(datasets=None):
59
+ """
60
+ Cleans the scipy datasets cache directory.
61
+
62
+ If a scipy.datasets method or a list/tuple of the same is
63
+ provided, then clear_cache removes all the data files
64
+ associated to the passed dataset method callable(s).
65
+
66
+ By default, it removes all the cached data files.
67
+
68
+ Parameters
69
+ ----------
70
+ datasets : callable or list/tuple of callable or None
71
+
72
+ Examples
73
+ --------
74
+ >>> from scipy import datasets
75
+ >>> ascent_array = datasets.ascent()
76
+ >>> ascent_array.shape
77
+ (512, 512)
78
+ >>> datasets.clear_cache([datasets.ascent])
79
+ Cleaning the file ascent.dat for dataset ascent
80
+ """
81
+ _clear_cache(datasets)
llmeval-env/lib/python3.10/site-packages/scipy/signal/_arraytools.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Functions for acting on a axis of an array.
3
+ """
4
+ import numpy as np
5
+
6
+
7
+ def axis_slice(a, start=None, stop=None, step=None, axis=-1):
8
+ """Take a slice along axis 'axis' from 'a'.
9
+
10
+ Parameters
11
+ ----------
12
+ a : numpy.ndarray
13
+ The array to be sliced.
14
+ start, stop, step : int or None
15
+ The slice parameters.
16
+ axis : int, optional
17
+ The axis of `a` to be sliced.
18
+
19
+ Examples
20
+ --------
21
+ >>> import numpy as np
22
+ >>> from scipy.signal._arraytools import axis_slice
23
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
24
+ >>> axis_slice(a, start=0, stop=1, axis=1)
25
+ array([[1],
26
+ [4],
27
+ [7]])
28
+ >>> axis_slice(a, start=1, axis=0)
29
+ array([[4, 5, 6],
30
+ [7, 8, 9]])
31
+
32
+ Notes
33
+ -----
34
+ The keyword arguments start, stop and step are used by calling
35
+ slice(start, stop, step). This implies axis_slice() does not
36
+ handle its arguments the exactly the same as indexing. To select
37
+ a single index k, for example, use
38
+ axis_slice(a, start=k, stop=k+1)
39
+ In this case, the length of the axis 'axis' in the result will
40
+ be 1; the trivial dimension is not removed. (Use numpy.squeeze()
41
+ to remove trivial axes.)
42
+ """
43
+ a_slice = [slice(None)] * a.ndim
44
+ a_slice[axis] = slice(start, stop, step)
45
+ b = a[tuple(a_slice)]
46
+ return b
47
+
48
+
49
+ def axis_reverse(a, axis=-1):
50
+ """Reverse the 1-D slices of `a` along axis `axis`.
51
+
52
+ Returns axis_slice(a, step=-1, axis=axis).
53
+ """
54
+ return axis_slice(a, step=-1, axis=axis)
55
+
56
+
57
+ def odd_ext(x, n, axis=-1):
58
+ """
59
+ Odd extension at the boundaries of an array
60
+
61
+ Generate a new ndarray by making an odd extension of `x` along an axis.
62
+
63
+ Parameters
64
+ ----------
65
+ x : ndarray
66
+ The array to be extended.
67
+ n : int
68
+ The number of elements by which to extend `x` at each end of the axis.
69
+ axis : int, optional
70
+ The axis along which to extend `x`. Default is -1.
71
+
72
+ Examples
73
+ --------
74
+ >>> import numpy as np
75
+ >>> from scipy.signal._arraytools import odd_ext
76
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
77
+ >>> odd_ext(a, 2)
78
+ array([[-1, 0, 1, 2, 3, 4, 5, 6, 7],
79
+ [-4, -1, 0, 1, 4, 9, 16, 23, 28]])
80
+
81
+ Odd extension is a "180 degree rotation" at the endpoints of the original
82
+ array:
83
+
84
+ >>> t = np.linspace(0, 1.5, 100)
85
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
86
+ >>> b = odd_ext(a, 40)
87
+ >>> import matplotlib.pyplot as plt
88
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='odd extension')
89
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
90
+ >>> plt.legend(loc='best')
91
+ >>> plt.show()
92
+ """
93
+ if n < 1:
94
+ return x
95
+ if n > x.shape[axis] - 1:
96
+ raise ValueError(("The extension length n (%d) is too big. " +
97
+ "It must not exceed x.shape[axis]-1, which is %d.")
98
+ % (n, x.shape[axis] - 1))
99
+ left_end = axis_slice(x, start=0, stop=1, axis=axis)
100
+ left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
101
+ right_end = axis_slice(x, start=-1, axis=axis)
102
+ right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
103
+ ext = np.concatenate((2 * left_end - left_ext,
104
+ x,
105
+ 2 * right_end - right_ext),
106
+ axis=axis)
107
+ return ext
108
+
109
+
110
+ def even_ext(x, n, axis=-1):
111
+ """
112
+ Even extension at the boundaries of an array
113
+
114
+ Generate a new ndarray by making an even extension of `x` along an axis.
115
+
116
+ Parameters
117
+ ----------
118
+ x : ndarray
119
+ The array to be extended.
120
+ n : int
121
+ The number of elements by which to extend `x` at each end of the axis.
122
+ axis : int, optional
123
+ The axis along which to extend `x`. Default is -1.
124
+
125
+ Examples
126
+ --------
127
+ >>> import numpy as np
128
+ >>> from scipy.signal._arraytools import even_ext
129
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
130
+ >>> even_ext(a, 2)
131
+ array([[ 3, 2, 1, 2, 3, 4, 5, 4, 3],
132
+ [ 4, 1, 0, 1, 4, 9, 16, 9, 4]])
133
+
134
+ Even extension is a "mirror image" at the boundaries of the original array:
135
+
136
+ >>> t = np.linspace(0, 1.5, 100)
137
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
138
+ >>> b = even_ext(a, 40)
139
+ >>> import matplotlib.pyplot as plt
140
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='even extension')
141
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
142
+ >>> plt.legend(loc='best')
143
+ >>> plt.show()
144
+ """
145
+ if n < 1:
146
+ return x
147
+ if n > x.shape[axis] - 1:
148
+ raise ValueError(("The extension length n (%d) is too big. " +
149
+ "It must not exceed x.shape[axis]-1, which is %d.")
150
+ % (n, x.shape[axis] - 1))
151
+ left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
152
+ right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
153
+ ext = np.concatenate((left_ext,
154
+ x,
155
+ right_ext),
156
+ axis=axis)
157
+ return ext
158
+
159
+
160
+ def const_ext(x, n, axis=-1):
161
+ """
162
+ Constant extension at the boundaries of an array
163
+
164
+ Generate a new ndarray that is a constant extension of `x` along an axis.
165
+
166
+ The extension repeats the values at the first and last element of
167
+ the axis.
168
+
169
+ Parameters
170
+ ----------
171
+ x : ndarray
172
+ The array to be extended.
173
+ n : int
174
+ The number of elements by which to extend `x` at each end of the axis.
175
+ axis : int, optional
176
+ The axis along which to extend `x`. Default is -1.
177
+
178
+ Examples
179
+ --------
180
+ >>> import numpy as np
181
+ >>> from scipy.signal._arraytools import const_ext
182
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
183
+ >>> const_ext(a, 2)
184
+ array([[ 1, 1, 1, 2, 3, 4, 5, 5, 5],
185
+ [ 0, 0, 0, 1, 4, 9, 16, 16, 16]])
186
+
187
+ Constant extension continues with the same values as the endpoints of the
188
+ array:
189
+
190
+ >>> t = np.linspace(0, 1.5, 100)
191
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
192
+ >>> b = const_ext(a, 40)
193
+ >>> import matplotlib.pyplot as plt
194
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='constant extension')
195
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
196
+ >>> plt.legend(loc='best')
197
+ >>> plt.show()
198
+ """
199
+ if n < 1:
200
+ return x
201
+ left_end = axis_slice(x, start=0, stop=1, axis=axis)
202
+ ones_shape = [1] * x.ndim
203
+ ones_shape[axis] = n
204
+ ones = np.ones(ones_shape, dtype=x.dtype)
205
+ left_ext = ones * left_end
206
+ right_end = axis_slice(x, start=-1, axis=axis)
207
+ right_ext = ones * right_end
208
+ ext = np.concatenate((left_ext,
209
+ x,
210
+ right_ext),
211
+ axis=axis)
212
+ return ext
213
+
214
+
215
+ def zero_ext(x, n, axis=-1):
216
+ """
217
+ Zero padding at the boundaries of an array
218
+
219
+ Generate a new ndarray that is a zero-padded extension of `x` along
220
+ an axis.
221
+
222
+ Parameters
223
+ ----------
224
+ x : ndarray
225
+ The array to be extended.
226
+ n : int
227
+ The number of elements by which to extend `x` at each end of the
228
+ axis.
229
+ axis : int, optional
230
+ The axis along which to extend `x`. Default is -1.
231
+
232
+ Examples
233
+ --------
234
+ >>> import numpy as np
235
+ >>> from scipy.signal._arraytools import zero_ext
236
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
237
+ >>> zero_ext(a, 2)
238
+ array([[ 0, 0, 1, 2, 3, 4, 5, 0, 0],
239
+ [ 0, 0, 0, 1, 4, 9, 16, 0, 0]])
240
+ """
241
+ if n < 1:
242
+ return x
243
+ zeros_shape = list(x.shape)
244
+ zeros_shape[axis] = n
245
+ zeros = np.zeros(zeros_shape, dtype=x.dtype)
246
+ ext = np.concatenate((zeros, x, zeros), axis=axis)
247
+ return ext
248
+
249
+
250
+ def _validate_fs(fs, allow_none=True):
251
+ """
252
+ Check if the given sampling frequency is a scalar and raises an exception
253
+ otherwise. If allow_none is False, also raises an exception for none
254
+ sampling rates. Returns the sampling frequency as float or none if the
255
+ input is none.
256
+ """
257
+ if fs is None:
258
+ if not allow_none:
259
+ raise ValueError("Sampling frequency can not be none.")
260
+ else: # should be float
261
+ if not np.isscalar(fs):
262
+ raise ValueError("Sampling frequency fs must be a single scalar.")
263
+ fs = float(fs)
264
+ return fs
llmeval-env/lib/python3.10/site-packages/scipy/signal/_czt.py ADDED
@@ -0,0 +1,575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This program is public domain
2
+ # Authors: Paul Kienzle, Nadav Horesh
3
+ """
4
+ Chirp z-transform.
5
+
6
+ We provide two interfaces to the chirp z-transform: an object interface
7
+ which precalculates part of the transform and can be applied efficiently
8
+ to many different data sets, and a functional interface which is applied
9
+ only to the given data set.
10
+
11
+ Transforms
12
+ ----------
13
+
14
+ CZT : callable (x, axis=-1) -> array
15
+ Define a chirp z-transform that can be applied to different signals.
16
+ ZoomFFT : callable (x, axis=-1) -> array
17
+ Define a Fourier transform on a range of frequencies.
18
+
19
+ Functions
20
+ ---------
21
+
22
+ czt : array
23
+ Compute the chirp z-transform for a signal.
24
+ zoom_fft : array
25
+ Compute the Fourier transform on a range of frequencies.
26
+ """
27
+
28
+ import cmath
29
+ import numbers
30
+ import numpy as np
31
+ from numpy import pi, arange
32
+ from scipy.fft import fft, ifft, next_fast_len
33
+
34
+ __all__ = ['czt', 'zoom_fft', 'CZT', 'ZoomFFT', 'czt_points']
35
+
36
+
37
+ def _validate_sizes(n, m):
38
+ if n < 1 or not isinstance(n, numbers.Integral):
39
+ raise ValueError('Invalid number of CZT data '
40
+ f'points ({n}) specified. '
41
+ 'n must be positive and integer type.')
42
+
43
+ if m is None:
44
+ m = n
45
+ elif m < 1 or not isinstance(m, numbers.Integral):
46
+ raise ValueError('Invalid number of CZT output '
47
+ f'points ({m}) specified. '
48
+ 'm must be positive and integer type.')
49
+
50
+ return m
51
+
52
+
53
+ def czt_points(m, w=None, a=1+0j):
54
+ """
55
+ Return the points at which the chirp z-transform is computed.
56
+
57
+ Parameters
58
+ ----------
59
+ m : int
60
+ The number of points desired.
61
+ w : complex, optional
62
+ The ratio between points in each step.
63
+ Defaults to equally spaced points around the entire unit circle.
64
+ a : complex, optional
65
+ The starting point in the complex plane. Default is 1+0j.
66
+
67
+ Returns
68
+ -------
69
+ out : ndarray
70
+ The points in the Z plane at which `CZT` samples the z-transform,
71
+ when called with arguments `m`, `w`, and `a`, as complex numbers.
72
+
73
+ See Also
74
+ --------
75
+ CZT : Class that creates a callable chirp z-transform function.
76
+ czt : Convenience function for quickly calculating CZT.
77
+
78
+ Examples
79
+ --------
80
+ Plot the points of a 16-point FFT:
81
+
82
+ >>> import numpy as np
83
+ >>> from scipy.signal import czt_points
84
+ >>> points = czt_points(16)
85
+ >>> import matplotlib.pyplot as plt
86
+ >>> plt.plot(points.real, points.imag, 'o')
87
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
88
+ >>> plt.axis('equal')
89
+ >>> plt.show()
90
+
91
+ and a 91-point logarithmic spiral that crosses the unit circle:
92
+
93
+ >>> m, w, a = 91, 0.995*np.exp(-1j*np.pi*.05), 0.8*np.exp(1j*np.pi/6)
94
+ >>> points = czt_points(m, w, a)
95
+ >>> plt.plot(points.real, points.imag, 'o')
96
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
97
+ >>> plt.axis('equal')
98
+ >>> plt.show()
99
+ """
100
+ m = _validate_sizes(1, m)
101
+
102
+ k = arange(m)
103
+
104
+ a = 1.0 * a # at least float
105
+
106
+ if w is None:
107
+ # Nothing specified, default to FFT
108
+ return a * np.exp(2j * pi * k / m)
109
+ else:
110
+ # w specified
111
+ w = 1.0 * w # at least float
112
+ return a * w**-k
113
+
114
+
115
+ class CZT:
116
+ """
117
+ Create a callable chirp z-transform function.
118
+
119
+ Transform to compute the frequency response around a spiral.
120
+ Objects of this class are callables which can compute the
121
+ chirp z-transform on their inputs. This object precalculates the constant
122
+ chirps used in the given transform.
123
+
124
+ Parameters
125
+ ----------
126
+ n : int
127
+ The size of the signal.
128
+ m : int, optional
129
+ The number of output points desired. Default is `n`.
130
+ w : complex, optional
131
+ The ratio between points in each step. This must be precise or the
132
+ accumulated error will degrade the tail of the output sequence.
133
+ Defaults to equally spaced points around the entire unit circle.
134
+ a : complex, optional
135
+ The starting point in the complex plane. Default is 1+0j.
136
+
137
+ Returns
138
+ -------
139
+ f : CZT
140
+ Callable object ``f(x, axis=-1)`` for computing the chirp z-transform
141
+ on `x`.
142
+
143
+ See Also
144
+ --------
145
+ czt : Convenience function for quickly calculating CZT.
146
+ ZoomFFT : Class that creates a callable partial FFT function.
147
+
148
+ Notes
149
+ -----
150
+ The defaults are chosen such that ``f(x)`` is equivalent to
151
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, m)`` is equivalent to
152
+ ``fft.fft(x, m)``.
153
+
154
+ If `w` does not lie on the unit circle, then the transform will be
155
+ around a spiral with exponentially-increasing radius. Regardless,
156
+ angle will increase linearly.
157
+
158
+ For transforms that do lie on the unit circle, accuracy is better when
159
+ using `ZoomFFT`, since any numerical error in `w` is
160
+ accumulated for long data lengths, drifting away from the unit circle.
161
+
162
+ The chirp z-transform can be faster than an equivalent FFT with
163
+ zero padding. Try it with your own array sizes to see.
164
+
165
+ However, the chirp z-transform is considerably less precise than the
166
+ equivalent zero-padded FFT.
167
+
168
+ As this CZT is implemented using the Bluestein algorithm, it can compute
169
+ large prime-length Fourier transforms in O(N log N) time, rather than the
170
+ O(N**2) time required by the direct DFT calculation. (`scipy.fft` also
171
+ uses Bluestein's algorithm'.)
172
+
173
+ (The name "chirp z-transform" comes from the use of a chirp in the
174
+ Bluestein algorithm. It does not decompose signals into chirps, like
175
+ other transforms with "chirp" in the name.)
176
+
177
+ References
178
+ ----------
179
+ .. [1] Leo I. Bluestein, "A linear filtering approach to the computation
180
+ of the discrete Fourier transform," Northeast Electronics Research
181
+ and Engineering Meeting Record 10, 218-219 (1968).
182
+ .. [2] Rabiner, Schafer, and Rader, "The chirp z-transform algorithm and
183
+ its application," Bell Syst. Tech. J. 48, 1249-1292 (1969).
184
+
185
+ Examples
186
+ --------
187
+ Compute multiple prime-length FFTs:
188
+
189
+ >>> from scipy.signal import CZT
190
+ >>> import numpy as np
191
+ >>> a = np.random.rand(7)
192
+ >>> b = np.random.rand(7)
193
+ >>> c = np.random.rand(7)
194
+ >>> czt_7 = CZT(n=7)
195
+ >>> A = czt_7(a)
196
+ >>> B = czt_7(b)
197
+ >>> C = czt_7(c)
198
+
199
+ Display the points at which the FFT is calculated:
200
+
201
+ >>> czt_7.points()
202
+ array([ 1.00000000+0.j , 0.62348980+0.78183148j,
203
+ -0.22252093+0.97492791j, -0.90096887+0.43388374j,
204
+ -0.90096887-0.43388374j, -0.22252093-0.97492791j,
205
+ 0.62348980-0.78183148j])
206
+ >>> import matplotlib.pyplot as plt
207
+ >>> plt.plot(czt_7.points().real, czt_7.points().imag, 'o')
208
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
209
+ >>> plt.axis('equal')
210
+ >>> plt.show()
211
+ """
212
+
213
+ def __init__(self, n, m=None, w=None, a=1+0j):
214
+ m = _validate_sizes(n, m)
215
+
216
+ k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2))
217
+
218
+ if w is None:
219
+ # Nothing specified, default to FFT-like
220
+ w = cmath.exp(-2j*pi/m)
221
+ wk2 = np.exp(-(1j * pi * ((k**2) % (2*m))) / m)
222
+ else:
223
+ # w specified
224
+ wk2 = w**(k**2/2.)
225
+
226
+ a = 1.0 * a # at least float
227
+
228
+ self.w, self.a = w, a
229
+ self.m, self.n = m, n
230
+
231
+ nfft = next_fast_len(n + m - 1)
232
+ self._Awk2 = a**-k[:n] * wk2[:n]
233
+ self._nfft = nfft
234
+ self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
235
+ self._wk2 = wk2[:m]
236
+ self._yidx = slice(n-1, n+m-1)
237
+
238
+ def __call__(self, x, *, axis=-1):
239
+ """
240
+ Calculate the chirp z-transform of a signal.
241
+
242
+ Parameters
243
+ ----------
244
+ x : array
245
+ The signal to transform.
246
+ axis : int, optional
247
+ Axis over which to compute the FFT. If not given, the last axis is
248
+ used.
249
+
250
+ Returns
251
+ -------
252
+ out : ndarray
253
+ An array of the same dimensions as `x`, but with the length of the
254
+ transformed axis set to `m`.
255
+ """
256
+ x = np.asarray(x)
257
+ if x.shape[axis] != self.n:
258
+ raise ValueError(f"CZT defined for length {self.n}, not "
259
+ f"{x.shape[axis]}")
260
+ # Calculate transpose coordinates, to allow operation on any given axis
261
+ trnsp = np.arange(x.ndim)
262
+ trnsp[[axis, -1]] = [-1, axis]
263
+ x = x.transpose(*trnsp)
264
+ y = ifft(self._Fwk2 * fft(x*self._Awk2, self._nfft))
265
+ y = y[..., self._yidx] * self._wk2
266
+ return y.transpose(*trnsp)
267
+
268
+ def points(self):
269
+ """
270
+ Return the points at which the chirp z-transform is computed.
271
+ """
272
+ return czt_points(self.m, self.w, self.a)
273
+
274
+
275
+ class ZoomFFT(CZT):
276
+ """
277
+ Create a callable zoom FFT transform function.
278
+
279
+ This is a specialization of the chirp z-transform (`CZT`) for a set of
280
+ equally-spaced frequencies around the unit circle, used to calculate a
281
+ section of the FFT more efficiently than calculating the entire FFT and
282
+ truncating.
283
+
284
+ Parameters
285
+ ----------
286
+ n : int
287
+ The size of the signal.
288
+ fn : array_like
289
+ A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
290
+ scalar, for which the range [0, `fn`] is assumed.
291
+ m : int, optional
292
+ The number of points to evaluate. Default is `n`.
293
+ fs : float, optional
294
+ The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
295
+ then `f1` and `f2` would also be given in kHz.
296
+ The default sampling frequency is 2, so `f1` and `f2` should be
297
+ in the range [0, 1] to keep the transform below the Nyquist
298
+ frequency.
299
+ endpoint : bool, optional
300
+ If True, `f2` is the last sample. Otherwise, it is not included.
301
+ Default is False.
302
+
303
+ Returns
304
+ -------
305
+ f : ZoomFFT
306
+ Callable object ``f(x, axis=-1)`` for computing the zoom FFT on `x`.
307
+
308
+ See Also
309
+ --------
310
+ zoom_fft : Convenience function for calculating a zoom FFT.
311
+
312
+ Notes
313
+ -----
314
+ The defaults are chosen such that ``f(x, 2)`` is equivalent to
315
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, 2, m)`` is equivalent to
316
+ ``fft.fft(x, m)``.
317
+
318
+ Sampling frequency is 1/dt, the time step between samples in the
319
+ signal `x`. The unit circle corresponds to frequencies from 0 up
320
+ to the sampling frequency. The default sampling frequency of 2
321
+ means that `f1`, `f2` values up to the Nyquist frequency are in the
322
+ range [0, 1). For `f1`, `f2` values expressed in radians, a sampling
323
+ frequency of 2*pi should be used.
324
+
325
+ Remember that a zoom FFT can only interpolate the points of the existing
326
+ FFT. It cannot help to resolve two separate nearby frequencies.
327
+ Frequency resolution can only be increased by increasing acquisition
328
+ time.
329
+
330
+ These functions are implemented using Bluestein's algorithm (as is
331
+ `scipy.fft`). [2]_
332
+
333
+ References
334
+ ----------
335
+ .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
336
+ applications", pg 29 (1970)
337
+ https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
338
+ .. [2] Leo I. Bluestein, "A linear filtering approach to the computation
339
+ of the discrete Fourier transform," Northeast Electronics Research
340
+ and Engineering Meeting Record 10, 218-219 (1968).
341
+
342
+ Examples
343
+ --------
344
+ To plot the transform results use something like the following:
345
+
346
+ >>> import numpy as np
347
+ >>> from scipy.signal import ZoomFFT
348
+ >>> t = np.linspace(0, 1, 1021)
349
+ >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t)
350
+ >>> f1, f2 = 5, 27
351
+ >>> transform = ZoomFFT(len(x), [f1, f2], len(x), fs=1021)
352
+ >>> X = transform(x)
353
+ >>> f = np.linspace(f1, f2, len(x))
354
+ >>> import matplotlib.pyplot as plt
355
+ >>> plt.plot(f, 20*np.log10(np.abs(X)))
356
+ >>> plt.show()
357
+ """
358
+
359
+ def __init__(self, n, fn, m=None, *, fs=2, endpoint=False):
360
+ m = _validate_sizes(n, m)
361
+
362
+ k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2))
363
+
364
+ if np.size(fn) == 2:
365
+ f1, f2 = fn
366
+ elif np.size(fn) == 1:
367
+ f1, f2 = 0.0, fn
368
+ else:
369
+ raise ValueError('fn must be a scalar or 2-length sequence')
370
+
371
+ self.f1, self.f2, self.fs = f1, f2, fs
372
+
373
+ if endpoint:
374
+ scale = ((f2 - f1) * m) / (fs * (m - 1))
375
+ else:
376
+ scale = (f2 - f1) / fs
377
+ a = cmath.exp(2j * pi * f1/fs)
378
+ wk2 = np.exp(-(1j * pi * scale * k**2) / m)
379
+
380
+ self.w = cmath.exp(-2j*pi/m * scale)
381
+ self.a = a
382
+ self.m, self.n = m, n
383
+
384
+ ak = np.exp(-2j * pi * f1/fs * k[:n])
385
+ self._Awk2 = ak * wk2[:n]
386
+
387
+ nfft = next_fast_len(n + m - 1)
388
+ self._nfft = nfft
389
+ self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
390
+ self._wk2 = wk2[:m]
391
+ self._yidx = slice(n-1, n+m-1)
392
+
393
+
394
+ def czt(x, m=None, w=None, a=1+0j, *, axis=-1):
395
+ """
396
+ Compute the frequency response around a spiral in the Z plane.
397
+
398
+ Parameters
399
+ ----------
400
+ x : array
401
+ The signal to transform.
402
+ m : int, optional
403
+ The number of output points desired. Default is the length of the
404
+ input data.
405
+ w : complex, optional
406
+ The ratio between points in each step. This must be precise or the
407
+ accumulated error will degrade the tail of the output sequence.
408
+ Defaults to equally spaced points around the entire unit circle.
409
+ a : complex, optional
410
+ The starting point in the complex plane. Default is 1+0j.
411
+ axis : int, optional
412
+ Axis over which to compute the FFT. If not given, the last axis is
413
+ used.
414
+
415
+ Returns
416
+ -------
417
+ out : ndarray
418
+ An array of the same dimensions as `x`, but with the length of the
419
+ transformed axis set to `m`.
420
+
421
+ See Also
422
+ --------
423
+ CZT : Class that creates a callable chirp z-transform function.
424
+ zoom_fft : Convenience function for partial FFT calculations.
425
+
426
+ Notes
427
+ -----
428
+ The defaults are chosen such that ``signal.czt(x)`` is equivalent to
429
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.czt(x, m)`` is
430
+ equivalent to ``fft.fft(x, m)``.
431
+
432
+ If the transform needs to be repeated, use `CZT` to construct a
433
+ specialized transform function which can be reused without
434
+ recomputing constants.
435
+
436
+ An example application is in system identification, repeatedly evaluating
437
+ small slices of the z-transform of a system, around where a pole is
438
+ expected to exist, to refine the estimate of the pole's true location. [1]_
439
+
440
+ References
441
+ ----------
442
+ .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
443
+ applications", pg 20 (1970)
444
+ https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
445
+
446
+ Examples
447
+ --------
448
+ Generate a sinusoid:
449
+
450
+ >>> import numpy as np
451
+ >>> f1, f2, fs = 8, 10, 200 # Hz
452
+ >>> t = np.linspace(0, 1, fs, endpoint=False)
453
+ >>> x = np.sin(2*np.pi*t*f2)
454
+ >>> import matplotlib.pyplot as plt
455
+ >>> plt.plot(t, x)
456
+ >>> plt.axis([0, 1, -1.1, 1.1])
457
+ >>> plt.show()
458
+
459
+ Its discrete Fourier transform has all of its energy in a single frequency
460
+ bin:
461
+
462
+ >>> from scipy.fft import rfft, rfftfreq
463
+ >>> from scipy.signal import czt, czt_points
464
+ >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x)))
465
+ >>> plt.margins(0, 0.1)
466
+ >>> plt.show()
467
+
468
+ However, if the sinusoid is logarithmically-decaying:
469
+
470
+ >>> x = np.exp(-t*f1) * np.sin(2*np.pi*t*f2)
471
+ >>> plt.plot(t, x)
472
+ >>> plt.axis([0, 1, -1.1, 1.1])
473
+ >>> plt.show()
474
+
475
+ the DFT will have spectral leakage:
476
+
477
+ >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x)))
478
+ >>> plt.margins(0, 0.1)
479
+ >>> plt.show()
480
+
481
+ While the DFT always samples the z-transform around the unit circle, the
482
+ chirp z-transform allows us to sample the Z-transform along any
483
+ logarithmic spiral, such as a circle with radius smaller than unity:
484
+
485
+ >>> M = fs // 2 # Just positive frequencies, like rfft
486
+ >>> a = np.exp(-f1/fs) # Starting point of the circle, radius < 1
487
+ >>> w = np.exp(-1j*np.pi/M) # "Step size" of circle
488
+ >>> points = czt_points(M + 1, w, a) # M + 1 to include Nyquist
489
+ >>> plt.plot(points.real, points.imag, '.')
490
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
491
+ >>> plt.axis('equal'); plt.axis([-1.05, 1.05, -0.05, 1.05])
492
+ >>> plt.show()
493
+
494
+ With the correct radius, this transforms the decaying sinusoid (and others
495
+ with the same decay rate) without spectral leakage:
496
+
497
+ >>> z_vals = czt(x, M + 1, w, a) # Include Nyquist for comparison to rfft
498
+ >>> freqs = np.angle(points)*fs/(2*np.pi) # angle = omega, radius = sigma
499
+ >>> plt.plot(freqs, abs(z_vals))
500
+ >>> plt.margins(0, 0.1)
501
+ >>> plt.show()
502
+ """
503
+ x = np.asarray(x)
504
+ transform = CZT(x.shape[axis], m=m, w=w, a=a)
505
+ return transform(x, axis=axis)
506
+
507
+
508
+ def zoom_fft(x, fn, m=None, *, fs=2, endpoint=False, axis=-1):
509
+ """
510
+ Compute the DFT of `x` only for frequencies in range `fn`.
511
+
512
+ Parameters
513
+ ----------
514
+ x : array
515
+ The signal to transform.
516
+ fn : array_like
517
+ A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
518
+ scalar, for which the range [0, `fn`] is assumed.
519
+ m : int, optional
520
+ The number of points to evaluate. The default is the length of `x`.
521
+ fs : float, optional
522
+ The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
523
+ then `f1` and `f2` would also be given in kHz.
524
+ The default sampling frequency is 2, so `f1` and `f2` should be
525
+ in the range [0, 1] to keep the transform below the Nyquist
526
+ frequency.
527
+ endpoint : bool, optional
528
+ If True, `f2` is the last sample. Otherwise, it is not included.
529
+ Default is False.
530
+ axis : int, optional
531
+ Axis over which to compute the FFT. If not given, the last axis is
532
+ used.
533
+
534
+ Returns
535
+ -------
536
+ out : ndarray
537
+ The transformed signal. The Fourier transform will be calculated
538
+ at the points f1, f1+df, f1+2df, ..., f2, where df=(f2-f1)/m.
539
+
540
+ See Also
541
+ --------
542
+ ZoomFFT : Class that creates a callable partial FFT function.
543
+
544
+ Notes
545
+ -----
546
+ The defaults are chosen such that ``signal.zoom_fft(x, 2)`` is equivalent
547
+ to ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.zoom_fft(x, 2, m)``
548
+ is equivalent to ``fft.fft(x, m)``.
549
+
550
+ To graph the magnitude of the resulting transform, use::
551
+
552
+ plot(linspace(f1, f2, m, endpoint=False), abs(zoom_fft(x, [f1, f2], m)))
553
+
554
+ If the transform needs to be repeated, use `ZoomFFT` to construct
555
+ a specialized transform function which can be reused without
556
+ recomputing constants.
557
+
558
+ Examples
559
+ --------
560
+ To plot the transform results use something like the following:
561
+
562
+ >>> import numpy as np
563
+ >>> from scipy.signal import zoom_fft
564
+ >>> t = np.linspace(0, 1, 1021)
565
+ >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t)
566
+ >>> f1, f2 = 5, 27
567
+ >>> X = zoom_fft(x, [f1, f2], len(x), fs=1021)
568
+ >>> f = np.linspace(f1, f2, len(x))
569
+ >>> import matplotlib.pyplot as plt
570
+ >>> plt.plot(f, 20*np.log10(np.abs(X)))
571
+ >>> plt.show()
572
+ """
573
+ x = np.asarray(x)
574
+ transform = ZoomFFT(x.shape[axis], fn, m=m, fs=fs, endpoint=endpoint)
575
+ return transform(x, axis=axis)
llmeval-env/lib/python3.10/site-packages/scipy/signal/_fir_filter_design.py ADDED
@@ -0,0 +1,1301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Functions for FIR filter design."""
2
+
3
+ from math import ceil, log
4
+ import operator
5
+ import warnings
6
+
7
+ import numpy as np
8
+ from numpy.fft import irfft, fft, ifft
9
+ from scipy.special import sinc
10
+ from scipy.linalg import (toeplitz, hankel, solve, LinAlgError, LinAlgWarning,
11
+ lstsq)
12
+ from scipy._lib.deprecation import _NoValue, _deprecate_positional_args
13
+ from scipy.signal._arraytools import _validate_fs
14
+
15
+ from . import _sigtools
16
+
17
+ __all__ = ['kaiser_beta', 'kaiser_atten', 'kaiserord',
18
+ 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase']
19
+
20
+
21
+ def _get_fs(fs, nyq):
22
+ """
23
+ Utility for replacing the argument 'nyq' (with default 1) with 'fs'.
24
+ """
25
+ if nyq is _NoValue and fs is None:
26
+ fs = 2
27
+ elif nyq is not _NoValue:
28
+ if fs is not None:
29
+ raise ValueError("Values cannot be given for both 'nyq' and 'fs'.")
30
+ msg = ("Keyword argument 'nyq' is deprecated in favour of 'fs' and "
31
+ "will be removed in SciPy 1.14.0.")
32
+ warnings.warn(msg, DeprecationWarning, stacklevel=3)
33
+ if nyq is None:
34
+ fs = 2
35
+ else:
36
+ fs = 2*nyq
37
+ return fs
38
+
39
+
40
+ # Some notes on function parameters:
41
+ #
42
+ # `cutoff` and `width` are given as numbers between 0 and 1. These are
43
+ # relative frequencies, expressed as a fraction of the Nyquist frequency.
44
+ # For example, if the Nyquist frequency is 2 KHz, then width=0.15 is a width
45
+ # of 300 Hz.
46
+ #
47
+ # The `order` of a FIR filter is one less than the number of taps.
48
+ # This is a potential source of confusion, so in the following code,
49
+ # we will always use the number of taps as the parameterization of
50
+ # the 'size' of the filter. The "number of taps" means the number
51
+ # of coefficients, which is the same as the length of the impulse
52
+ # response of the filter.
53
+
54
+
55
+ def kaiser_beta(a):
56
+ """Compute the Kaiser parameter `beta`, given the attenuation `a`.
57
+
58
+ Parameters
59
+ ----------
60
+ a : float
61
+ The desired attenuation in the stopband and maximum ripple in
62
+ the passband, in dB. This should be a *positive* number.
63
+
64
+ Returns
65
+ -------
66
+ beta : float
67
+ The `beta` parameter to be used in the formula for a Kaiser window.
68
+
69
+ References
70
+ ----------
71
+ Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476.
72
+
73
+ Examples
74
+ --------
75
+ Suppose we want to design a lowpass filter, with 65 dB attenuation
76
+ in the stop band. The Kaiser window parameter to be used in the
77
+ window method is computed by ``kaiser_beta(65)``:
78
+
79
+ >>> from scipy.signal import kaiser_beta
80
+ >>> kaiser_beta(65)
81
+ 6.20426
82
+
83
+ """
84
+ if a > 50:
85
+ beta = 0.1102 * (a - 8.7)
86
+ elif a > 21:
87
+ beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21)
88
+ else:
89
+ beta = 0.0
90
+ return beta
91
+
92
+
93
+ def kaiser_atten(numtaps, width):
94
+ """Compute the attenuation of a Kaiser FIR filter.
95
+
96
+ Given the number of taps `N` and the transition width `width`, compute the
97
+ attenuation `a` in dB, given by Kaiser's formula:
98
+
99
+ a = 2.285 * (N - 1) * pi * width + 7.95
100
+
101
+ Parameters
102
+ ----------
103
+ numtaps : int
104
+ The number of taps in the FIR filter.
105
+ width : float
106
+ The desired width of the transition region between passband and
107
+ stopband (or, in general, at any discontinuity) for the filter,
108
+ expressed as a fraction of the Nyquist frequency.
109
+
110
+ Returns
111
+ -------
112
+ a : float
113
+ The attenuation of the ripple, in dB.
114
+
115
+ See Also
116
+ --------
117
+ kaiserord, kaiser_beta
118
+
119
+ Examples
120
+ --------
121
+ Suppose we want to design a FIR filter using the Kaiser window method
122
+ that will have 211 taps and a transition width of 9 Hz for a signal that
123
+ is sampled at 480 Hz. Expressed as a fraction of the Nyquist frequency,
124
+ the width is 9/(0.5*480) = 0.0375. The approximate attenuation (in dB)
125
+ is computed as follows:
126
+
127
+ >>> from scipy.signal import kaiser_atten
128
+ >>> kaiser_atten(211, 0.0375)
129
+ 64.48099630593983
130
+
131
+ """
132
+ a = 2.285 * (numtaps - 1) * np.pi * width + 7.95
133
+ return a
134
+
135
+
136
+ def kaiserord(ripple, width):
137
+ """
138
+ Determine the filter window parameters for the Kaiser window method.
139
+
140
+ The parameters returned by this function are generally used to create
141
+ a finite impulse response filter using the window method, with either
142
+ `firwin` or `firwin2`.
143
+
144
+ Parameters
145
+ ----------
146
+ ripple : float
147
+ Upper bound for the deviation (in dB) of the magnitude of the
148
+ filter's frequency response from that of the desired filter (not
149
+ including frequencies in any transition intervals). That is, if w
150
+ is the frequency expressed as a fraction of the Nyquist frequency,
151
+ A(w) is the actual frequency response of the filter and D(w) is the
152
+ desired frequency response, the design requirement is that::
153
+
154
+ abs(A(w) - D(w))) < 10**(-ripple/20)
155
+
156
+ for 0 <= w <= 1 and w not in a transition interval.
157
+ width : float
158
+ Width of transition region, normalized so that 1 corresponds to pi
159
+ radians / sample. That is, the frequency is expressed as a fraction
160
+ of the Nyquist frequency.
161
+
162
+ Returns
163
+ -------
164
+ numtaps : int
165
+ The length of the Kaiser window.
166
+ beta : float
167
+ The beta parameter for the Kaiser window.
168
+
169
+ See Also
170
+ --------
171
+ kaiser_beta, kaiser_atten
172
+
173
+ Notes
174
+ -----
175
+ There are several ways to obtain the Kaiser window:
176
+
177
+ - ``signal.windows.kaiser(numtaps, beta, sym=True)``
178
+ - ``signal.get_window(beta, numtaps)``
179
+ - ``signal.get_window(('kaiser', beta), numtaps)``
180
+
181
+ The empirical equations discovered by Kaiser are used.
182
+
183
+ References
184
+ ----------
185
+ Oppenheim, Schafer, "Discrete-Time Signal Processing", pp.475-476.
186
+
187
+ Examples
188
+ --------
189
+ We will use the Kaiser window method to design a lowpass FIR filter
190
+ for a signal that is sampled at 1000 Hz.
191
+
192
+ We want at least 65 dB rejection in the stop band, and in the pass
193
+ band the gain should vary no more than 0.5%.
194
+
195
+ We want a cutoff frequency of 175 Hz, with a transition between the
196
+ pass band and the stop band of 24 Hz. That is, in the band [0, 163],
197
+ the gain varies no more than 0.5%, and in the band [187, 500], the
198
+ signal is attenuated by at least 65 dB.
199
+
200
+ >>> import numpy as np
201
+ >>> from scipy.signal import kaiserord, firwin, freqz
202
+ >>> import matplotlib.pyplot as plt
203
+ >>> fs = 1000.0
204
+ >>> cutoff = 175
205
+ >>> width = 24
206
+
207
+ The Kaiser method accepts just a single parameter to control the pass
208
+ band ripple and the stop band rejection, so we use the more restrictive
209
+ of the two. In this case, the pass band ripple is 0.005, or 46.02 dB,
210
+ so we will use 65 dB as the design parameter.
211
+
212
+ Use `kaiserord` to determine the length of the filter and the
213
+ parameter for the Kaiser window.
214
+
215
+ >>> numtaps, beta = kaiserord(65, width/(0.5*fs))
216
+ >>> numtaps
217
+ 167
218
+ >>> beta
219
+ 6.20426
220
+
221
+ Use `firwin` to create the FIR filter.
222
+
223
+ >>> taps = firwin(numtaps, cutoff, window=('kaiser', beta),
224
+ ... scale=False, fs=fs)
225
+
226
+ Compute the frequency response of the filter. ``w`` is the array of
227
+ frequencies, and ``h`` is the corresponding complex array of frequency
228
+ responses.
229
+
230
+ >>> w, h = freqz(taps, worN=8000)
231
+ >>> w *= 0.5*fs/np.pi # Convert w to Hz.
232
+
233
+ Compute the deviation of the magnitude of the filter's response from
234
+ that of the ideal lowpass filter. Values in the transition region are
235
+ set to ``nan``, so they won't appear in the plot.
236
+
237
+ >>> ideal = w < cutoff # The "ideal" frequency response.
238
+ >>> deviation = np.abs(np.abs(h) - ideal)
239
+ >>> deviation[(w > cutoff - 0.5*width) & (w < cutoff + 0.5*width)] = np.nan
240
+
241
+ Plot the deviation. A close look at the left end of the stop band shows
242
+ that the requirement for 65 dB attenuation is violated in the first lobe
243
+ by about 0.125 dB. This is not unusual for the Kaiser window method.
244
+
245
+ >>> plt.plot(w, 20*np.log10(np.abs(deviation)))
246
+ >>> plt.xlim(0, 0.5*fs)
247
+ >>> plt.ylim(-90, -60)
248
+ >>> plt.grid(alpha=0.25)
249
+ >>> plt.axhline(-65, color='r', ls='--', alpha=0.3)
250
+ >>> plt.xlabel('Frequency (Hz)')
251
+ >>> plt.ylabel('Deviation from ideal (dB)')
252
+ >>> plt.title('Lowpass Filter Frequency Response')
253
+ >>> plt.show()
254
+
255
+ """
256
+ A = abs(ripple) # in case somebody is confused as to what's meant
257
+ if A < 8:
258
+ # Formula for N is not valid in this range.
259
+ raise ValueError("Requested maximum ripple attenuation %f is too "
260
+ "small for the Kaiser formula." % A)
261
+ beta = kaiser_beta(A)
262
+
263
+ # Kaiser's formula (as given in Oppenheim and Schafer) is for the filter
264
+ # order, so we have to add 1 to get the number of taps.
265
+ numtaps = (A - 7.95) / 2.285 / (np.pi * width) + 1
266
+
267
+ return int(ceil(numtaps)), beta
268
+
269
+
270
+ @_deprecate_positional_args(version="1.14")
271
+ def firwin(numtaps, cutoff, *, width=None, window='hamming', pass_zero=True,
272
+ scale=True, nyq=_NoValue, fs=None):
273
+ """
274
+ FIR filter design using the window method.
275
+
276
+ This function computes the coefficients of a finite impulse response
277
+ filter. The filter will have linear phase; it will be Type I if
278
+ `numtaps` is odd and Type II if `numtaps` is even.
279
+
280
+ Type II filters always have zero response at the Nyquist frequency, so a
281
+ ValueError exception is raised if firwin is called with `numtaps` even and
282
+ having a passband whose right end is at the Nyquist frequency.
283
+
284
+ Parameters
285
+ ----------
286
+ numtaps : int
287
+ Length of the filter (number of coefficients, i.e. the filter
288
+ order + 1). `numtaps` must be odd if a passband includes the
289
+ Nyquist frequency.
290
+ cutoff : float or 1-D array_like
291
+ Cutoff frequency of filter (expressed in the same units as `fs`)
292
+ OR an array of cutoff frequencies (that is, band edges). In the
293
+ latter case, the frequencies in `cutoff` should be positive and
294
+ monotonically increasing between 0 and `fs/2`. The values 0 and
295
+ `fs/2` must not be included in `cutoff`.
296
+ width : float or None, optional
297
+ If `width` is not None, then assume it is the approximate width
298
+ of the transition region (expressed in the same units as `fs`)
299
+ for use in Kaiser FIR filter design. In this case, the `window`
300
+ argument is ignored.
301
+ window : string or tuple of string and parameter values, optional
302
+ Desired window to use. See `scipy.signal.get_window` for a list
303
+ of windows and required parameters.
304
+ pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
305
+ If True, the gain at the frequency 0 (i.e., the "DC gain") is 1.
306
+ If False, the DC gain is 0. Can also be a string argument for the
307
+ desired filter type (equivalent to ``btype`` in IIR design functions).
308
+
309
+ .. versionadded:: 1.3.0
310
+ Support for string arguments.
311
+ scale : bool, optional
312
+ Set to True to scale the coefficients so that the frequency
313
+ response is exactly unity at a certain frequency.
314
+ That frequency is either:
315
+
316
+ - 0 (DC) if the first passband starts at 0 (i.e. pass_zero
317
+ is True)
318
+ - `fs/2` (the Nyquist frequency) if the first passband ends at
319
+ `fs/2` (i.e the filter is a single band highpass filter);
320
+ center of first passband otherwise
321
+
322
+ nyq : float, optional, deprecated
323
+ This is the Nyquist frequency. Each frequency in `cutoff` must be
324
+ between 0 and `nyq`. Default is 1.
325
+
326
+ .. deprecated:: 1.0.0
327
+ `firwin` keyword argument `nyq` is deprecated in favour of `fs` and
328
+ will be removed in SciPy 1.14.0.
329
+ fs : float, optional
330
+ The sampling frequency of the signal. Each frequency in `cutoff`
331
+ must be between 0 and ``fs/2``. Default is 2.
332
+
333
+ Returns
334
+ -------
335
+ h : (numtaps,) ndarray
336
+ Coefficients of length `numtaps` FIR filter.
337
+
338
+ Raises
339
+ ------
340
+ ValueError
341
+ If any value in `cutoff` is less than or equal to 0 or greater
342
+ than or equal to ``fs/2``, if the values in `cutoff` are not strictly
343
+ monotonically increasing, or if `numtaps` is even but a passband
344
+ includes the Nyquist frequency.
345
+
346
+ See Also
347
+ --------
348
+ firwin2
349
+ firls
350
+ minimum_phase
351
+ remez
352
+
353
+ Examples
354
+ --------
355
+ Low-pass from 0 to f:
356
+
357
+ >>> from scipy import signal
358
+ >>> numtaps = 3
359
+ >>> f = 0.1
360
+ >>> signal.firwin(numtaps, f)
361
+ array([ 0.06799017, 0.86401967, 0.06799017])
362
+
363
+ Use a specific window function:
364
+
365
+ >>> signal.firwin(numtaps, f, window='nuttall')
366
+ array([ 3.56607041e-04, 9.99286786e-01, 3.56607041e-04])
367
+
368
+ High-pass ('stop' from 0 to f):
369
+
370
+ >>> signal.firwin(numtaps, f, pass_zero=False)
371
+ array([-0.00859313, 0.98281375, -0.00859313])
372
+
373
+ Band-pass:
374
+
375
+ >>> f1, f2 = 0.1, 0.2
376
+ >>> signal.firwin(numtaps, [f1, f2], pass_zero=False)
377
+ array([ 0.06301614, 0.88770441, 0.06301614])
378
+
379
+ Band-stop:
380
+
381
+ >>> signal.firwin(numtaps, [f1, f2])
382
+ array([-0.00801395, 1.0160279 , -0.00801395])
383
+
384
+ Multi-band (passbands are [0, f1], [f2, f3] and [f4, 1]):
385
+
386
+ >>> f3, f4 = 0.3, 0.4
387
+ >>> signal.firwin(numtaps, [f1, f2, f3, f4])
388
+ array([-0.01376344, 1.02752689, -0.01376344])
389
+
390
+ Multi-band (passbands are [f1, f2] and [f3,f4]):
391
+
392
+ >>> signal.firwin(numtaps, [f1, f2, f3, f4], pass_zero=False)
393
+ array([ 0.04890915, 0.91284326, 0.04890915])
394
+
395
+ """
396
+ # The major enhancements to this function added in November 2010 were
397
+ # developed by Tom Krauss (see ticket #902).
398
+ fs = _validate_fs(fs, allow_none=True)
399
+
400
+ nyq = 0.5 * _get_fs(fs, nyq)
401
+
402
+ cutoff = np.atleast_1d(cutoff) / float(nyq)
403
+
404
+ # Check for invalid input.
405
+ if cutoff.ndim > 1:
406
+ raise ValueError("The cutoff argument must be at most "
407
+ "one-dimensional.")
408
+ if cutoff.size == 0:
409
+ raise ValueError("At least one cutoff frequency must be given.")
410
+ if cutoff.min() <= 0 or cutoff.max() >= 1:
411
+ raise ValueError("Invalid cutoff frequency: frequencies must be "
412
+ "greater than 0 and less than fs/2.")
413
+ if np.any(np.diff(cutoff) <= 0):
414
+ raise ValueError("Invalid cutoff frequencies: the frequencies "
415
+ "must be strictly increasing.")
416
+
417
+ if width is not None:
418
+ # A width was given. Find the beta parameter of the Kaiser window
419
+ # and set `window`. This overrides the value of `window` passed in.
420
+ atten = kaiser_atten(numtaps, float(width) / nyq)
421
+ beta = kaiser_beta(atten)
422
+ window = ('kaiser', beta)
423
+
424
+ if isinstance(pass_zero, str):
425
+ if pass_zero in ('bandstop', 'lowpass'):
426
+ if pass_zero == 'lowpass':
427
+ if cutoff.size != 1:
428
+ raise ValueError('cutoff must have one element if '
429
+ f'pass_zero=="lowpass", got {cutoff.shape}')
430
+ elif cutoff.size <= 1:
431
+ raise ValueError('cutoff must have at least two elements if '
432
+ f'pass_zero=="bandstop", got {cutoff.shape}')
433
+ pass_zero = True
434
+ elif pass_zero in ('bandpass', 'highpass'):
435
+ if pass_zero == 'highpass':
436
+ if cutoff.size != 1:
437
+ raise ValueError('cutoff must have one element if '
438
+ f'pass_zero=="highpass", got {cutoff.shape}')
439
+ elif cutoff.size <= 1:
440
+ raise ValueError('cutoff must have at least two elements if '
441
+ f'pass_zero=="bandpass", got {cutoff.shape}')
442
+ pass_zero = False
443
+ else:
444
+ raise ValueError('pass_zero must be True, False, "bandpass", '
445
+ '"lowpass", "highpass", or "bandstop", got '
446
+ f'{pass_zero}')
447
+ pass_zero = bool(operator.index(pass_zero)) # ensure bool-like
448
+
449
+ pass_nyquist = bool(cutoff.size & 1) ^ pass_zero
450
+ if pass_nyquist and numtaps % 2 == 0:
451
+ raise ValueError("A filter with an even number of coefficients must "
452
+ "have zero response at the Nyquist frequency.")
453
+
454
+ # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff
455
+ # is even, and each pair in cutoff corresponds to passband.
456
+ cutoff = np.hstack(([0.0] * pass_zero, cutoff, [1.0] * pass_nyquist))
457
+
458
+ # `bands` is a 2-D array; each row gives the left and right edges of
459
+ # a passband.
460
+ bands = cutoff.reshape(-1, 2)
461
+
462
+ # Build up the coefficients.
463
+ alpha = 0.5 * (numtaps - 1)
464
+ m = np.arange(0, numtaps) - alpha
465
+ h = 0
466
+ for left, right in bands:
467
+ h += right * sinc(right * m)
468
+ h -= left * sinc(left * m)
469
+
470
+ # Get and apply the window function.
471
+ from .windows import get_window
472
+ win = get_window(window, numtaps, fftbins=False)
473
+ h *= win
474
+
475
+ # Now handle scaling if desired.
476
+ if scale:
477
+ # Get the first passband.
478
+ left, right = bands[0]
479
+ if left == 0:
480
+ scale_frequency = 0.0
481
+ elif right == 1:
482
+ scale_frequency = 1.0
483
+ else:
484
+ scale_frequency = 0.5 * (left + right)
485
+ c = np.cos(np.pi * m * scale_frequency)
486
+ s = np.sum(h * c)
487
+ h /= s
488
+
489
+ return h
490
+
491
+
492
+ # Original version of firwin2 from scipy ticket #457, submitted by "tash".
493
+ #
494
+ # Rewritten by Warren Weckesser, 2010.
495
+ @_deprecate_positional_args(version="1.14")
496
+ def firwin2(numtaps, freq, gain, *, nfreqs=None, window='hamming', nyq=_NoValue,
497
+ antisymmetric=False, fs=None):
498
+ """
499
+ FIR filter design using the window method.
500
+
501
+ From the given frequencies `freq` and corresponding gains `gain`,
502
+ this function constructs an FIR filter with linear phase and
503
+ (approximately) the given frequency response.
504
+
505
+ Parameters
506
+ ----------
507
+ numtaps : int
508
+ The number of taps in the FIR filter. `numtaps` must be less than
509
+ `nfreqs`.
510
+ freq : array_like, 1-D
511
+ The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being
512
+ Nyquist. The Nyquist frequency is half `fs`.
513
+ The values in `freq` must be nondecreasing. A value can be repeated
514
+ once to implement a discontinuity. The first value in `freq` must
515
+ be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must
516
+ not be repeated.
517
+ gain : array_like
518
+ The filter gains at the frequency sampling points. Certain
519
+ constraints to gain values, depending on the filter type, are applied,
520
+ see Notes for details.
521
+ nfreqs : int, optional
522
+ The size of the interpolation mesh used to construct the filter.
523
+ For most efficient behavior, this should be a power of 2 plus 1
524
+ (e.g, 129, 257, etc). The default is one more than the smallest
525
+ power of 2 that is not less than `numtaps`. `nfreqs` must be greater
526
+ than `numtaps`.
527
+ window : string or (string, float) or float, or None, optional
528
+ Window function to use. Default is "hamming". See
529
+ `scipy.signal.get_window` for the complete list of possible values.
530
+ If None, no window function is applied.
531
+ nyq : float, optional, deprecated
532
+ This is the Nyquist frequency. Each frequency in `freq` must be
533
+ between 0 and `nyq`. Default is 1.
534
+
535
+ .. deprecated:: 1.0.0
536
+ `firwin2` keyword argument `nyq` is deprecated in favour of `fs` and
537
+ will be removed in SciPy 1.14.0.
538
+ antisymmetric : bool, optional
539
+ Whether resulting impulse response is symmetric/antisymmetric.
540
+ See Notes for more details.
541
+ fs : float, optional
542
+ The sampling frequency of the signal. Each frequency in `cutoff`
543
+ must be between 0 and ``fs/2``. Default is 2.
544
+
545
+ Returns
546
+ -------
547
+ taps : ndarray
548
+ The filter coefficients of the FIR filter, as a 1-D array of length
549
+ `numtaps`.
550
+
551
+ See Also
552
+ --------
553
+ firls
554
+ firwin
555
+ minimum_phase
556
+ remez
557
+
558
+ Notes
559
+ -----
560
+ From the given set of frequencies and gains, the desired response is
561
+ constructed in the frequency domain. The inverse FFT is applied to the
562
+ desired response to create the associated convolution kernel, and the
563
+ first `numtaps` coefficients of this kernel, scaled by `window`, are
564
+ returned.
565
+
566
+ The FIR filter will have linear phase. The type of filter is determined by
567
+ the value of 'numtaps` and `antisymmetric` flag.
568
+ There are four possible combinations:
569
+
570
+ - odd `numtaps`, `antisymmetric` is False, type I filter is produced
571
+ - even `numtaps`, `antisymmetric` is False, type II filter is produced
572
+ - odd `numtaps`, `antisymmetric` is True, type III filter is produced
573
+ - even `numtaps`, `antisymmetric` is True, type IV filter is produced
574
+
575
+ Magnitude response of all but type I filters are subjects to following
576
+ constraints:
577
+
578
+ - type II -- zero at the Nyquist frequency
579
+ - type III -- zero at zero and Nyquist frequencies
580
+ - type IV -- zero at zero frequency
581
+
582
+ .. versionadded:: 0.9.0
583
+
584
+ References
585
+ ----------
586
+ .. [1] Oppenheim, A. V. and Schafer, R. W., "Discrete-Time Signal
587
+ Processing", Prentice-Hall, Englewood Cliffs, New Jersey (1989).
588
+ (See, for example, Section 7.4.)
589
+
590
+ .. [2] Smith, Steven W., "The Scientist and Engineer's Guide to Digital
591
+ Signal Processing", Ch. 17. http://www.dspguide.com/ch17/1.htm
592
+
593
+ Examples
594
+ --------
595
+ A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and
596
+ that decreases linearly on [0.5, 1.0] from 1 to 0:
597
+
598
+ >>> from scipy import signal
599
+ >>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0])
600
+ >>> print(taps[72:78])
601
+ [-0.02286961 -0.06362756 0.57310236 0.57310236 -0.06362756 -0.02286961]
602
+
603
+ """
604
+ fs = _validate_fs(fs, allow_none=True)
605
+ nyq = 0.5 * _get_fs(fs, nyq)
606
+
607
+ if len(freq) != len(gain):
608
+ raise ValueError('freq and gain must be of same length.')
609
+
610
+ if nfreqs is not None and numtaps >= nfreqs:
611
+ raise ValueError(('ntaps must be less than nfreqs, but firwin2 was '
612
+ 'called with ntaps=%d and nfreqs=%s') %
613
+ (numtaps, nfreqs))
614
+
615
+ if freq[0] != 0 or freq[-1] != nyq:
616
+ raise ValueError('freq must start with 0 and end with fs/2.')
617
+ d = np.diff(freq)
618
+ if (d < 0).any():
619
+ raise ValueError('The values in freq must be nondecreasing.')
620
+ d2 = d[:-1] + d[1:]
621
+ if (d2 == 0).any():
622
+ raise ValueError('A value in freq must not occur more than twice.')
623
+ if freq[1] == 0:
624
+ raise ValueError('Value 0 must not be repeated in freq')
625
+ if freq[-2] == nyq:
626
+ raise ValueError('Value fs/2 must not be repeated in freq')
627
+
628
+ if antisymmetric:
629
+ if numtaps % 2 == 0:
630
+ ftype = 4
631
+ else:
632
+ ftype = 3
633
+ else:
634
+ if numtaps % 2 == 0:
635
+ ftype = 2
636
+ else:
637
+ ftype = 1
638
+
639
+ if ftype == 2 and gain[-1] != 0.0:
640
+ raise ValueError("A Type II filter must have zero gain at the "
641
+ "Nyquist frequency.")
642
+ elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0):
643
+ raise ValueError("A Type III filter must have zero gain at zero "
644
+ "and Nyquist frequencies.")
645
+ elif ftype == 4 and gain[0] != 0.0:
646
+ raise ValueError("A Type IV filter must have zero gain at zero "
647
+ "frequency.")
648
+
649
+ if nfreqs is None:
650
+ nfreqs = 1 + 2 ** int(ceil(log(numtaps, 2)))
651
+
652
+ if (d == 0).any():
653
+ # Tweak any repeated values in freq so that interp works.
654
+ freq = np.array(freq, copy=True)
655
+ eps = np.finfo(float).eps * nyq
656
+ for k in range(len(freq) - 1):
657
+ if freq[k] == freq[k + 1]:
658
+ freq[k] = freq[k] - eps
659
+ freq[k + 1] = freq[k + 1] + eps
660
+ # Check if freq is strictly increasing after tweak
661
+ d = np.diff(freq)
662
+ if (d <= 0).any():
663
+ raise ValueError("freq cannot contain numbers that are too close "
664
+ "(within eps * (fs/2): "
665
+ f"{eps}) to a repeated value")
666
+
667
+ # Linearly interpolate the desired response on a uniform mesh `x`.
668
+ x = np.linspace(0.0, nyq, nfreqs)
669
+ fx = np.interp(x, freq, gain)
670
+
671
+ # Adjust the phases of the coefficients so that the first `ntaps` of the
672
+ # inverse FFT are the desired filter coefficients.
673
+ shift = np.exp(-(numtaps - 1) / 2. * 1.j * np.pi * x / nyq)
674
+ if ftype > 2:
675
+ shift *= 1j
676
+
677
+ fx2 = fx * shift
678
+
679
+ # Use irfft to compute the inverse FFT.
680
+ out_full = irfft(fx2)
681
+
682
+ if window is not None:
683
+ # Create the window to apply to the filter coefficients.
684
+ from .windows import get_window
685
+ wind = get_window(window, numtaps, fftbins=False)
686
+ else:
687
+ wind = 1
688
+
689
+ # Keep only the first `numtaps` coefficients in `out`, and multiply by
690
+ # the window.
691
+ out = out_full[:numtaps] * wind
692
+
693
+ if ftype == 3:
694
+ out[out.size // 2] = 0.0
695
+
696
+ return out
697
+
698
+
699
+ @_deprecate_positional_args(version="1.14")
700
+ def remez(numtaps, bands, desired, *, weight=None, Hz=_NoValue, type='bandpass',
701
+ maxiter=25, grid_density=16, fs=None):
702
+ """
703
+ Calculate the minimax optimal filter using the Remez exchange algorithm.
704
+
705
+ Calculate the filter-coefficients for the finite impulse response
706
+ (FIR) filter whose transfer function minimizes the maximum error
707
+ between the desired gain and the realized gain in the specified
708
+ frequency bands using the Remez exchange algorithm.
709
+
710
+ Parameters
711
+ ----------
712
+ numtaps : int
713
+ The desired number of taps in the filter. The number of taps is
714
+ the number of terms in the filter, or the filter order plus one.
715
+ bands : array_like
716
+ A monotonic sequence containing the band edges.
717
+ All elements must be non-negative and less than half the sampling
718
+ frequency as given by `fs`.
719
+ desired : array_like
720
+ A sequence half the size of bands containing the desired gain
721
+ in each of the specified bands.
722
+ weight : array_like, optional
723
+ A relative weighting to give to each band region. The length of
724
+ `weight` has to be half the length of `bands`.
725
+ Hz : scalar, optional, deprecated
726
+ The sampling frequency in Hz. Default is 1.
727
+
728
+ .. deprecated:: 1.0.0
729
+ `remez` keyword argument `Hz` is deprecated in favour of `fs` and
730
+ will be removed in SciPy 1.14.0.
731
+ type : {'bandpass', 'differentiator', 'hilbert'}, optional
732
+ The type of filter:
733
+
734
+ * 'bandpass' : flat response in bands. This is the default.
735
+
736
+ * 'differentiator' : frequency proportional response in bands.
737
+
738
+ * 'hilbert' : filter with odd symmetry, that is, type III
739
+ (for even order) or type IV (for odd order)
740
+ linear phase filters.
741
+
742
+ maxiter : int, optional
743
+ Maximum number of iterations of the algorithm. Default is 25.
744
+ grid_density : int, optional
745
+ Grid density. The dense grid used in `remez` is of size
746
+ ``(numtaps + 1) * grid_density``. Default is 16.
747
+ fs : float, optional
748
+ The sampling frequency of the signal. Default is 1.
749
+
750
+ Returns
751
+ -------
752
+ out : ndarray
753
+ A rank-1 array containing the coefficients of the optimal
754
+ (in a minimax sense) filter.
755
+
756
+ See Also
757
+ --------
758
+ firls
759
+ firwin
760
+ firwin2
761
+ minimum_phase
762
+
763
+ References
764
+ ----------
765
+ .. [1] J. H. McClellan and T. W. Parks, "A unified approach to the
766
+ design of optimum FIR linear phase digital filters",
767
+ IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.
768
+ .. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer
769
+ Program for Designing Optimum FIR Linear Phase Digital
770
+ Filters", IEEE Trans. Audio Electroacoust., vol. AU-21,
771
+ pp. 506-525, 1973.
772
+
773
+ Examples
774
+ --------
775
+ In these examples, `remez` is used to design low-pass, high-pass,
776
+ band-pass and band-stop filters. The parameters that define each filter
777
+ are the filter order, the band boundaries, the transition widths of the
778
+ boundaries, the desired gains in each band, and the sampling frequency.
779
+
780
+ We'll use a sample frequency of 22050 Hz in all the examples. In each
781
+ example, the desired gain in each band is either 0 (for a stop band)
782
+ or 1 (for a pass band).
783
+
784
+ `freqz` is used to compute the frequency response of each filter, and
785
+ the utility function ``plot_response`` defined below is used to plot
786
+ the response.
787
+
788
+ >>> import numpy as np
789
+ >>> from scipy import signal
790
+ >>> import matplotlib.pyplot as plt
791
+
792
+ >>> fs = 22050 # Sample rate, Hz
793
+
794
+ >>> def plot_response(w, h, title):
795
+ ... "Utility function to plot response functions"
796
+ ... fig = plt.figure()
797
+ ... ax = fig.add_subplot(111)
798
+ ... ax.plot(w, 20*np.log10(np.abs(h)))
799
+ ... ax.set_ylim(-40, 5)
800
+ ... ax.grid(True)
801
+ ... ax.set_xlabel('Frequency (Hz)')
802
+ ... ax.set_ylabel('Gain (dB)')
803
+ ... ax.set_title(title)
804
+
805
+ The first example is a low-pass filter, with cutoff frequency 8 kHz.
806
+ The filter length is 325, and the transition width from pass to stop
807
+ is 100 Hz.
808
+
809
+ >>> cutoff = 8000.0 # Desired cutoff frequency, Hz
810
+ >>> trans_width = 100 # Width of transition from pass to stop, Hz
811
+ >>> numtaps = 325 # Size of the FIR filter.
812
+ >>> taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5*fs],
813
+ ... [1, 0], fs=fs)
814
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
815
+ >>> plot_response(w, h, "Low-pass Filter")
816
+ >>> plt.show()
817
+
818
+ This example shows a high-pass filter:
819
+
820
+ >>> cutoff = 2000.0 # Desired cutoff frequency, Hz
821
+ >>> trans_width = 250 # Width of transition from pass to stop, Hz
822
+ >>> numtaps = 125 # Size of the FIR filter.
823
+ >>> taps = signal.remez(numtaps, [0, cutoff - trans_width, cutoff, 0.5*fs],
824
+ ... [0, 1], fs=fs)
825
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
826
+ >>> plot_response(w, h, "High-pass Filter")
827
+ >>> plt.show()
828
+
829
+ This example shows a band-pass filter with a pass-band from 2 kHz to
830
+ 5 kHz. The transition width is 260 Hz and the length of the filter
831
+ is 63, which is smaller than in the other examples:
832
+
833
+ >>> band = [2000, 5000] # Desired pass band, Hz
834
+ >>> trans_width = 260 # Width of transition from pass to stop, Hz
835
+ >>> numtaps = 63 # Size of the FIR filter.
836
+ >>> edges = [0, band[0] - trans_width, band[0], band[1],
837
+ ... band[1] + trans_width, 0.5*fs]
838
+ >>> taps = signal.remez(numtaps, edges, [0, 1, 0], fs=fs)
839
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
840
+ >>> plot_response(w, h, "Band-pass Filter")
841
+ >>> plt.show()
842
+
843
+ The low order leads to higher ripple and less steep transitions.
844
+
845
+ The next example shows a band-stop filter.
846
+
847
+ >>> band = [6000, 8000] # Desired stop band, Hz
848
+ >>> trans_width = 200 # Width of transition from pass to stop, Hz
849
+ >>> numtaps = 175 # Size of the FIR filter.
850
+ >>> edges = [0, band[0] - trans_width, band[0], band[1],
851
+ ... band[1] + trans_width, 0.5*fs]
852
+ >>> taps = signal.remez(numtaps, edges, [1, 0, 1], fs=fs)
853
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
854
+ >>> plot_response(w, h, "Band-stop Filter")
855
+ >>> plt.show()
856
+
857
+ """
858
+ fs = _validate_fs(fs, allow_none=True)
859
+ if Hz is _NoValue and fs is None:
860
+ fs = 1.0
861
+ elif Hz is not _NoValue:
862
+ if fs is not None:
863
+ raise ValueError("Values cannot be given for both 'Hz' and 'fs'.")
864
+ msg = ("'remez' keyword argument 'Hz' is deprecated in favour of 'fs'"
865
+ " and will be removed in SciPy 1.14.0.")
866
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
867
+ fs = Hz
868
+
869
+ # Convert type
870
+ try:
871
+ tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type]
872
+ except KeyError as e:
873
+ raise ValueError("Type must be 'bandpass', 'differentiator', "
874
+ "or 'hilbert'") from e
875
+
876
+ # Convert weight
877
+ if weight is None:
878
+ weight = [1] * len(desired)
879
+
880
+ bands = np.asarray(bands).copy()
881
+ return _sigtools._remez(numtaps, bands, desired, weight, tnum, fs,
882
+ maxiter, grid_density)
883
+
884
+
885
+ @_deprecate_positional_args(version="1.14")
886
+ def firls(numtaps, bands, desired, *, weight=None, nyq=_NoValue, fs=None):
887
+ """
888
+ FIR filter design using least-squares error minimization.
889
+
890
+ Calculate the filter coefficients for the linear-phase finite
891
+ impulse response (FIR) filter which has the best approximation
892
+ to the desired frequency response described by `bands` and
893
+ `desired` in the least squares sense (i.e., the integral of the
894
+ weighted mean-squared error within the specified bands is
895
+ minimized).
896
+
897
+ Parameters
898
+ ----------
899
+ numtaps : int
900
+ The number of taps in the FIR filter. `numtaps` must be odd.
901
+ bands : array_like
902
+ A monotonic nondecreasing sequence containing the band edges in
903
+ Hz. All elements must be non-negative and less than or equal to
904
+ the Nyquist frequency given by `nyq`. The bands are specified as
905
+ frequency pairs, thus, if using a 1D array, its length must be
906
+ even, e.g., `np.array([0, 1, 2, 3, 4, 5])`. Alternatively, the
907
+ bands can be specified as an nx2 sized 2D array, where n is the
908
+ number of bands, e.g, `np.array([[0, 1], [2, 3], [4, 5]])`.
909
+ desired : array_like
910
+ A sequence the same size as `bands` containing the desired gain
911
+ at the start and end point of each band.
912
+ weight : array_like, optional
913
+ A relative weighting to give to each band region when solving
914
+ the least squares problem. `weight` has to be half the size of
915
+ `bands`.
916
+ nyq : float, optional, deprecated
917
+ This is the Nyquist frequency. Each frequency in `bands` must be
918
+ between 0 and `nyq` (inclusive). Default is 1.
919
+
920
+ .. deprecated:: 1.0.0
921
+ `firls` keyword argument `nyq` is deprecated in favour of `fs` and
922
+ will be removed in SciPy 1.14.0.
923
+ fs : float, optional
924
+ The sampling frequency of the signal. Each frequency in `bands`
925
+ must be between 0 and ``fs/2`` (inclusive). Default is 2.
926
+
927
+ Returns
928
+ -------
929
+ coeffs : ndarray
930
+ Coefficients of the optimal (in a least squares sense) FIR filter.
931
+
932
+ See Also
933
+ --------
934
+ firwin
935
+ firwin2
936
+ minimum_phase
937
+ remez
938
+
939
+ Notes
940
+ -----
941
+ This implementation follows the algorithm given in [1]_.
942
+ As noted there, least squares design has multiple advantages:
943
+
944
+ 1. Optimal in a least-squares sense.
945
+ 2. Simple, non-iterative method.
946
+ 3. The general solution can obtained by solving a linear
947
+ system of equations.
948
+ 4. Allows the use of a frequency dependent weighting function.
949
+
950
+ This function constructs a Type I linear phase FIR filter, which
951
+ contains an odd number of `coeffs` satisfying for :math:`n < numtaps`:
952
+
953
+ .. math:: coeffs(n) = coeffs(numtaps - 1 - n)
954
+
955
+ The odd number of coefficients and filter symmetry avoid boundary
956
+ conditions that could otherwise occur at the Nyquist and 0 frequencies
957
+ (e.g., for Type II, III, or IV variants).
958
+
959
+ .. versionadded:: 0.18
960
+
961
+ References
962
+ ----------
963
+ .. [1] Ivan Selesnick, Linear-Phase Fir Filter Design By Least Squares.
964
+ OpenStax CNX. Aug 9, 2005.
965
+ http://cnx.org/contents/eb1ecb35-03a9-4610-ba87-41cd771c95f2@7
966
+
967
+ Examples
968
+ --------
969
+ We want to construct a band-pass filter. Note that the behavior in the
970
+ frequency ranges between our stop bands and pass bands is unspecified,
971
+ and thus may overshoot depending on the parameters of our filter:
972
+
973
+ >>> import numpy as np
974
+ >>> from scipy import signal
975
+ >>> import matplotlib.pyplot as plt
976
+ >>> fig, axs = plt.subplots(2)
977
+ >>> fs = 10.0 # Hz
978
+ >>> desired = (0, 0, 1, 1, 0, 0)
979
+ >>> for bi, bands in enumerate(((0, 1, 2, 3, 4, 5), (0, 1, 2, 4, 4.5, 5))):
980
+ ... fir_firls = signal.firls(73, bands, desired, fs=fs)
981
+ ... fir_remez = signal.remez(73, bands, desired[::2], fs=fs)
982
+ ... fir_firwin2 = signal.firwin2(73, bands, desired, fs=fs)
983
+ ... hs = list()
984
+ ... ax = axs[bi]
985
+ ... for fir in (fir_firls, fir_remez, fir_firwin2):
986
+ ... freq, response = signal.freqz(fir)
987
+ ... hs.append(ax.semilogy(0.5*fs*freq/np.pi, np.abs(response))[0])
988
+ ... for band, gains in zip(zip(bands[::2], bands[1::2]),
989
+ ... zip(desired[::2], desired[1::2])):
990
+ ... ax.semilogy(band, np.maximum(gains, 1e-7), 'k--', linewidth=2)
991
+ ... if bi == 0:
992
+ ... ax.legend(hs, ('firls', 'remez', 'firwin2'),
993
+ ... loc='lower center', frameon=False)
994
+ ... else:
995
+ ... ax.set_xlabel('Frequency (Hz)')
996
+ ... ax.grid(True)
997
+ ... ax.set(title='Band-pass %d-%d Hz' % bands[2:4], ylabel='Magnitude')
998
+ ...
999
+ >>> fig.tight_layout()
1000
+ >>> plt.show()
1001
+
1002
+ """
1003
+ fs = _validate_fs(fs, allow_none=True)
1004
+ nyq = 0.5 * _get_fs(fs, nyq)
1005
+
1006
+ numtaps = int(numtaps)
1007
+ if numtaps % 2 == 0 or numtaps < 1:
1008
+ raise ValueError("numtaps must be odd and >= 1")
1009
+ M = (numtaps-1) // 2
1010
+
1011
+ # normalize bands 0->1 and make it 2 columns
1012
+ nyq = float(nyq)
1013
+ if nyq <= 0:
1014
+ raise ValueError('nyq must be positive, got %s <= 0.' % nyq)
1015
+ bands = np.asarray(bands).flatten() / nyq
1016
+ if len(bands) % 2 != 0:
1017
+ raise ValueError("bands must contain frequency pairs.")
1018
+ if (bands < 0).any() or (bands > 1).any():
1019
+ raise ValueError("bands must be between 0 and 1 relative to Nyquist")
1020
+ bands.shape = (-1, 2)
1021
+
1022
+ # check remaining params
1023
+ desired = np.asarray(desired).flatten()
1024
+ if bands.size != desired.size:
1025
+ raise ValueError("desired must have one entry per frequency, got {} "
1026
+ "gains for {} frequencies.".format(desired.size, bands.size))
1027
+ desired.shape = (-1, 2)
1028
+ if (np.diff(bands) <= 0).any() or (np.diff(bands[:, 0]) < 0).any():
1029
+ raise ValueError("bands must be monotonically nondecreasing and have "
1030
+ "width > 0.")
1031
+ if (bands[:-1, 1] > bands[1:, 0]).any():
1032
+ raise ValueError("bands must not overlap.")
1033
+ if (desired < 0).any():
1034
+ raise ValueError("desired must be non-negative.")
1035
+ if weight is None:
1036
+ weight = np.ones(len(desired))
1037
+ weight = np.asarray(weight).flatten()
1038
+ if len(weight) != len(desired):
1039
+ raise ValueError("weight must be the same size as the number of "
1040
+ f"band pairs ({len(bands)}).")
1041
+ if (weight < 0).any():
1042
+ raise ValueError("weight must be non-negative.")
1043
+
1044
+ # Set up the linear matrix equation to be solved, Qa = b
1045
+
1046
+ # We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n)
1047
+ # where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel.
1048
+
1049
+ # We omit the factor of 0.5 above, instead adding it during coefficient
1050
+ # calculation.
1051
+
1052
+ # We also omit the 1/π from both Q and b equations, as they cancel
1053
+ # during solving.
1054
+
1055
+ # We have that:
1056
+ # q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π)
1057
+ # Using our normalization ω=πf and with a constant weight W over each
1058
+ # interval f1->f2 we get:
1059
+ # q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf
1060
+ # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
1061
+ n = np.arange(numtaps)[:, np.newaxis, np.newaxis]
1062
+ q = np.dot(np.diff(np.sinc(bands * n) * bands, axis=2)[:, :, 0], weight)
1063
+
1064
+ # Now we assemble our sum of Toeplitz and Hankel
1065
+ Q1 = toeplitz(q[:M+1])
1066
+ Q2 = hankel(q[:M+1], q[M:])
1067
+ Q = Q1 + Q2
1068
+
1069
+ # Now for b(n) we have that:
1070
+ # b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π)
1071
+ # Using our normalization ω=πf and with a constant weight W over each
1072
+ # interval and a linear term for D(ω) we get (over each f1->f2 interval):
1073
+ # b(n) = W ∫ (mf+c)cos(πnf)df
1074
+ # = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2
1075
+ # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
1076
+ n = n[:M + 1] # only need this many coefficients here
1077
+ # Choose m and c such that we are at the start and end weights
1078
+ m = (np.diff(desired, axis=1) / np.diff(bands, axis=1))
1079
+ c = desired[:, [0]] - bands[:, [0]] * m
1080
+ b = bands * (m*bands + c) * np.sinc(bands * n)
1081
+ # Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0
1082
+ b[0] -= m * bands * bands / 2.
1083
+ b[1:] += m * np.cos(n[1:] * np.pi * bands) / (np.pi * n[1:]) ** 2
1084
+ b = np.dot(np.diff(b, axis=2)[:, :, 0], weight)
1085
+
1086
+ # Now we can solve the equation
1087
+ try: # try the fast way
1088
+ with warnings.catch_warnings(record=True) as w:
1089
+ warnings.simplefilter('always')
1090
+ a = solve(Q, b, assume_a="pos", check_finite=False)
1091
+ for ww in w:
1092
+ if (ww.category == LinAlgWarning and
1093
+ str(ww.message).startswith('Ill-conditioned matrix')):
1094
+ raise LinAlgError(str(ww.message))
1095
+ except LinAlgError: # in case Q is rank deficient
1096
+ # This is faster than pinvh, even though we don't explicitly use
1097
+ # the symmetry here. gelsy was faster than gelsd and gelss in
1098
+ # some non-exhaustive tests.
1099
+ a = lstsq(Q, b, lapack_driver='gelsy')[0]
1100
+
1101
+ # make coefficients symmetric (linear phase)
1102
+ coeffs = np.hstack((a[:0:-1], 2 * a[0], a[1:]))
1103
+ return coeffs
1104
+
1105
+
1106
+ def _dhtm(mag):
1107
+ """Compute the modified 1-D discrete Hilbert transform
1108
+
1109
+ Parameters
1110
+ ----------
1111
+ mag : ndarray
1112
+ The magnitude spectrum. Should be 1-D with an even length, and
1113
+ preferably a fast length for FFT/IFFT.
1114
+ """
1115
+ # Adapted based on code by Niranjan Damera-Venkata,
1116
+ # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`)
1117
+ sig = np.zeros(len(mag))
1118
+ # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5
1119
+ midpt = len(mag) // 2
1120
+ sig[1:midpt] = 1
1121
+ sig[midpt+1:] = -1
1122
+ # eventually if we want to support complex filters, we will need a
1123
+ # np.abs() on the mag inside the log, and should remove the .real
1124
+ recon = ifft(mag * np.exp(fft(sig * ifft(np.log(mag))))).real
1125
+ return recon
1126
+
1127
+
1128
+ def minimum_phase(h, method='homomorphic', n_fft=None):
1129
+ """Convert a linear-phase FIR filter to minimum phase
1130
+
1131
+ Parameters
1132
+ ----------
1133
+ h : array
1134
+ Linear-phase FIR filter coefficients.
1135
+ method : {'hilbert', 'homomorphic'}
1136
+ The method to use:
1137
+
1138
+ 'homomorphic' (default)
1139
+ This method [4]_ [5]_ works best with filters with an
1140
+ odd number of taps, and the resulting minimum phase filter
1141
+ will have a magnitude response that approximates the square
1142
+ root of the original filter's magnitude response.
1143
+
1144
+ 'hilbert'
1145
+ This method [1]_ is designed to be used with equiripple
1146
+ filters (e.g., from `remez`) with unity or zero gain
1147
+ regions.
1148
+
1149
+ n_fft : int
1150
+ The number of points to use for the FFT. Should be at least a
1151
+ few times larger than the signal length (see Notes).
1152
+
1153
+ Returns
1154
+ -------
1155
+ h_minimum : array
1156
+ The minimum-phase version of the filter, with length
1157
+ ``(length(h) + 1) // 2``.
1158
+
1159
+ See Also
1160
+ --------
1161
+ firwin
1162
+ firwin2
1163
+ remez
1164
+
1165
+ Notes
1166
+ -----
1167
+ Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection
1168
+ of an FFT length to estimate the complex cepstrum of the filter.
1169
+
1170
+ In the case of the Hilbert method, the deviation from the ideal
1171
+ spectrum ``epsilon`` is related to the number of stopband zeros
1172
+ ``n_stop`` and FFT length ``n_fft`` as::
1173
+
1174
+ epsilon = 2. * n_stop / n_fft
1175
+
1176
+ For example, with 100 stopband zeros and a FFT length of 2048,
1177
+ ``epsilon = 0.0976``. If we conservatively assume that the number of
1178
+ stopband zeros is one less than the filter length, we can take the FFT
1179
+ length to be the next power of 2 that satisfies ``epsilon=0.01`` as::
1180
+
1181
+ n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01)))
1182
+
1183
+ This gives reasonable results for both the Hilbert and homomorphic
1184
+ methods, and gives the value used when ``n_fft=None``.
1185
+
1186
+ Alternative implementations exist for creating minimum-phase filters,
1187
+ including zero inversion [2]_ and spectral factorization [3]_ [4]_.
1188
+ For more information, see:
1189
+
1190
+ http://dspguru.com/dsp/howtos/how-to-design-minimum-phase-fir-filters
1191
+
1192
+ References
1193
+ ----------
1194
+ .. [1] N. Damera-Venkata and B. L. Evans, "Optimal design of real and
1195
+ complex minimum phase digital FIR filters," Acoustics, Speech,
1196
+ and Signal Processing, 1999. Proceedings., 1999 IEEE International
1197
+ Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3.
1198
+ :doi:`10.1109/ICASSP.1999.756179`
1199
+ .. [2] X. Chen and T. W. Parks, "Design of optimal minimum phase FIR
1200
+ filters by direct factorization," Signal Processing,
1201
+ vol. 10, no. 4, pp. 369-383, Jun. 1986.
1202
+ .. [3] T. Saramaki, "Finite Impulse Response Filter Design," in
1203
+ Handbook for Digital Signal Processing, chapter 4,
1204
+ New York: Wiley-Interscience, 1993.
1205
+ .. [4] J. S. Lim, Advanced Topics in Signal Processing.
1206
+ Englewood Cliffs, N.J.: Prentice Hall, 1988.
1207
+ .. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck,
1208
+ "Discrete-Time Signal Processing," 2nd edition.
1209
+ Upper Saddle River, N.J.: Prentice Hall, 1999.
1210
+
1211
+ Examples
1212
+ --------
1213
+ Create an optimal linear-phase filter, then convert it to minimum phase:
1214
+
1215
+ >>> import numpy as np
1216
+ >>> from scipy.signal import remez, minimum_phase, freqz, group_delay
1217
+ >>> import matplotlib.pyplot as plt
1218
+ >>> freq = [0, 0.2, 0.3, 1.0]
1219
+ >>> desired = [1, 0]
1220
+ >>> h_linear = remez(151, freq, desired, fs=2.)
1221
+
1222
+ Convert it to minimum phase:
1223
+
1224
+ >>> h_min_hom = minimum_phase(h_linear, method='homomorphic')
1225
+ >>> h_min_hil = minimum_phase(h_linear, method='hilbert')
1226
+
1227
+ Compare the three filters:
1228
+
1229
+ >>> fig, axs = plt.subplots(4, figsize=(4, 8))
1230
+ >>> for h, style, color in zip((h_linear, h_min_hom, h_min_hil),
1231
+ ... ('-', '-', '--'), ('k', 'r', 'c')):
1232
+ ... w, H = freqz(h)
1233
+ ... w, gd = group_delay((h, 1))
1234
+ ... w /= np.pi
1235
+ ... axs[0].plot(h, color=color, linestyle=style)
1236
+ ... axs[1].plot(w, np.abs(H), color=color, linestyle=style)
1237
+ ... axs[2].plot(w, 20 * np.log10(np.abs(H)), color=color, linestyle=style)
1238
+ ... axs[3].plot(w, gd, color=color, linestyle=style)
1239
+ >>> for ax in axs:
1240
+ ... ax.grid(True, color='0.5')
1241
+ ... ax.fill_between(freq[1:3], *ax.get_ylim(), color='#ffeeaa', zorder=1)
1242
+ >>> axs[0].set(xlim=[0, len(h_linear) - 1], ylabel='Amplitude', xlabel='Samples')
1243
+ >>> axs[1].legend(['Linear', 'Min-Hom', 'Min-Hil'], title='Phase')
1244
+ >>> for ax, ylim in zip(axs[1:], ([0, 1.1], [-150, 10], [-60, 60])):
1245
+ ... ax.set(xlim=[0, 1], ylim=ylim, xlabel='Frequency')
1246
+ >>> axs[1].set(ylabel='Magnitude')
1247
+ >>> axs[2].set(ylabel='Magnitude (dB)')
1248
+ >>> axs[3].set(ylabel='Group delay')
1249
+ >>> plt.tight_layout()
1250
+
1251
+ """
1252
+ h = np.asarray(h)
1253
+ if np.iscomplexobj(h):
1254
+ raise ValueError('Complex filters not supported')
1255
+ if h.ndim != 1 or h.size <= 2:
1256
+ raise ValueError('h must be 1-D and at least 2 samples long')
1257
+ n_half = len(h) // 2
1258
+ if not np.allclose(h[-n_half:][::-1], h[:n_half]):
1259
+ warnings.warn('h does not appear to by symmetric, conversion may fail',
1260
+ RuntimeWarning, stacklevel=2)
1261
+ if not isinstance(method, str) or method not in \
1262
+ ('homomorphic', 'hilbert',):
1263
+ raise ValueError(f'method must be "homomorphic" or "hilbert", got {method!r}')
1264
+ if n_fft is None:
1265
+ n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01)))
1266
+ n_fft = int(n_fft)
1267
+ if n_fft < len(h):
1268
+ raise ValueError('n_fft must be at least len(h)==%s' % len(h))
1269
+ if method == 'hilbert':
1270
+ w = np.arange(n_fft) * (2 * np.pi / n_fft * n_half)
1271
+ H = np.real(fft(h, n_fft) * np.exp(1j * w))
1272
+ dp = max(H) - 1
1273
+ ds = 0 - min(H)
1274
+ S = 4. / (np.sqrt(1+dp+ds) + np.sqrt(1-dp+ds)) ** 2
1275
+ H += ds
1276
+ H *= S
1277
+ H = np.sqrt(H, out=H)
1278
+ H += 1e-10 # ensure that the log does not explode
1279
+ h_minimum = _dhtm(H)
1280
+ else: # method == 'homomorphic'
1281
+ # zero-pad; calculate the DFT
1282
+ h_temp = np.abs(fft(h, n_fft))
1283
+ # take 0.25*log(|H|**2) = 0.5*log(|H|)
1284
+ h_temp += 1e-7 * h_temp[h_temp > 0].min() # don't let log blow up
1285
+ np.log(h_temp, out=h_temp)
1286
+ h_temp *= 0.5
1287
+ # IDFT
1288
+ h_temp = ifft(h_temp).real
1289
+ # multiply pointwise by the homomorphic filter
1290
+ # lmin[n] = 2u[n] - d[n]
1291
+ win = np.zeros(n_fft)
1292
+ win[0] = 1
1293
+ stop = (len(h) + 1) // 2
1294
+ win[1:stop] = 2
1295
+ if len(h) % 2:
1296
+ win[stop] = 1
1297
+ h_temp *= win
1298
+ h_temp = ifft(np.exp(fft(h_temp)))
1299
+ h_minimum = h_temp.real
1300
+ n_out = n_half + len(h) % 2
1301
+ return h_minimum[:n_out]
llmeval-env/lib/python3.10/site-packages/scipy/signal/_lti_conversion.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ltisys -- a collection of functions to convert linear time invariant systems
3
+ from one representation to another.
4
+ """
5
+ import numpy
6
+ import numpy as np
7
+ from numpy import (r_, eye, atleast_2d, poly, dot,
8
+ asarray, prod, zeros, array, outer)
9
+ from scipy import linalg
10
+
11
+ from ._filter_design import tf2zpk, zpk2tf, normalize
12
+
13
+
14
+ __all__ = ['tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk',
15
+ 'cont2discrete']
16
+
17
+
18
+ def tf2ss(num, den):
19
+ r"""Transfer function to state-space representation.
20
+
21
+ Parameters
22
+ ----------
23
+ num, den : array_like
24
+ Sequences representing the coefficients of the numerator and
25
+ denominator polynomials, in order of descending degree. The
26
+ denominator needs to be at least as long as the numerator.
27
+
28
+ Returns
29
+ -------
30
+ A, B, C, D : ndarray
31
+ State space representation of the system, in controller canonical
32
+ form.
33
+
34
+ Examples
35
+ --------
36
+ Convert the transfer function:
37
+
38
+ .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
39
+
40
+ >>> num = [1, 3, 3]
41
+ >>> den = [1, 2, 1]
42
+
43
+ to the state-space representation:
44
+
45
+ .. math::
46
+
47
+ \dot{\textbf{x}}(t) =
48
+ \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
49
+ \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
50
+
51
+ \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
52
+ \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
53
+
54
+ >>> from scipy.signal import tf2ss
55
+ >>> A, B, C, D = tf2ss(num, den)
56
+ >>> A
57
+ array([[-2., -1.],
58
+ [ 1., 0.]])
59
+ >>> B
60
+ array([[ 1.],
61
+ [ 0.]])
62
+ >>> C
63
+ array([[ 1., 2.]])
64
+ >>> D
65
+ array([[ 1.]])
66
+ """
67
+ # Controller canonical state-space representation.
68
+ # if M+1 = len(num) and K+1 = len(den) then we must have M <= K
69
+ # states are found by asserting that X(s) = U(s) / D(s)
70
+ # then Y(s) = N(s) * X(s)
71
+ #
72
+ # A, B, C, and D follow quite naturally.
73
+ #
74
+ num, den = normalize(num, den) # Strips zeros, checks arrays
75
+ nn = len(num.shape)
76
+ if nn == 1:
77
+ num = asarray([num], num.dtype)
78
+ M = num.shape[1]
79
+ K = len(den)
80
+ if M > K:
81
+ msg = "Improper transfer function. `num` is longer than `den`."
82
+ raise ValueError(msg)
83
+ if M == 0 or K == 0: # Null system
84
+ return (array([], float), array([], float), array([], float),
85
+ array([], float))
86
+
87
+ # pad numerator to have same number of columns has denominator
88
+ num = np.hstack((np.zeros((num.shape[0], K - M), dtype=num.dtype), num))
89
+
90
+ if num.shape[-1] > 0:
91
+ D = atleast_2d(num[:, 0])
92
+
93
+ else:
94
+ # We don't assign it an empty array because this system
95
+ # is not 'null'. It just doesn't have a non-zero D
96
+ # matrix. Thus, it should have a non-zero shape so that
97
+ # it can be operated on by functions like 'ss2tf'
98
+ D = array([[0]], float)
99
+
100
+ if K == 1:
101
+ D = D.reshape(num.shape)
102
+
103
+ return (zeros((1, 1)), zeros((1, D.shape[1])),
104
+ zeros((D.shape[0], 1)), D)
105
+
106
+ frow = -array([den[1:]])
107
+ A = r_[frow, eye(K - 2, K - 1)]
108
+ B = eye(K - 1, 1)
109
+ C = num[:, 1:] - outer(num[:, 0], den[1:])
110
+ D = D.reshape((C.shape[0], B.shape[1]))
111
+
112
+ return A, B, C, D
113
+
114
+
115
+ def _none_to_empty_2d(arg):
116
+ if arg is None:
117
+ return zeros((0, 0))
118
+ else:
119
+ return arg
120
+
121
+
122
+ def _atleast_2d_or_none(arg):
123
+ if arg is not None:
124
+ return atleast_2d(arg)
125
+
126
+
127
+ def _shape_or_none(M):
128
+ if M is not None:
129
+ return M.shape
130
+ else:
131
+ return (None,) * 2
132
+
133
+
134
+ def _choice_not_none(*args):
135
+ for arg in args:
136
+ if arg is not None:
137
+ return arg
138
+
139
+
140
+ def _restore(M, shape):
141
+ if M.shape == (0, 0):
142
+ return zeros(shape)
143
+ else:
144
+ if M.shape != shape:
145
+ raise ValueError("The input arrays have incompatible shapes.")
146
+ return M
147
+
148
+
149
+ def abcd_normalize(A=None, B=None, C=None, D=None):
150
+ """Check state-space matrices and ensure they are 2-D.
151
+
152
+ If enough information on the system is provided, that is, enough
153
+ properly-shaped arrays are passed to the function, the missing ones
154
+ are built from this information, ensuring the correct number of
155
+ rows and columns. Otherwise a ValueError is raised.
156
+
157
+ Parameters
158
+ ----------
159
+ A, B, C, D : array_like, optional
160
+ State-space matrices. All of them are None (missing) by default.
161
+ See `ss2tf` for format.
162
+
163
+ Returns
164
+ -------
165
+ A, B, C, D : array
166
+ Properly shaped state-space matrices.
167
+
168
+ Raises
169
+ ------
170
+ ValueError
171
+ If not enough information on the system was provided.
172
+
173
+ """
174
+ A, B, C, D = map(_atleast_2d_or_none, (A, B, C, D))
175
+
176
+ MA, NA = _shape_or_none(A)
177
+ MB, NB = _shape_or_none(B)
178
+ MC, NC = _shape_or_none(C)
179
+ MD, ND = _shape_or_none(D)
180
+
181
+ p = _choice_not_none(MA, MB, NC)
182
+ q = _choice_not_none(NB, ND)
183
+ r = _choice_not_none(MC, MD)
184
+ if p is None or q is None or r is None:
185
+ raise ValueError("Not enough information on the system.")
186
+
187
+ A, B, C, D = map(_none_to_empty_2d, (A, B, C, D))
188
+ A = _restore(A, (p, p))
189
+ B = _restore(B, (p, q))
190
+ C = _restore(C, (r, p))
191
+ D = _restore(D, (r, q))
192
+
193
+ return A, B, C, D
194
+
195
+
196
+ def ss2tf(A, B, C, D, input=0):
197
+ r"""State-space to transfer function.
198
+
199
+ A, B, C, D defines a linear state-space system with `p` inputs,
200
+ `q` outputs, and `n` state variables.
201
+
202
+ Parameters
203
+ ----------
204
+ A : array_like
205
+ State (or system) matrix of shape ``(n, n)``
206
+ B : array_like
207
+ Input matrix of shape ``(n, p)``
208
+ C : array_like
209
+ Output matrix of shape ``(q, n)``
210
+ D : array_like
211
+ Feedthrough (or feedforward) matrix of shape ``(q, p)``
212
+ input : int, optional
213
+ For multiple-input systems, the index of the input to use.
214
+
215
+ Returns
216
+ -------
217
+ num : 2-D ndarray
218
+ Numerator(s) of the resulting transfer function(s). `num` has one row
219
+ for each of the system's outputs. Each row is a sequence representation
220
+ of the numerator polynomial.
221
+ den : 1-D ndarray
222
+ Denominator of the resulting transfer function(s). `den` is a sequence
223
+ representation of the denominator polynomial.
224
+
225
+ Examples
226
+ --------
227
+ Convert the state-space representation:
228
+
229
+ .. math::
230
+
231
+ \dot{\textbf{x}}(t) =
232
+ \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
233
+ \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
234
+
235
+ \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
236
+ \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
237
+
238
+ >>> A = [[-2, -1], [1, 0]]
239
+ >>> B = [[1], [0]] # 2-D column vector
240
+ >>> C = [[1, 2]] # 2-D row vector
241
+ >>> D = 1
242
+
243
+ to the transfer function:
244
+
245
+ .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
246
+
247
+ >>> from scipy.signal import ss2tf
248
+ >>> ss2tf(A, B, C, D)
249
+ (array([[1., 3., 3.]]), array([ 1., 2., 1.]))
250
+ """
251
+ # transfer function is C (sI - A)**(-1) B + D
252
+
253
+ # Check consistency and make them all rank-2 arrays
254
+ A, B, C, D = abcd_normalize(A, B, C, D)
255
+
256
+ nout, nin = D.shape
257
+ if input >= nin:
258
+ raise ValueError("System does not have the input specified.")
259
+
260
+ # make SIMO from possibly MIMO system.
261
+ B = B[:, input:input + 1]
262
+ D = D[:, input:input + 1]
263
+
264
+ try:
265
+ den = poly(A)
266
+ except ValueError:
267
+ den = 1
268
+
269
+ if (prod(B.shape, axis=0) == 0) and (prod(C.shape, axis=0) == 0):
270
+ num = numpy.ravel(D)
271
+ if (prod(D.shape, axis=0) == 0) and (prod(A.shape, axis=0) == 0):
272
+ den = []
273
+ return num, den
274
+
275
+ num_states = A.shape[0]
276
+ type_test = A[:, 0] + B[:, 0] + C[0, :] + D + 0.0
277
+ num = numpy.empty((nout, num_states + 1), type_test.dtype)
278
+ for k in range(nout):
279
+ Ck = atleast_2d(C[k, :])
280
+ num[k] = poly(A - dot(B, Ck)) + (D[k] - 1) * den
281
+
282
+ return num, den
283
+
284
+
285
+ def zpk2ss(z, p, k):
286
+ """Zero-pole-gain representation to state-space representation
287
+
288
+ Parameters
289
+ ----------
290
+ z, p : sequence
291
+ Zeros and poles.
292
+ k : float
293
+ System gain.
294
+
295
+ Returns
296
+ -------
297
+ A, B, C, D : ndarray
298
+ State space representation of the system, in controller canonical
299
+ form.
300
+
301
+ """
302
+ return tf2ss(*zpk2tf(z, p, k))
303
+
304
+
305
+ def ss2zpk(A, B, C, D, input=0):
306
+ """State-space representation to zero-pole-gain representation.
307
+
308
+ A, B, C, D defines a linear state-space system with `p` inputs,
309
+ `q` outputs, and `n` state variables.
310
+
311
+ Parameters
312
+ ----------
313
+ A : array_like
314
+ State (or system) matrix of shape ``(n, n)``
315
+ B : array_like
316
+ Input matrix of shape ``(n, p)``
317
+ C : array_like
318
+ Output matrix of shape ``(q, n)``
319
+ D : array_like
320
+ Feedthrough (or feedforward) matrix of shape ``(q, p)``
321
+ input : int, optional
322
+ For multiple-input systems, the index of the input to use.
323
+
324
+ Returns
325
+ -------
326
+ z, p : sequence
327
+ Zeros and poles.
328
+ k : float
329
+ System gain.
330
+
331
+ """
332
+ return tf2zpk(*ss2tf(A, B, C, D, input=input))
333
+
334
+
335
+ def cont2discrete(system, dt, method="zoh", alpha=None):
336
+ """
337
+ Transform a continuous to a discrete state-space system.
338
+
339
+ Parameters
340
+ ----------
341
+ system : a tuple describing the system or an instance of `lti`
342
+ The following gives the number of elements in the tuple and
343
+ the interpretation:
344
+
345
+ * 1: (instance of `lti`)
346
+ * 2: (num, den)
347
+ * 3: (zeros, poles, gain)
348
+ * 4: (A, B, C, D)
349
+
350
+ dt : float
351
+ The discretization time step.
352
+ method : str, optional
353
+ Which method to use:
354
+
355
+ * gbt: generalized bilinear transformation
356
+ * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
357
+ * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
358
+ * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
359
+ * zoh: zero-order hold (default)
360
+ * foh: first-order hold (*versionadded: 1.3.0*)
361
+ * impulse: equivalent impulse response (*versionadded: 1.3.0*)
362
+
363
+ alpha : float within [0, 1], optional
364
+ The generalized bilinear transformation weighting parameter, which
365
+ should only be specified with method="gbt", and is ignored otherwise
366
+
367
+ Returns
368
+ -------
369
+ sysd : tuple containing the discrete system
370
+ Based on the input type, the output will be of the form
371
+
372
+ * (num, den, dt) for transfer function input
373
+ * (zeros, poles, gain, dt) for zeros-poles-gain input
374
+ * (A, B, C, D, dt) for state-space system input
375
+
376
+ Notes
377
+ -----
378
+ By default, the routine uses a Zero-Order Hold (zoh) method to perform
379
+ the transformation. Alternatively, a generalized bilinear transformation
380
+ may be used, which includes the common Tustin's bilinear approximation,
381
+ an Euler's method technique, or a backwards differencing technique.
382
+
383
+ The Zero-Order Hold (zoh) method is based on [1]_, the generalized bilinear
384
+ approximation is based on [2]_ and [3]_, the First-Order Hold (foh) method
385
+ is based on [4]_.
386
+
387
+ References
388
+ ----------
389
+ .. [1] https://en.wikipedia.org/wiki/Discretization#Discretization_of_linear_state_space_models
390
+
391
+ .. [2] http://techteach.no/publications/discretetime_signals_systems/discrete.pdf
392
+
393
+ .. [3] G. Zhang, X. Chen, and T. Chen, Digital redesign via the generalized
394
+ bilinear transformation, Int. J. Control, vol. 82, no. 4, pp. 741-754,
395
+ 2009.
396
+ (https://www.mypolyuweb.hk/~magzhang/Research/ZCC09_IJC.pdf)
397
+
398
+ .. [4] G. F. Franklin, J. D. Powell, and M. L. Workman, Digital control
399
+ of dynamic systems, 3rd ed. Menlo Park, Calif: Addison-Wesley,
400
+ pp. 204-206, 1998.
401
+
402
+ Examples
403
+ --------
404
+ We can transform a continuous state-space system to a discrete one:
405
+
406
+ >>> import numpy as np
407
+ >>> import matplotlib.pyplot as plt
408
+ >>> from scipy.signal import cont2discrete, lti, dlti, dstep
409
+
410
+ Define a continuous state-space system.
411
+
412
+ >>> A = np.array([[0, 1],[-10., -3]])
413
+ >>> B = np.array([[0],[10.]])
414
+ >>> C = np.array([[1., 0]])
415
+ >>> D = np.array([[0.]])
416
+ >>> l_system = lti(A, B, C, D)
417
+ >>> t, x = l_system.step(T=np.linspace(0, 5, 100))
418
+ >>> fig, ax = plt.subplots()
419
+ >>> ax.plot(t, x, label='Continuous', linewidth=3)
420
+
421
+ Transform it to a discrete state-space system using several methods.
422
+
423
+ >>> dt = 0.1
424
+ >>> for method in ['zoh', 'bilinear', 'euler', 'backward_diff', 'foh', 'impulse']:
425
+ ... d_system = cont2discrete((A, B, C, D), dt, method=method)
426
+ ... s, x_d = dstep(d_system)
427
+ ... ax.step(s, np.squeeze(x_d), label=method, where='post')
428
+ >>> ax.axis([t[0], t[-1], x[0], 1.4])
429
+ >>> ax.legend(loc='best')
430
+ >>> fig.tight_layout()
431
+ >>> plt.show()
432
+
433
+ """
434
+ if len(system) == 1:
435
+ return system.to_discrete()
436
+ if len(system) == 2:
437
+ sysd = cont2discrete(tf2ss(system[0], system[1]), dt, method=method,
438
+ alpha=alpha)
439
+ return ss2tf(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,)
440
+ elif len(system) == 3:
441
+ sysd = cont2discrete(zpk2ss(system[0], system[1], system[2]), dt,
442
+ method=method, alpha=alpha)
443
+ return ss2zpk(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,)
444
+ elif len(system) == 4:
445
+ a, b, c, d = system
446
+ else:
447
+ raise ValueError("First argument must either be a tuple of 2 (tf), "
448
+ "3 (zpk), or 4 (ss) arrays.")
449
+
450
+ if method == 'gbt':
451
+ if alpha is None:
452
+ raise ValueError("Alpha parameter must be specified for the "
453
+ "generalized bilinear transform (gbt) method")
454
+ elif alpha < 0 or alpha > 1:
455
+ raise ValueError("Alpha parameter must be within the interval "
456
+ "[0,1] for the gbt method")
457
+
458
+ if method == 'gbt':
459
+ # This parameter is used repeatedly - compute once here
460
+ ima = np.eye(a.shape[0]) - alpha*dt*a
461
+ ad = linalg.solve(ima, np.eye(a.shape[0]) + (1.0-alpha)*dt*a)
462
+ bd = linalg.solve(ima, dt*b)
463
+
464
+ # Similarly solve for the output equation matrices
465
+ cd = linalg.solve(ima.transpose(), c.transpose())
466
+ cd = cd.transpose()
467
+ dd = d + alpha*np.dot(c, bd)
468
+
469
+ elif method == 'bilinear' or method == 'tustin':
470
+ return cont2discrete(system, dt, method="gbt", alpha=0.5)
471
+
472
+ elif method == 'euler' or method == 'forward_diff':
473
+ return cont2discrete(system, dt, method="gbt", alpha=0.0)
474
+
475
+ elif method == 'backward_diff':
476
+ return cont2discrete(system, dt, method="gbt", alpha=1.0)
477
+
478
+ elif method == 'zoh':
479
+ # Build an exponential matrix
480
+ em_upper = np.hstack((a, b))
481
+
482
+ # Need to stack zeros under the a and b matrices
483
+ em_lower = np.hstack((np.zeros((b.shape[1], a.shape[0])),
484
+ np.zeros((b.shape[1], b.shape[1]))))
485
+
486
+ em = np.vstack((em_upper, em_lower))
487
+ ms = linalg.expm(dt * em)
488
+
489
+ # Dispose of the lower rows
490
+ ms = ms[:a.shape[0], :]
491
+
492
+ ad = ms[:, 0:a.shape[1]]
493
+ bd = ms[:, a.shape[1]:]
494
+
495
+ cd = c
496
+ dd = d
497
+
498
+ elif method == 'foh':
499
+ # Size parameters for convenience
500
+ n = a.shape[0]
501
+ m = b.shape[1]
502
+
503
+ # Build an exponential matrix similar to 'zoh' method
504
+ em_upper = linalg.block_diag(np.block([a, b]) * dt, np.eye(m))
505
+ em_lower = zeros((m, n + 2 * m))
506
+ em = np.block([[em_upper], [em_lower]])
507
+
508
+ ms = linalg.expm(em)
509
+
510
+ # Get the three blocks from upper rows
511
+ ms11 = ms[:n, 0:n]
512
+ ms12 = ms[:n, n:n + m]
513
+ ms13 = ms[:n, n + m:]
514
+
515
+ ad = ms11
516
+ bd = ms12 - ms13 + ms11 @ ms13
517
+ cd = c
518
+ dd = d + c @ ms13
519
+
520
+ elif method == 'impulse':
521
+ if not np.allclose(d, 0):
522
+ raise ValueError("Impulse method is only applicable"
523
+ "to strictly proper systems")
524
+
525
+ ad = linalg.expm(a * dt)
526
+ bd = ad @ b * dt
527
+ cd = c
528
+ dd = c @ b * dt
529
+
530
+ else:
531
+ raise ValueError("Unknown transformation method '%s'" % method)
532
+
533
+ return ad, bd, cd, dd, dt
llmeval-env/lib/python3.10/site-packages/scipy/signal/_ltisys.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/scipy/signal/_max_len_seq.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author: Eric Larson
2
+ # 2014
3
+
4
+ """Tools for MLS generation"""
5
+
6
+ import numpy as np
7
+
8
+ from ._max_len_seq_inner import _max_len_seq_inner
9
+
10
+ __all__ = ['max_len_seq']
11
+
12
+
13
+ # These are definitions of linear shift register taps for use in max_len_seq()
14
+ _mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1],
15
+ 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8],
16
+ 14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14],
17
+ 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21],
18
+ 23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20],
19
+ 27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7],
20
+ 31: [28], 32: [31, 30, 10]}
21
+
22
+ def max_len_seq(nbits, state=None, length=None, taps=None):
23
+ """
24
+ Maximum length sequence (MLS) generator.
25
+
26
+ Parameters
27
+ ----------
28
+ nbits : int
29
+ Number of bits to use. Length of the resulting sequence will
30
+ be ``(2**nbits) - 1``. Note that generating long sequences
31
+ (e.g., greater than ``nbits == 16``) can take a long time.
32
+ state : array_like, optional
33
+ If array, must be of length ``nbits``, and will be cast to binary
34
+ (bool) representation. If None, a seed of ones will be used,
35
+ producing a repeatable representation. If ``state`` is all
36
+ zeros, an error is raised as this is invalid. Default: None.
37
+ length : int, optional
38
+ Number of samples to compute. If None, the entire length
39
+ ``(2**nbits) - 1`` is computed.
40
+ taps : array_like, optional
41
+ Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence).
42
+ If None, taps will be automatically selected (for up to
43
+ ``nbits == 32``).
44
+
45
+ Returns
46
+ -------
47
+ seq : array
48
+ Resulting MLS sequence of 0's and 1's.
49
+ state : array
50
+ The final state of the shift register.
51
+
52
+ Notes
53
+ -----
54
+ The algorithm for MLS generation is generically described in:
55
+
56
+ https://en.wikipedia.org/wiki/Maximum_length_sequence
57
+
58
+ The default values for taps are specifically taken from the first
59
+ option listed for each value of ``nbits`` in:
60
+
61
+ https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm
62
+
63
+ .. versionadded:: 0.15.0
64
+
65
+ Examples
66
+ --------
67
+ MLS uses binary convention:
68
+
69
+ >>> from scipy.signal import max_len_seq
70
+ >>> max_len_seq(4)[0]
71
+ array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8)
72
+
73
+ MLS has a white spectrum (except for DC):
74
+
75
+ >>> import numpy as np
76
+ >>> import matplotlib.pyplot as plt
77
+ >>> from numpy.fft import fft, ifft, fftshift, fftfreq
78
+ >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1
79
+ >>> spec = fft(seq)
80
+ >>> N = len(seq)
81
+ >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-')
82
+ >>> plt.margins(0.1, 0.1)
83
+ >>> plt.grid(True)
84
+ >>> plt.show()
85
+
86
+ Circular autocorrelation of MLS is an impulse:
87
+
88
+ >>> acorrcirc = ifft(spec * np.conj(spec)).real
89
+ >>> plt.figure()
90
+ >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-')
91
+ >>> plt.margins(0.1, 0.1)
92
+ >>> plt.grid(True)
93
+ >>> plt.show()
94
+
95
+ Linear autocorrelation of MLS is approximately an impulse:
96
+
97
+ >>> acorr = np.correlate(seq, seq, 'full')
98
+ >>> plt.figure()
99
+ >>> plt.plot(np.arange(-N+1, N), acorr, '.-')
100
+ >>> plt.margins(0.1, 0.1)
101
+ >>> plt.grid(True)
102
+ >>> plt.show()
103
+
104
+ """
105
+ taps_dtype = np.int32 if np.intp().itemsize == 4 else np.int64
106
+ if taps is None:
107
+ if nbits not in _mls_taps:
108
+ known_taps = np.array(list(_mls_taps.keys()))
109
+ raise ValueError(f'nbits must be between {known_taps.min()} and '
110
+ f'{known_taps.max()} if taps is None')
111
+ taps = np.array(_mls_taps[nbits], taps_dtype)
112
+ else:
113
+ taps = np.unique(np.array(taps, taps_dtype))[::-1]
114
+ if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1:
115
+ raise ValueError('taps must be non-empty with values between '
116
+ 'zero and nbits (inclusive)')
117
+ taps = np.array(taps) # needed for Cython and Pythran
118
+ n_max = (2**nbits) - 1
119
+ if length is None:
120
+ length = n_max
121
+ else:
122
+ length = int(length)
123
+ if length < 0:
124
+ raise ValueError('length must be greater than or equal to 0')
125
+ # We use int8 instead of bool here because NumPy arrays of bools
126
+ # don't seem to work nicely with Cython
127
+ if state is None:
128
+ state = np.ones(nbits, dtype=np.int8, order='c')
129
+ else:
130
+ # makes a copy if need be, ensuring it's 0's and 1's
131
+ state = np.array(state, dtype=bool, order='c').astype(np.int8)
132
+ if state.ndim != 1 or state.size != nbits:
133
+ raise ValueError('state must be a 1-D array of size nbits')
134
+ if np.all(state == 0):
135
+ raise ValueError('state must not be all zeros')
136
+
137
+ seq = np.empty(length, dtype=np.int8, order='c')
138
+ state = _max_len_seq_inner(taps, state, nbits, length, seq)
139
+ return seq, state
llmeval-env/lib/python3.10/site-packages/scipy/signal/_savitzky_golay.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.linalg import lstsq
3
+ from scipy._lib._util import float_factorial
4
+ from scipy.ndimage import convolve1d
5
+ from ._arraytools import axis_slice
6
+
7
+
8
+ def savgol_coeffs(window_length, polyorder, deriv=0, delta=1.0, pos=None,
9
+ use="conv"):
10
+ """Compute the coefficients for a 1-D Savitzky-Golay FIR filter.
11
+
12
+ Parameters
13
+ ----------
14
+ window_length : int
15
+ The length of the filter window (i.e., the number of coefficients).
16
+ polyorder : int
17
+ The order of the polynomial used to fit the samples.
18
+ `polyorder` must be less than `window_length`.
19
+ deriv : int, optional
20
+ The order of the derivative to compute. This must be a
21
+ nonnegative integer. The default is 0, which means to filter
22
+ the data without differentiating.
23
+ delta : float, optional
24
+ The spacing of the samples to which the filter will be applied.
25
+ This is only used if deriv > 0.
26
+ pos : int or None, optional
27
+ If pos is not None, it specifies evaluation position within the
28
+ window. The default is the middle of the window.
29
+ use : str, optional
30
+ Either 'conv' or 'dot'. This argument chooses the order of the
31
+ coefficients. The default is 'conv', which means that the
32
+ coefficients are ordered to be used in a convolution. With
33
+ use='dot', the order is reversed, so the filter is applied by
34
+ dotting the coefficients with the data set.
35
+
36
+ Returns
37
+ -------
38
+ coeffs : 1-D ndarray
39
+ The filter coefficients.
40
+
41
+ See Also
42
+ --------
43
+ savgol_filter
44
+
45
+ Notes
46
+ -----
47
+ .. versionadded:: 0.14.0
48
+
49
+ References
50
+ ----------
51
+ A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by
52
+ Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8),
53
+ pp 1627-1639.
54
+ Jianwen Luo, Kui Ying, and Jing Bai. 2005. Savitzky-Golay smoothing and
55
+ differentiation filter for even number data. Signal Process.
56
+ 85, 7 (July 2005), 1429-1434.
57
+
58
+ Examples
59
+ --------
60
+ >>> import numpy as np
61
+ >>> from scipy.signal import savgol_coeffs
62
+ >>> savgol_coeffs(5, 2)
63
+ array([-0.08571429, 0.34285714, 0.48571429, 0.34285714, -0.08571429])
64
+ >>> savgol_coeffs(5, 2, deriv=1)
65
+ array([ 2.00000000e-01, 1.00000000e-01, 2.07548111e-16, -1.00000000e-01,
66
+ -2.00000000e-01])
67
+
68
+ Note that use='dot' simply reverses the coefficients.
69
+
70
+ >>> savgol_coeffs(5, 2, pos=3)
71
+ array([ 0.25714286, 0.37142857, 0.34285714, 0.17142857, -0.14285714])
72
+ >>> savgol_coeffs(5, 2, pos=3, use='dot')
73
+ array([-0.14285714, 0.17142857, 0.34285714, 0.37142857, 0.25714286])
74
+ >>> savgol_coeffs(4, 2, pos=3, deriv=1, use='dot')
75
+ array([0.45, -0.85, -0.65, 1.05])
76
+
77
+ `x` contains data from the parabola x = t**2, sampled at
78
+ t = -1, 0, 1, 2, 3. `c` holds the coefficients that will compute the
79
+ derivative at the last position. When dotted with `x` the result should
80
+ be 6.
81
+
82
+ >>> x = np.array([1, 0, 1, 4, 9])
83
+ >>> c = savgol_coeffs(5, 2, pos=4, deriv=1, use='dot')
84
+ >>> c.dot(x)
85
+ 6.0
86
+ """
87
+
88
+ # An alternative method for finding the coefficients when deriv=0 is
89
+ # t = np.arange(window_length)
90
+ # unit = (t == pos).astype(int)
91
+ # coeffs = np.polyval(np.polyfit(t, unit, polyorder), t)
92
+ # The method implemented here is faster.
93
+
94
+ # To recreate the table of sample coefficients shown in the chapter on
95
+ # the Savitzy-Golay filter in the Numerical Recipes book, use
96
+ # window_length = nL + nR + 1
97
+ # pos = nL + 1
98
+ # c = savgol_coeffs(window_length, M, pos=pos, use='dot')
99
+
100
+ if polyorder >= window_length:
101
+ raise ValueError("polyorder must be less than window_length.")
102
+
103
+ halflen, rem = divmod(window_length, 2)
104
+
105
+ if pos is None:
106
+ if rem == 0:
107
+ pos = halflen - 0.5
108
+ else:
109
+ pos = halflen
110
+
111
+ if not (0 <= pos < window_length):
112
+ raise ValueError("pos must be nonnegative and less than "
113
+ "window_length.")
114
+
115
+ if use not in ['conv', 'dot']:
116
+ raise ValueError("`use` must be 'conv' or 'dot'")
117
+
118
+ if deriv > polyorder:
119
+ coeffs = np.zeros(window_length)
120
+ return coeffs
121
+
122
+ # Form the design matrix A. The columns of A are powers of the integers
123
+ # from -pos to window_length - pos - 1. The powers (i.e., rows) range
124
+ # from 0 to polyorder. (That is, A is a vandermonde matrix, but not
125
+ # necessarily square.)
126
+ x = np.arange(-pos, window_length - pos, dtype=float)
127
+
128
+ if use == "conv":
129
+ # Reverse so that result can be used in a convolution.
130
+ x = x[::-1]
131
+
132
+ order = np.arange(polyorder + 1).reshape(-1, 1)
133
+ A = x ** order
134
+
135
+ # y determines which order derivative is returned.
136
+ y = np.zeros(polyorder + 1)
137
+ # The coefficient assigned to y[deriv] scales the result to take into
138
+ # account the order of the derivative and the sample spacing.
139
+ y[deriv] = float_factorial(deriv) / (delta ** deriv)
140
+
141
+ # Find the least-squares solution of A*c = y
142
+ coeffs, _, _, _ = lstsq(A, y)
143
+
144
+ return coeffs
145
+
146
+
147
+ def _polyder(p, m):
148
+ """Differentiate polynomials represented with coefficients.
149
+
150
+ p must be a 1-D or 2-D array. In the 2-D case, each column gives
151
+ the coefficients of a polynomial; the first row holds the coefficients
152
+ associated with the highest power. m must be a nonnegative integer.
153
+ (numpy.polyder doesn't handle the 2-D case.)
154
+ """
155
+
156
+ if m == 0:
157
+ result = p
158
+ else:
159
+ n = len(p)
160
+ if n <= m:
161
+ result = np.zeros_like(p[:1, ...])
162
+ else:
163
+ dp = p[:-m].copy()
164
+ for k in range(m):
165
+ rng = np.arange(n - k - 1, m - k - 1, -1)
166
+ dp *= rng.reshape((n - m,) + (1,) * (p.ndim - 1))
167
+ result = dp
168
+ return result
169
+
170
+
171
+ def _fit_edge(x, window_start, window_stop, interp_start, interp_stop,
172
+ axis, polyorder, deriv, delta, y):
173
+ """
174
+ Given an N-d array `x` and the specification of a slice of `x` from
175
+ `window_start` to `window_stop` along `axis`, create an interpolating
176
+ polynomial of each 1-D slice, and evaluate that polynomial in the slice
177
+ from `interp_start` to `interp_stop`. Put the result into the
178
+ corresponding slice of `y`.
179
+ """
180
+
181
+ # Get the edge into a (window_length, -1) array.
182
+ x_edge = axis_slice(x, start=window_start, stop=window_stop, axis=axis)
183
+ if axis == 0 or axis == -x.ndim:
184
+ xx_edge = x_edge
185
+ swapped = False
186
+ else:
187
+ xx_edge = x_edge.swapaxes(axis, 0)
188
+ swapped = True
189
+ xx_edge = xx_edge.reshape(xx_edge.shape[0], -1)
190
+
191
+ # Fit the edges. poly_coeffs has shape (polyorder + 1, -1),
192
+ # where '-1' is the same as in xx_edge.
193
+ poly_coeffs = np.polyfit(np.arange(0, window_stop - window_start),
194
+ xx_edge, polyorder)
195
+
196
+ if deriv > 0:
197
+ poly_coeffs = _polyder(poly_coeffs, deriv)
198
+
199
+ # Compute the interpolated values for the edge.
200
+ i = np.arange(interp_start - window_start, interp_stop - window_start)
201
+ values = np.polyval(poly_coeffs, i.reshape(-1, 1)) / (delta ** deriv)
202
+
203
+ # Now put the values into the appropriate slice of y.
204
+ # First reshape values to match y.
205
+ shp = list(y.shape)
206
+ shp[0], shp[axis] = shp[axis], shp[0]
207
+ values = values.reshape(interp_stop - interp_start, *shp[1:])
208
+ if swapped:
209
+ values = values.swapaxes(0, axis)
210
+ # Get a view of the data to be replaced by values.
211
+ y_edge = axis_slice(y, start=interp_start, stop=interp_stop, axis=axis)
212
+ y_edge[...] = values
213
+
214
+
215
+ def _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y):
216
+ """
217
+ Use polynomial interpolation of x at the low and high ends of the axis
218
+ to fill in the halflen values in y.
219
+
220
+ This function just calls _fit_edge twice, once for each end of the axis.
221
+ """
222
+ halflen = window_length // 2
223
+ _fit_edge(x, 0, window_length, 0, halflen, axis,
224
+ polyorder, deriv, delta, y)
225
+ n = x.shape[axis]
226
+ _fit_edge(x, n - window_length, n, n - halflen, n, axis,
227
+ polyorder, deriv, delta, y)
228
+
229
+
230
+ def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0,
231
+ axis=-1, mode='interp', cval=0.0):
232
+ """ Apply a Savitzky-Golay filter to an array.
233
+
234
+ This is a 1-D filter. If `x` has dimension greater than 1, `axis`
235
+ determines the axis along which the filter is applied.
236
+
237
+ Parameters
238
+ ----------
239
+ x : array_like
240
+ The data to be filtered. If `x` is not a single or double precision
241
+ floating point array, it will be converted to type ``numpy.float64``
242
+ before filtering.
243
+ window_length : int
244
+ The length of the filter window (i.e., the number of coefficients).
245
+ If `mode` is 'interp', `window_length` must be less than or equal
246
+ to the size of `x`.
247
+ polyorder : int
248
+ The order of the polynomial used to fit the samples.
249
+ `polyorder` must be less than `window_length`.
250
+ deriv : int, optional
251
+ The order of the derivative to compute. This must be a
252
+ nonnegative integer. The default is 0, which means to filter
253
+ the data without differentiating.
254
+ delta : float, optional
255
+ The spacing of the samples to which the filter will be applied.
256
+ This is only used if deriv > 0. Default is 1.0.
257
+ axis : int, optional
258
+ The axis of the array `x` along which the filter is to be applied.
259
+ Default is -1.
260
+ mode : str, optional
261
+ Must be 'mirror', 'constant', 'nearest', 'wrap' or 'interp'. This
262
+ determines the type of extension to use for the padded signal to
263
+ which the filter is applied. When `mode` is 'constant', the padding
264
+ value is given by `cval`. See the Notes for more details on 'mirror',
265
+ 'constant', 'wrap', and 'nearest'.
266
+ When the 'interp' mode is selected (the default), no extension
267
+ is used. Instead, a degree `polyorder` polynomial is fit to the
268
+ last `window_length` values of the edges, and this polynomial is
269
+ used to evaluate the last `window_length // 2` output values.
270
+ cval : scalar, optional
271
+ Value to fill past the edges of the input if `mode` is 'constant'.
272
+ Default is 0.0.
273
+
274
+ Returns
275
+ -------
276
+ y : ndarray, same shape as `x`
277
+ The filtered data.
278
+
279
+ See Also
280
+ --------
281
+ savgol_coeffs
282
+
283
+ Notes
284
+ -----
285
+ Details on the `mode` options:
286
+
287
+ 'mirror':
288
+ Repeats the values at the edges in reverse order. The value
289
+ closest to the edge is not included.
290
+ 'nearest':
291
+ The extension contains the nearest input value.
292
+ 'constant':
293
+ The extension contains the value given by the `cval` argument.
294
+ 'wrap':
295
+ The extension contains the values from the other end of the array.
296
+
297
+ For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and
298
+ `window_length` is 7, the following shows the extended data for
299
+ the various `mode` options (assuming `cval` is 0)::
300
+
301
+ mode | Ext | Input | Ext
302
+ -----------+---------+------------------------+---------
303
+ 'mirror' | 4 3 2 | 1 2 3 4 5 6 7 8 | 7 6 5
304
+ 'nearest' | 1 1 1 | 1 2 3 4 5 6 7 8 | 8 8 8
305
+ 'constant' | 0 0 0 | 1 2 3 4 5 6 7 8 | 0 0 0
306
+ 'wrap' | 6 7 8 | 1 2 3 4 5 6 7 8 | 1 2 3
307
+
308
+ .. versionadded:: 0.14.0
309
+
310
+ Examples
311
+ --------
312
+ >>> import numpy as np
313
+ >>> from scipy.signal import savgol_filter
314
+ >>> np.set_printoptions(precision=2) # For compact display.
315
+ >>> x = np.array([2, 2, 5, 2, 1, 0, 1, 4, 9])
316
+
317
+ Filter with a window length of 5 and a degree 2 polynomial. Use
318
+ the defaults for all other parameters.
319
+
320
+ >>> savgol_filter(x, 5, 2)
321
+ array([1.66, 3.17, 3.54, 2.86, 0.66, 0.17, 1. , 4. , 9. ])
322
+
323
+ Note that the last five values in x are samples of a parabola, so
324
+ when mode='interp' (the default) is used with polyorder=2, the last
325
+ three values are unchanged. Compare that to, for example,
326
+ `mode='nearest'`:
327
+
328
+ >>> savgol_filter(x, 5, 2, mode='nearest')
329
+ array([1.74, 3.03, 3.54, 2.86, 0.66, 0.17, 1. , 4.6 , 7.97])
330
+
331
+ """
332
+ if mode not in ["mirror", "constant", "nearest", "interp", "wrap"]:
333
+ raise ValueError("mode must be 'mirror', 'constant', 'nearest' "
334
+ "'wrap' or 'interp'.")
335
+
336
+ x = np.asarray(x)
337
+ # Ensure that x is either single or double precision floating point.
338
+ if x.dtype != np.float64 and x.dtype != np.float32:
339
+ x = x.astype(np.float64)
340
+
341
+ coeffs = savgol_coeffs(window_length, polyorder, deriv=deriv, delta=delta)
342
+
343
+ if mode == "interp":
344
+ if window_length > x.shape[axis]:
345
+ raise ValueError("If mode is 'interp', window_length must be less "
346
+ "than or equal to the size of x.")
347
+
348
+ # Do not pad. Instead, for the elements within `window_length // 2`
349
+ # of the ends of the sequence, use the polynomial that is fitted to
350
+ # the last `window_length` elements.
351
+ y = convolve1d(x, coeffs, axis=axis, mode="constant")
352
+ _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y)
353
+ else:
354
+ # Any mode other than 'interp' is passed on to ndimage.convolve1d.
355
+ y = convolve1d(x, coeffs, axis=axis, mode=mode, cval=cval)
356
+
357
+ return y
llmeval-env/lib/python3.10/site-packages/scipy/signal/_short_time_fft.py ADDED
@@ -0,0 +1,1676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of an FFT-based Short-time Fourier Transform. """
2
+
3
+ # Implementation Notes for this file (as of 2023-07)
4
+ # --------------------------------------------------
5
+ # * MyPy version 1.1.1 does not seem to support decorated property methods
6
+ # properly. Hence, applying ``@property`` to methods decorated with `@cache``
7
+ # (as tried with the ``lower_border_end`` method) causes a mypy error when
8
+ # accessing it as an index (e.g., ``SFT.lower_border_end[0]``).
9
+ # * Since the method `stft` and `istft` have identical names as the legacy
10
+ # functions in the signal module, referencing them as HTML link in the
11
+ # docstrings has to be done by an explicit `~ShortTimeFFT.stft` instead of an
12
+ # ambiguous `stft` (The ``~`` hides the class / module name).
13
+ # * The HTML documentation currently renders each method/property on a separate
14
+ # page without reference to the parent class. Thus, a link to `ShortTimeFFT`
15
+ # was added to the "See Also" section of each method/property. These links
16
+ # can be removed, when SciPy updates ``pydata-sphinx-theme`` to >= 0.13.3
17
+ # (currently 0.9). Consult Issue 18512 and PR 16660 for further details.
18
+ #
19
+
20
+ # Provides typing union operator ``|`` in Python 3.9:
21
+ from __future__ import annotations
22
+ # Linter does not allow to import ``Generator`` from ``typing`` module:
23
+ from collections.abc import Generator
24
+ from functools import cache, lru_cache, partial
25
+ from typing import Callable, get_args, Literal
26
+
27
+ import numpy as np
28
+
29
+ import scipy.fft as fft_lib
30
+ from scipy.signal import detrend
31
+ from scipy.signal.windows import get_window
32
+
33
+ __all__ = ['ShortTimeFFT']
34
+
35
+
36
+ #: Allowed values for parameter `padding` of method `ShortTimeFFT.stft()`:
37
+ PAD_TYPE = Literal['zeros', 'edge', 'even', 'odd']
38
+
39
+ #: Allowed values for property `ShortTimeFFT.fft_mode`:
40
+ FFT_MODE_TYPE = Literal['twosided', 'centered', 'onesided', 'onesided2X']
41
+
42
+
43
+ def _calc_dual_canonical_window(win: np.ndarray, hop: int) -> np.ndarray:
44
+ """Calculate canonical dual window for 1d window `win` and a time step
45
+ of `hop` samples.
46
+
47
+ A ``ValueError`` is raised, if the inversion fails.
48
+
49
+ This is a separate function not a method, since it is also used in the
50
+ class method ``ShortTimeFFT.from_dual()``.
51
+ """
52
+ if hop > len(win):
53
+ raise ValueError(f"{hop=} is larger than window length of {len(win)}" +
54
+ " => STFT not invertible!")
55
+ if issubclass(win.dtype.type, np.integer):
56
+ raise ValueError("Parameter 'win' cannot be of integer type, but " +
57
+ f"{win.dtype=} => STFT not invertible!")
58
+ # The calculation of `relative_resolution` does not work for ints.
59
+ # Furthermore, `win / DD` casts the integers away, thus an implicit
60
+ # cast is avoided, which can always cause confusion when using 32-Bit
61
+ # floats.
62
+
63
+ w2 = win.real**2 + win.imag**2 # win*win.conj() does not ensure w2 is real
64
+ DD = w2.copy()
65
+ for k_ in range(hop, len(win), hop):
66
+ DD[k_:] += w2[:-k_]
67
+ DD[:-k_] += w2[k_:]
68
+
69
+ # check DD > 0:
70
+ relative_resolution = np.finfo(win.dtype).resolution * max(DD)
71
+ if not np.all(DD >= relative_resolution):
72
+ raise ValueError("Short-time Fourier Transform not invertible!")
73
+
74
+ return win / DD
75
+
76
+
77
+ # noinspection PyShadowingNames
78
+ class ShortTimeFFT:
79
+ r"""Provide a parametrized discrete Short-time Fourier transform (stft)
80
+ and its inverse (istft).
81
+
82
+ .. currentmodule:: scipy.signal.ShortTimeFFT
83
+
84
+ The `~ShortTimeFFT.stft` calculates sequential FFTs by sliding a
85
+ window (`win`) over an input signal by `hop` increments. It can be used to
86
+ quantify the change of the spectrum over time.
87
+
88
+ The `~ShortTimeFFT.stft` is represented by a complex-valued matrix S[q,p]
89
+ where the p-th column represents an FFT with the window centered at the
90
+ time t[p] = p * `delta_t` = p * `hop` * `T` where `T` is the sampling
91
+ interval of the input signal. The q-th row represents the values at the
92
+ frequency f[q] = q * `delta_f` with `delta_f` = 1 / (`mfft` * `T`) being
93
+ the bin width of the FFT.
94
+
95
+ The inverse STFT `~ShortTimeFFT.istft` is calculated by reversing the steps
96
+ of the STFT: Take the IFFT of the p-th slice of S[q,p] and multiply the
97
+ result with the so-called dual window (see `dual_win`). Shift the result by
98
+ p * `delta_t` and add the result to previous shifted results to reconstruct
99
+ the signal. If only the dual window is known and the STFT is invertible,
100
+ `from_dual` can be used to instantiate this class.
101
+
102
+ Due to the convention of time t = 0 being at the first sample of the input
103
+ signal, the STFT values typically have negative time slots. Hence,
104
+ negative indexes like `p_min` or `k_min` do not indicate counting
105
+ backwards from an array's end like in standard Python indexing but being
106
+ left of t = 0.
107
+
108
+ More detailed information can be found in the :ref:`tutorial_stft` section
109
+ of the :ref:`user_guide`.
110
+
111
+ Note that all parameters of the initializer, except `scale_to` (which uses
112
+ `scaling`) have identical named attributes.
113
+
114
+ Parameters
115
+ ----------
116
+ win : np.ndarray
117
+ The window must be a real- or complex-valued 1d array.
118
+ hop : int
119
+ The increment in samples, by which the window is shifted in each step.
120
+ fs : float
121
+ Sampling frequency of input signal and window. Its relation to the
122
+ sampling interval `T` is ``T = 1 / fs``.
123
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
124
+ Mode of FFT to be used (default 'onesided').
125
+ See property `fft_mode` for details.
126
+ mfft: int | None
127
+ Length of the FFT used, if a zero padded FFT is desired.
128
+ If ``None`` (default), the length of the window `win` is used.
129
+ dual_win : np.ndarray | None
130
+ The dual window of `win`. If set to ``None``, it is calculated if
131
+ needed.
132
+ scale_to : 'magnitude', 'psd' | None
133
+ If not ``None`` (default) the window function is scaled, so each STFT
134
+ column represents either a 'magnitude' or a power spectral density
135
+ ('psd') spectrum. This parameter sets the property `scaling` to the
136
+ same value. See method `scale_to` for details.
137
+ phase_shift : int | None
138
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
139
+ frequency `f`. The default value 0 ensures that there is no phase shift
140
+ on the zeroth slice (in which t=0 is centered). See property
141
+ `phase_shift` for more details.
142
+
143
+ Examples
144
+ --------
145
+ The following example shows the magnitude of the STFT of a sine with
146
+ varying frequency :math:`f_i(t)` (marked by a red dashed line in the plot):
147
+
148
+ >>> import numpy as np
149
+ >>> import matplotlib.pyplot as plt
150
+ >>> from scipy.signal import ShortTimeFFT
151
+ >>> from scipy.signal.windows import gaussian
152
+ ...
153
+ >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal
154
+ >>> t_x = np.arange(N) * T_x # time indexes for signal
155
+ >>> f_i = 1 * np.arctan((t_x - t_x[N // 2]) / 2) + 5 # varying frequency
156
+ >>> x = np.sin(2*np.pi*np.cumsum(f_i)*T_x) # the signal
157
+
158
+ The utilized Gaussian window is 50 samples or 2.5 s long. The parameter
159
+ ``mfft=200`` in `ShortTimeFFT` causes the spectrum to be oversampled
160
+ by a factor of 4:
161
+
162
+ >>> g_std = 8 # standard deviation for Gaussian window in samples
163
+ >>> w = gaussian(50, std=g_std, sym=True) # symmetric Gaussian window
164
+ >>> SFT = ShortTimeFFT(w, hop=10, fs=1/T_x, mfft=200, scale_to='magnitude')
165
+ >>> Sx = SFT.stft(x) # perform the STFT
166
+
167
+ In the plot, the time extent of the signal `x` is marked by vertical dashed
168
+ lines. Note that the SFT produces values outside the time range of `x`. The
169
+ shaded areas on the left and the right indicate border effects caused
170
+ by the window slices in that area not fully being inside time range of
171
+ `x`:
172
+
173
+ >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit
174
+ >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot
175
+ >>> ax1.set_title(rf"STFT ({SFT.m_num*SFT.T:g}$\,s$ Gaussian window, " +
176
+ ... rf"$\sigma_t={g_std*SFT.T}\,$s)")
177
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " +
178
+ ... rf"$\Delta t = {SFT.delta_t:g}\,$s)",
179
+ ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " +
180
+ ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)",
181
+ ... xlim=(t_lo, t_hi))
182
+ ...
183
+ >>> im1 = ax1.imshow(abs(Sx), origin='lower', aspect='auto',
184
+ ... extent=SFT.extent(N), cmap='viridis')
185
+ >>> ax1.plot(t_x, f_i, 'r--', alpha=.5, label='$f_i(t)$')
186
+ >>> fig1.colorbar(im1, label="Magnitude $|S_x(t, f)|$")
187
+ ...
188
+ >>> # Shade areas where window slices stick out to the side:
189
+ >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T),
190
+ ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]:
191
+ ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.2)
192
+ >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line:
193
+ ... ax1.axvline(t_, color='y', linestyle='--', alpha=0.5)
194
+ >>> ax1.legend()
195
+ >>> fig1.tight_layout()
196
+ >>> plt.show()
197
+
198
+ Reconstructing the signal with the `~ShortTimeFFT.istft` is
199
+ straightforward, but note that the length of `x1` should be specified,
200
+ since the SFT length increases in `hop` steps:
201
+
202
+ >>> SFT.invertible # check if invertible
203
+ True
204
+ >>> x1 = SFT.istft(Sx, k1=N)
205
+ >>> np.allclose(x, x1)
206
+ True
207
+
208
+ It is possible to calculate the SFT of signal parts:
209
+
210
+ >>> p_q = SFT.nearest_k_p(N // 2)
211
+ >>> Sx0 = SFT.stft(x[:p_q])
212
+ >>> Sx1 = SFT.stft(x[p_q:])
213
+
214
+ When assembling sequential STFT parts together, the overlap needs to be
215
+ considered:
216
+
217
+ >>> p0_ub = SFT.upper_border_begin(p_q)[1] - SFT.p_min
218
+ >>> p1_le = SFT.lower_border_end[1] - SFT.p_min
219
+ >>> Sx01 = np.hstack((Sx0[:, :p0_ub],
220
+ ... Sx0[:, p0_ub:] + Sx1[:, :p1_le],
221
+ ... Sx1[:, p1_le:]))
222
+ >>> np.allclose(Sx01, Sx) # Compare with SFT of complete signal
223
+ True
224
+
225
+ It is also possible to calculate the `itsft` for signal parts:
226
+
227
+ >>> y_p = SFT.istft(Sx, N//3, N//2)
228
+ >>> np.allclose(y_p, x[N//3:N//2])
229
+ True
230
+
231
+ """
232
+ # immutable attributes (only have getters but no setters):
233
+ _win: np.ndarray # window
234
+ _dual_win: np.ndarray | None = None # canonical dual window
235
+ _hop: int # Step of STFT in number of samples
236
+
237
+ # mutable attributes:
238
+ _fs: float # sampling frequency of input signal and window
239
+ _fft_mode: FFT_MODE_TYPE = 'onesided' # Mode of FFT to use
240
+ _mfft: int # length of FFT used - defaults to len(win)
241
+ _scaling: Literal['magnitude', 'psd'] | None = None # Scaling of _win
242
+ _phase_shift: int | None # amount to shift phase of FFT in samples
243
+
244
+ # attributes for caching calculated values:
245
+ _fac_mag: float | None = None
246
+ _fac_psd: float | None = None
247
+ _lower_border_end: tuple[int, int] | None = None
248
+
249
+ def __init__(self, win: np.ndarray, hop: int, fs: float, *,
250
+ fft_mode: FFT_MODE_TYPE = 'onesided',
251
+ mfft: int | None = None,
252
+ dual_win: np.ndarray | None = None,
253
+ scale_to: Literal['magnitude', 'psd'] | None = None,
254
+ phase_shift: int | None = 0):
255
+ if not (win.ndim == 1 and win.size > 0):
256
+ raise ValueError(f"Parameter win must be 1d, but {win.shape=}!")
257
+ if not all(np.isfinite(win)):
258
+ raise ValueError("Parameter win must have finite entries!")
259
+ if not (hop >= 1 and isinstance(hop, int)):
260
+ raise ValueError(f"Parameter {hop=} is not an integer >= 1!")
261
+ self._win, self._hop, self.fs = win, hop, fs
262
+
263
+ self.mfft = len(win) if mfft is None else mfft
264
+
265
+ if dual_win is not None:
266
+ if dual_win.shape != win.shape:
267
+ raise ValueError(f"{dual_win.shape=} must equal {win.shape=}!")
268
+ if not all(np.isfinite(dual_win)):
269
+ raise ValueError("Parameter dual_win must be a finite array!")
270
+ self._dual_win = dual_win # needs to be set before scaling
271
+
272
+ if scale_to is not None: # needs to be set before fft_mode
273
+ self.scale_to(scale_to)
274
+
275
+ self.fft_mode, self.phase_shift = fft_mode, phase_shift
276
+
277
+ @classmethod
278
+ def from_dual(cls, dual_win: np.ndarray, hop: int, fs: float, *,
279
+ fft_mode: FFT_MODE_TYPE = 'onesided',
280
+ mfft: int | None = None,
281
+ scale_to: Literal['magnitude', 'psd'] | None = None,
282
+ phase_shift: int | None = 0):
283
+ r"""Instantiate a `ShortTimeFFT` by only providing a dual window.
284
+
285
+ If an STFT is invertible, it is possible to calculate the window `win`
286
+ from a given dual window `dual_win`. All other parameters have the
287
+ same meaning as in the initializer of `ShortTimeFFT`.
288
+
289
+ As explained in the :ref:`tutorial_stft` section of the
290
+ :ref:`user_guide`, an invertible STFT can be interpreted as series
291
+ expansion of time-shifted and frequency modulated dual windows. E.g.,
292
+ the series coefficient S[q,p] belongs to the term, which shifted
293
+ `dual_win` by p * `delta_t` and multiplied it by
294
+ exp( 2 * j * pi * t * q * `delta_f`).
295
+
296
+
297
+ Examples
298
+ --------
299
+ The following example discusses decomposing a signal into time- and
300
+ frequency-shifted Gaussians. A Gaussian with standard deviation of
301
+ one made up of 51 samples will be used:
302
+
303
+ >>> import numpy as np
304
+ >>> import matplotlib.pyplot as plt
305
+ >>> from scipy.signal import ShortTimeFFT
306
+ >>> from scipy.signal.windows import gaussian
307
+ ...
308
+ >>> T, N = 0.1, 51
309
+ >>> d_win = gaussian(N, std=1/T, sym=True) # symmetric Gaussian window
310
+ >>> t = T * (np.arange(N) - N//2)
311
+ ...
312
+ >>> fg1, ax1 = plt.subplots()
313
+ >>> ax1.set_title(r"Dual Window: Gaussian with $\sigma_t=1$")
314
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)",
315
+ ... xlim=(t[0], t[-1]), ylim=(0, 1.1*max(d_win)))
316
+ >>> ax1.plot(t, d_win, 'C0-')
317
+
318
+ The following plot with the overlap of 41, 11 and 2 samples show how
319
+ the `hop` interval affects the shape of the window `win`:
320
+
321
+ >>> fig2, axx = plt.subplots(3, 1, sharex='all')
322
+ ...
323
+ >>> axx[0].set_title(r"Windows for hop$\in\{10, 40, 49\}$")
324
+ >>> for c_, h_ in enumerate([10, 40, 49]):
325
+ ... SFT = ShortTimeFFT.from_dual(d_win, h_, 1/T)
326
+ ... axx[c_].plot(t + h_ * T, SFT.win, 'k--', alpha=.3, label=None)
327
+ ... axx[c_].plot(t - h_ * T, SFT.win, 'k:', alpha=.3, label=None)
328
+ ... axx[c_].plot(t, SFT.win, f'C{c_+1}',
329
+ ... label=r"$\Delta t=%0.1f\,$s" % SFT.delta_t)
330
+ ... axx[c_].set_ylim(0, 1.1*max(SFT.win))
331
+ ... axx[c_].legend(loc='center')
332
+ >>> axx[-1].set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)",
333
+ ... xlim=(t[0], t[-1]))
334
+ >>> plt.show()
335
+
336
+ Beside the window `win` centered at t = 0 the previous (t = -`delta_t`)
337
+ and following window (t = `delta_t`) are depicted. It can be seen that
338
+ for small `hop` intervals, the window is compact and smooth, having a
339
+ good time-frequency concentration in the STFT. For the large `hop`
340
+ interval of 4.9 s, the window has small values around t = 0, which are
341
+ not covered by the overlap of the adjacent windows, which could lead to
342
+ numeric inaccuracies. Furthermore, the peaky shape at the beginning and
343
+ the end of the window points to a higher bandwidth, resulting in a
344
+ poorer time-frequency resolution of the STFT.
345
+ Hence, the choice of the `hop` interval will be a compromise between
346
+ a time-frequency resolution and memory requirements demanded by small
347
+ `hop` sizes.
348
+
349
+ See Also
350
+ --------
351
+ from_window: Create instance by wrapping `get_window`.
352
+ ShortTimeFFT: Create instance using standard initializer.
353
+ """
354
+ win = _calc_dual_canonical_window(dual_win, hop)
355
+ return cls(win=win, hop=hop, fs=fs, fft_mode=fft_mode, mfft=mfft,
356
+ dual_win=dual_win, scale_to=scale_to,
357
+ phase_shift=phase_shift)
358
+
359
+ @classmethod
360
+ def from_window(cls, win_param: str | tuple | float,
361
+ fs: float, nperseg: int, noverlap: int, *,
362
+ symmetric_win: bool = False,
363
+ fft_mode: FFT_MODE_TYPE = 'onesided',
364
+ mfft: int | None = None,
365
+ scale_to: Literal['magnitude', 'psd'] | None = None,
366
+ phase_shift: int | None = 0):
367
+ """Instantiate `ShortTimeFFT` by using `get_window`.
368
+
369
+ The method `get_window` is used to create a window of length
370
+ `nperseg`. The parameter names `noverlap`, and `nperseg` are used here,
371
+ since they more inline with other classical STFT libraries.
372
+
373
+ Parameters
374
+ ----------
375
+ win_param: Union[str, tuple, float],
376
+ Parameters passed to `get_window`. For windows with no parameters,
377
+ it may be a string (e.g., ``'hann'``), for parametrized windows a
378
+ tuple, (e.g., ``('gaussian', 2.)``) or a single float specifying
379
+ the shape parameter of a kaiser window (i.e. ``4.`` and
380
+ ``('kaiser', 4.)`` are equal. See `get_window` for more details.
381
+ fs : float
382
+ Sampling frequency of input signal. Its relation to the
383
+ sampling interval `T` is ``T = 1 / fs``.
384
+ nperseg: int
385
+ Window length in samples, which corresponds to the `m_num`.
386
+ noverlap: int
387
+ Window overlap in samples. It relates to the `hop` increment by
388
+ ``hop = npsereg - noverlap``.
389
+ symmetric_win: bool
390
+ If ``True`` then a symmetric window is generated, else a periodic
391
+ window is generated (default). Though symmetric windows seem for
392
+ most applications to be more sensible, the default of a periodic
393
+ windows was chosen to correspond to the default of `get_window`.
394
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
395
+ Mode of FFT to be used (default 'onesided').
396
+ See property `fft_mode` for details.
397
+ mfft: int | None
398
+ Length of the FFT used, if a zero padded FFT is desired.
399
+ If ``None`` (default), the length of the window `win` is used.
400
+ scale_to : 'magnitude', 'psd' | None
401
+ If not ``None`` (default) the window function is scaled, so each
402
+ STFT column represents either a 'magnitude' or a power spectral
403
+ density ('psd') spectrum. This parameter sets the property
404
+ `scaling` to the same value. See method `scale_to` for details.
405
+ phase_shift : int | None
406
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
407
+ frequency `f`. The default value 0 ensures that there is no phase
408
+ shift on the zeroth slice (in which t=0 is centered). See property
409
+ `phase_shift` for more details.
410
+
411
+ Examples
412
+ --------
413
+ The following instances ``SFT0`` and ``SFT1`` are equivalent:
414
+
415
+ >>> from scipy.signal import ShortTimeFFT, get_window
416
+ >>> nperseg = 9 # window length
417
+ >>> w = get_window(('gaussian', 2.), nperseg)
418
+ >>> fs = 128 # sampling frequency
419
+ >>> hop = 3 # increment of STFT time slice
420
+ >>> SFT0 = ShortTimeFFT(w, hop, fs=fs)
421
+ >>> SFT1 = ShortTimeFFT.from_window(('gaussian', 2.), fs, nperseg,
422
+ ... noverlap=nperseg-hop)
423
+
424
+ See Also
425
+ --------
426
+ scipy.signal.get_window: Return a window of a given length and type.
427
+ from_dual: Create instance using dual window.
428
+ ShortTimeFFT: Create instance using standard initializer.
429
+ """
430
+ win = get_window(win_param, nperseg, fftbins=not symmetric_win)
431
+ return cls(win, hop=nperseg-noverlap, fs=fs, fft_mode=fft_mode,
432
+ mfft=mfft, scale_to=scale_to, phase_shift=phase_shift)
433
+
434
+ @property
435
+ def win(self) -> np.ndarray:
436
+ """Window function as real- or complex-valued 1d array.
437
+
438
+ This attribute is read only, since `dual_win` depends on it.
439
+
440
+ See Also
441
+ --------
442
+ dual_win: Canonical dual window.
443
+ m_num: Number of samples in window `win`.
444
+ m_num_mid: Center index of window `win`.
445
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
446
+ hop: ime increment in signal samples for sliding window.
447
+ win: Window function as real- or complex-valued 1d array.
448
+ ShortTimeFFT: Class this property belongs to.
449
+ """
450
+ return self._win
451
+
452
+ @property
453
+ def hop(self) -> int:
454
+ """Time increment in signal samples for sliding window.
455
+
456
+ This attribute is read only, since `dual_win` depends on it.
457
+
458
+ See Also
459
+ --------
460
+ delta_t: Time increment of STFT (``hop*T``)
461
+ m_num: Number of samples in window `win`.
462
+ m_num_mid: Center index of window `win`.
463
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
464
+ T: Sampling interval of input signal and of the window.
465
+ win: Window function as real- or complex-valued 1d array.
466
+ ShortTimeFFT: Class this property belongs to.
467
+ """
468
+ return self._hop
469
+
470
+ @property
471
+ def T(self) -> float:
472
+ """Sampling interval of input signal and of the window.
473
+
474
+ A ``ValueError`` is raised if it is set to a non-positive value.
475
+
476
+ See Also
477
+ --------
478
+ delta_t: Time increment of STFT (``hop*T``)
479
+ hop: Time increment in signal samples for sliding window.
480
+ fs: Sampling frequency (being ``1/T``)
481
+ t: Times of STFT for an input signal with `n` samples.
482
+ ShortTimeFFT: Class this property belongs to.
483
+ """
484
+ return 1 / self._fs
485
+
486
+ @T.setter
487
+ def T(self, v: float):
488
+ """Sampling interval of input signal and of the window.
489
+
490
+ A ``ValueError`` is raised if it is set to a non-positive value.
491
+ """
492
+ if not (v > 0):
493
+ raise ValueError(f"Sampling interval T={v} must be positive!")
494
+ self._fs = 1 / v
495
+
496
+ @property
497
+ def fs(self) -> float:
498
+ """Sampling frequency of input signal and of the window.
499
+
500
+ The sampling frequency is the inverse of the sampling interval `T`.
501
+ A ``ValueError`` is raised if it is set to a non-positive value.
502
+
503
+ See Also
504
+ --------
505
+ delta_t: Time increment of STFT (``hop*T``)
506
+ hop: Time increment in signal samples for sliding window.
507
+ T: Sampling interval of input signal and of the window (``1/fs``).
508
+ ShortTimeFFT: Class this property belongs to.
509
+ """
510
+ return self._fs
511
+
512
+ @fs.setter
513
+ def fs(self, v: float):
514
+ """Sampling frequency of input signal and of the window.
515
+
516
+ The sampling frequency is the inverse of the sampling interval `T`.
517
+ A ``ValueError`` is raised if it is set to a non-positive value.
518
+ """
519
+ if not (v > 0):
520
+ raise ValueError(f"Sampling frequency fs={v} must be positive!")
521
+ self._fs = v
522
+
523
+ @property
524
+ def fft_mode(self) -> FFT_MODE_TYPE:
525
+ """Mode of utilized FFT ('twosided', 'centered', 'onesided' or
526
+ 'onesided2X').
527
+
528
+ It can have the following values:
529
+
530
+ 'twosided':
531
+ Two-sided FFT, where values for the negative frequencies are in
532
+ upper half of the array. Corresponds to :func:`~scipy.fft.fft()`.
533
+ 'centered':
534
+ Two-sided FFT with the values being ordered along monotonically
535
+ increasing frequencies. Corresponds to applying
536
+ :func:`~scipy.fft.fftshift()` to :func:`~scipy.fft.fft()`.
537
+ 'onesided':
538
+ Calculates only values for non-negative frequency values.
539
+ Corresponds to :func:`~scipy.fft.rfft()`.
540
+ 'onesided2X':
541
+ Like `onesided`, but the non-zero frequencies are doubled if
542
+ `scaling` is set to 'magnitude' or multiplied by ``sqrt(2)`` if
543
+ set to 'psd'. If `scaling` is ``None``, setting `fft_mode` to
544
+ `onesided2X` is not allowed.
545
+ If the FFT length `mfft` is even, the last FFT value is not paired,
546
+ and thus it is not scaled.
547
+
548
+ Note that `onesided` and `onesided2X` do not work for complex-valued signals or
549
+ complex-valued windows. Furthermore, the frequency values can be obtained by
550
+ reading the `f` property, and the number of samples by accessing the `f_pts`
551
+ property.
552
+
553
+ See Also
554
+ --------
555
+ delta_f: Width of the frequency bins of the STFT.
556
+ f: Frequencies values of the STFT.
557
+ f_pts: Width of the frequency bins of the STFT.
558
+ onesided_fft: True if a one-sided FFT is used.
559
+ scaling: Normalization applied to the window function
560
+ ShortTimeFFT: Class this property belongs to.
561
+ """
562
+ return self._fft_mode
563
+
564
+ @fft_mode.setter
565
+ def fft_mode(self, t: FFT_MODE_TYPE):
566
+ """Set mode of FFT.
567
+
568
+ Allowed values are 'twosided', 'centered', 'onesided', 'onesided2X'.
569
+ See the property `fft_mode` for more details.
570
+ """
571
+ if t not in (fft_mode_types := get_args(FFT_MODE_TYPE)):
572
+ raise ValueError(f"fft_mode='{t}' not in {fft_mode_types}!")
573
+
574
+ if t in {'onesided', 'onesided2X'} and np.iscomplexobj(self.win):
575
+ raise ValueError(f"One-sided spectra, i.e., fft_mode='{t}', " +
576
+ "are not allowed for complex-valued windows!")
577
+
578
+ if t == 'onesided2X' and self.scaling is None:
579
+ raise ValueError(f"For scaling is None, fft_mode='{t}' is invalid!"
580
+ "Do scale_to('psd') or scale_to('magnitude')!")
581
+ self._fft_mode = t
582
+
583
+ @property
584
+ def mfft(self) -> int:
585
+ """Length of input for the FFT used - may be larger than window
586
+ length `m_num`.
587
+
588
+ If not set, `mfft` defaults to the window length `m_num`.
589
+
590
+ See Also
591
+ --------
592
+ f_pts: Number of points along the frequency axis.
593
+ f: Frequencies values of the STFT.
594
+ m_num: Number of samples in window `win`.
595
+ ShortTimeFFT: Class this property belongs to.
596
+ """
597
+ return self._mfft
598
+
599
+ @mfft.setter
600
+ def mfft(self, n_: int):
601
+ """Setter for the length of FFT utilized.
602
+
603
+ See the property `mfft` for further details.
604
+ """
605
+ if not (n_ >= self.m_num):
606
+ raise ValueError(f"Attribute mfft={n_} needs to be at least the " +
607
+ f"window length m_num={self.m_num}!")
608
+ self._mfft = n_
609
+
610
+ @property
611
+ def scaling(self) -> Literal['magnitude', 'psd'] | None:
612
+ """Normalization applied to the window function
613
+ ('magnitude', 'psd' or ``None``).
614
+
615
+ If not ``None``, the FFTs can be either interpreted as a magnitude or
616
+ a power spectral density spectrum.
617
+
618
+ The window function can be scaled by calling the `scale_to` method,
619
+ or it is set by the initializer parameter ``scale_to``.
620
+
621
+ See Also
622
+ --------
623
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
624
+ fac_psd: Scaling factor for to a power spectral density spectrum.
625
+ fft_mode: Mode of utilized FFT
626
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
627
+ ShortTimeFFT: Class this property belongs to.
628
+ """
629
+ return self._scaling
630
+
631
+ def scale_to(self, scaling: Literal['magnitude', 'psd']):
632
+ """Scale window to obtain 'magnitude' or 'psd' scaling for the STFT.
633
+
634
+ The window of a 'magnitude' spectrum has an integral of one, i.e., unit
635
+ area for non-negative windows. This ensures that absolute the values of
636
+ spectrum does not change if the length of the window changes (given
637
+ the input signal is stationary).
638
+
639
+ To represent the power spectral density ('psd') for varying length
640
+ windows the area of the absolute square of the window needs to be
641
+ unity.
642
+
643
+ The `scaling` property shows the current scaling. The properties
644
+ `fac_magnitude` and `fac_psd` show the scaling factors required to
645
+ scale the STFT values to a magnitude or a psd spectrum.
646
+
647
+ This method is called, if the initializer parameter `scale_to` is set.
648
+
649
+ See Also
650
+ --------
651
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
652
+ fac_psd: Scaling factor for to a power spectral density spectrum.
653
+ fft_mode: Mode of utilized FFT
654
+ scaling: Normalization applied to the window function.
655
+ ShortTimeFFT: Class this method belongs to.
656
+ """
657
+ if scaling not in (scaling_values := {'magnitude', 'psd'}):
658
+ raise ValueError(f"{scaling=} not in {scaling_values}!")
659
+ if self._scaling == scaling: # do nothing
660
+ return
661
+
662
+ s_fac = self.fac_psd if scaling == 'psd' else self.fac_magnitude
663
+ self._win = self._win * s_fac
664
+ if self._dual_win is not None:
665
+ self._dual_win = self._dual_win / s_fac
666
+ self._fac_mag, self._fac_psd = None, None # reset scaling factors
667
+ self._scaling = scaling
668
+
669
+ @property
670
+ def phase_shift(self) -> int | None:
671
+ """If set, add linear phase `phase_shift` / `mfft` * `f` to each FFT
672
+ slice of frequency `f`.
673
+
674
+ Shifting (more precisely `rolling`) an `mfft`-point FFT input by
675
+ `phase_shift` samples results in a multiplication of the output by
676
+ ``np.exp(2j*np.pi*q*phase_shift/mfft)`` at the frequency q * `delta_f`.
677
+
678
+ The default value 0 ensures that there is no phase shift on the
679
+ zeroth slice (in which t=0 is centered).
680
+ No phase shift (``phase_shift is None``) is equivalent to
681
+ ``phase_shift = -mfft//2``. In this case slices are not shifted
682
+ before calculating the FFT.
683
+
684
+ The absolute value of `phase_shift` is limited to be less than `mfft`.
685
+
686
+ See Also
687
+ --------
688
+ delta_f: Width of the frequency bins of the STFT.
689
+ f: Frequencies values of the STFT.
690
+ mfft: Length of input for the FFT used
691
+ ShortTimeFFT: Class this property belongs to.
692
+ """
693
+ return self._phase_shift
694
+
695
+ @phase_shift.setter
696
+ def phase_shift(self, v: int | None):
697
+ """The absolute value of the phase shift needs to be less than mfft
698
+ samples.
699
+
700
+ See the `phase_shift` getter method for more details.
701
+ """
702
+ if v is None:
703
+ self._phase_shift = v
704
+ return
705
+ if not isinstance(v, int):
706
+ raise ValueError(f"phase_shift={v} has the unit samples. Hence " +
707
+ "it needs to be an int or it may be None!")
708
+ if not (-self.mfft < v < self.mfft):
709
+ raise ValueError("-mfft < phase_shift < mfft does not hold " +
710
+ f"for mfft={self.mfft}, phase_shift={v}!")
711
+ self._phase_shift = v
712
+
713
+ def _x_slices(self, x: np.ndarray, k_off: int, p0: int, p1: int,
714
+ padding: PAD_TYPE) -> Generator[np.ndarray, None, None]:
715
+ """Generate signal slices along last axis of `x`.
716
+
717
+ This method is only used by `stft_detrend`. The parameters are
718
+ described in `~ShortTimeFFT.stft`.
719
+ """
720
+ if padding not in (padding_types := get_args(PAD_TYPE)):
721
+ raise ValueError(f"Parameter {padding=} not in {padding_types}!")
722
+ pad_kws: dict[str, dict] = { # possible keywords to pass to np.pad:
723
+ 'zeros': dict(mode='constant', constant_values=(0, 0)),
724
+ 'edge': dict(mode='edge'),
725
+ 'even': dict(mode='reflect', reflect_type='even'),
726
+ 'odd': dict(mode='reflect', reflect_type='odd'),
727
+ } # typing of pad_kws is needed to make mypy happy
728
+
729
+ n, n1 = x.shape[-1], (p1 - p0) * self.hop
730
+ k0 = p0 * self.hop - self.m_num_mid + k_off # start sample
731
+ k1 = k0 + n1 + self.m_num # end sample
732
+
733
+ i0, i1 = max(k0, 0), min(k1, n) # indexes to shorten x
734
+ # dimensions for padding x:
735
+ pad_width = [(0, 0)] * (x.ndim-1) + [(-min(k0, 0), max(k1 - n, 0))]
736
+
737
+ x1 = np.pad(x[..., i0:i1], pad_width, **pad_kws[padding])
738
+ for k_ in range(0, n1, self.hop):
739
+ yield x1[..., k_:k_ + self.m_num]
740
+
741
+ def stft(self, x: np.ndarray, p0: int | None = None,
742
+ p1: int | None = None, *, k_offset: int = 0,
743
+ padding: PAD_TYPE = 'zeros', axis: int = -1) \
744
+ -> np.ndarray:
745
+ """Perform the short-time Fourier transform.
746
+
747
+ A two-dimensional matrix with ``p1-p0`` columns is calculated.
748
+ The `f_pts` rows represent value at the frequencies `f`. The q-th
749
+ column of the windowed FFT with the window `win` is centered at t[q].
750
+ The columns represent the values at the frequencies `f`.
751
+
752
+ Parameters
753
+ ----------
754
+ x
755
+ The input signal as real or complex valued array. For complex values, the
756
+ property `fft_mode` must be set to 'twosided' or 'centered'.
757
+ p0
758
+ The first element of the range of slices to calculate. If ``None``
759
+ then it is set to :attr:`p_min`, which is the smallest possible
760
+ slice.
761
+ p1
762
+ The end of the array. If ``None`` then `p_max(n)` is used.
763
+ k_offset
764
+ Index of first sample (t = 0) in `x`.
765
+ padding
766
+ Kind of values which are added, when the sliding window sticks out
767
+ on either the lower or upper end of the input `x`. Zeros are added
768
+ if the default 'zeros' is set. For 'edge' either the first or the
769
+ last value of `x` is used. 'even' pads by reflecting the
770
+ signal on the first or last sample and 'odd' additionally
771
+ multiplies it with -1.
772
+ axis
773
+ The axis of `x` over which to compute the STFT.
774
+ If not given, the last axis is used.
775
+
776
+ Returns
777
+ -------
778
+ S
779
+ A complex array is returned with the dimension always being larger
780
+ by one than of `x`. The last axis always represent the time slices
781
+ of the STFT. `axis` defines the frequency axis (default second to
782
+ last). E.g., for a one-dimensional `x`, a complex 2d array is
783
+ returned, with axis 0 representing frequency and axis 1 the time
784
+ slices.
785
+
786
+ See Also
787
+ --------
788
+ delta_f: Width of the frequency bins of the STFT.
789
+ delta_t: Time increment of STFT
790
+ f: Frequencies values of the STFT.
791
+ invertible: Check if STFT is invertible.
792
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
793
+ p_range: Determine and validate slice index range.
794
+ stft_detrend: STFT with detrended segments.
795
+ t: Times of STFT for an input signal with `n` samples.
796
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
797
+ """
798
+ return self.stft_detrend(x, None, p0, p1, k_offset=k_offset,
799
+ padding=padding, axis=axis)
800
+
801
+ def stft_detrend(self, x: np.ndarray,
802
+ detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None, # noqa: E501
803
+ p0: int | None = None, p1: int | None = None, *,
804
+ k_offset: int = 0, padding: PAD_TYPE = 'zeros',
805
+ axis: int = -1) \
806
+ -> np.ndarray:
807
+ """Short-time Fourier transform with a trend being subtracted from each
808
+ segment beforehand.
809
+
810
+ If `detr` is set to 'constant', the mean is subtracted, if set to
811
+ "linear", the linear trend is removed. This is achieved by calling
812
+ :func:`scipy.signal.detrend`. If `detr` is a function, `detr` is
813
+ applied to each segment.
814
+ All other parameters have the same meaning as in `~ShortTimeFFT.stft`.
815
+
816
+ Note that due to the detrending, the original signal cannot be
817
+ reconstructed by the `~ShortTimeFFT.istft`.
818
+
819
+ See Also
820
+ --------
821
+ invertible: Check if STFT is invertible.
822
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
823
+ :meth:`~ShortTimeFFT.stft`: Short-time Fourier transform
824
+ (without detrending).
825
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
826
+ """
827
+ if self.onesided_fft and np.iscomplexobj(x):
828
+ raise ValueError(f"Complex-valued `x` not allowed for {self.fft_mode=}'! "
829
+ "Set property `fft_mode` to 'twosided' or 'centered'.")
830
+ if isinstance(detr, str):
831
+ detr = partial(detrend, type=detr)
832
+ elif not (detr is None or callable(detr)):
833
+ raise ValueError(f"Parameter {detr=} is not a str, function or " +
834
+ "None!")
835
+ n = x.shape[axis]
836
+ if not (n >= (m2p := self.m_num-self.m_num_mid)):
837
+ e_str = f'{len(x)=}' if x.ndim == 1 else f'of {axis=} of {x.shape}'
838
+ raise ValueError(f"{e_str} must be >= ceil(m_num/2) = {m2p}!")
839
+
840
+ if x.ndim > 1: # motivated by the NumPy broadcasting mechanisms:
841
+ x = np.moveaxis(x, axis, -1)
842
+ # determine slice index range:
843
+ p0, p1 = self.p_range(n, p0, p1)
844
+ S_shape_1d = (self.f_pts, p1 - p0)
845
+ S_shape = x.shape[:-1] + S_shape_1d if x.ndim > 1 else S_shape_1d
846
+ S = np.zeros(S_shape, dtype=complex)
847
+ for p_, x_ in enumerate(self._x_slices(x, k_offset, p0, p1, padding)):
848
+ if detr is not None:
849
+ x_ = detr(x_)
850
+ S[..., :, p_] = self._fft_func(x_ * self.win.conj())
851
+ if x.ndim > 1:
852
+ return np.moveaxis(S, -2, axis if axis >= 0 else axis-1)
853
+ return S
854
+
855
+ def spectrogram(self, x: np.ndarray, y: np.ndarray | None = None,
856
+ detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None = None, # noqa: E501
857
+ *,
858
+ p0: int | None = None, p1: int | None = None,
859
+ k_offset: int = 0, padding: PAD_TYPE = 'zeros',
860
+ axis: int = -1) \
861
+ -> np.ndarray:
862
+ r"""Calculate spectrogram or cross-spectrogram.
863
+
864
+ The spectrogram is the absolute square of the STFT, i.e, it is
865
+ ``abs(S[q,p])**2`` for given ``S[q,p]`` and thus is always
866
+ non-negative.
867
+ For two STFTs ``Sx[q,p], Sy[q,p]``, the cross-spectrogram is defined
868
+ as ``Sx[q,p] * np.conj(Sx[q,p])`` and is complex-valued.
869
+ This is a convenience function for calling `~ShortTimeFFT.stft` /
870
+ `stft_detrend`, hence all parameters are discussed there. If `y` is not
871
+ ``None`` it needs to have the same shape as `x`.
872
+
873
+ Examples
874
+ --------
875
+ The following example shows the spectrogram of a square wave with
876
+ varying frequency :math:`f_i(t)` (marked by a green dashed line in the
877
+ plot) sampled with 20 Hz:
878
+
879
+ >>> import matplotlib.pyplot as plt
880
+ >>> import numpy as np
881
+ >>> from scipy.signal import square, ShortTimeFFT
882
+ >>> from scipy.signal.windows import gaussian
883
+ ...
884
+ >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal
885
+ >>> t_x = np.arange(N) * T_x # time indexes for signal
886
+ >>> f_i = 5e-3*(t_x - t_x[N // 3])**2 + 1 # varying frequency
887
+ >>> x = square(2*np.pi*np.cumsum(f_i)*T_x) # the signal
888
+
889
+ The utitlized Gaussian window is 50 samples or 2.5 s long. The
890
+ parameter ``mfft=800`` (oversampling factor 16) and the `hop` interval
891
+ of 2 in `ShortTimeFFT` was chosen to produce a sufficient number of
892
+ points:
893
+
894
+ >>> g_std = 12 # standard deviation for Gaussian window in samples
895
+ >>> win = gaussian(50, std=g_std, sym=True) # symmetric Gaussian wind.
896
+ >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T_x, mfft=800, scale_to='psd')
897
+ >>> Sx2 = SFT.spectrogram(x) # calculate absolute square of STFT
898
+
899
+ The plot's colormap is logarithmically scaled as the power spectral
900
+ density is in dB. The time extent of the signal `x` is marked by
901
+ vertical dashed lines and the shaded areas mark the presence of border
902
+ effects:
903
+
904
+ >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit
905
+ >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot
906
+ >>> ax1.set_title(rf"Spectrogram ({SFT.m_num*SFT.T:g}$\,s$ Gaussian " +
907
+ ... rf"window, $\sigma_t={g_std*SFT.T:g}\,$s)")
908
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " +
909
+ ... rf"$\Delta t = {SFT.delta_t:g}\,$s)",
910
+ ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " +
911
+ ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)",
912
+ ... xlim=(t_lo, t_hi))
913
+ >>> Sx_dB = 10 * np.log10(np.fmax(Sx2, 1e-4)) # limit range to -40 dB
914
+ >>> im1 = ax1.imshow(Sx_dB, origin='lower', aspect='auto',
915
+ ... extent=SFT.extent(N), cmap='magma')
916
+ >>> ax1.plot(t_x, f_i, 'g--', alpha=.5, label='$f_i(t)$')
917
+ >>> fig1.colorbar(im1, label='Power Spectral Density ' +
918
+ ... r"$20\,\log_{10}|S_x(t, f)|$ in dB")
919
+ ...
920
+ >>> # Shade areas where window slices stick out to the side:
921
+ >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T),
922
+ ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]:
923
+ ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.3)
924
+ >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line
925
+ ... ax1.axvline(t_, color='c', linestyle='--', alpha=0.5)
926
+ >>> ax1.legend()
927
+ >>> fig1.tight_layout()
928
+ >>> plt.show()
929
+
930
+ The logarithmic scaling reveals the odd harmonics of the square wave,
931
+ which are reflected at the Nyquist frequency of 10 Hz. This aliasing
932
+ is also the main source of the noise artifacts in the plot.
933
+
934
+
935
+ See Also
936
+ --------
937
+ :meth:`~ShortTimeFFT.stft`: Perform the short-time Fourier transform.
938
+ stft_detrend: STFT with a trend subtracted from each segment.
939
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
940
+ """
941
+ Sx = self.stft_detrend(x, detr, p0, p1, k_offset=k_offset,
942
+ padding=padding, axis=axis)
943
+ if y is None or y is x: # do spectrogram:
944
+ return Sx.real**2 + Sx.imag**2
945
+ # Cross-spectrogram:
946
+ Sy = self.stft_detrend(y, detr, p0, p1, k_offset=k_offset,
947
+ padding=padding, axis=axis)
948
+ return Sx * Sy.conj()
949
+
950
+ @property
951
+ def dual_win(self) -> np.ndarray:
952
+ """Canonical dual window.
953
+
954
+ A STFT can be interpreted as the input signal being expressed as a
955
+ weighted sum of modulated and time-shifted dual windows. Note that for
956
+ a given window there exist many dual windows. The canonical window is
957
+ the one with the minimal energy (i.e., :math:`L_2` norm).
958
+
959
+ `dual_win` has same length as `win`, namely `m_num` samples.
960
+
961
+ If the dual window cannot be calculated a ``ValueError`` is raised.
962
+ This attribute is read only and calculated lazily.
963
+
964
+ See Also
965
+ --------
966
+ dual_win: Canonical dual window.
967
+ m_num: Number of samples in window `win`.
968
+ win: Window function as real- or complex-valued 1d array.
969
+ ShortTimeFFT: Class this property belongs to.
970
+ """
971
+ if self._dual_win is None:
972
+ self._dual_win = _calc_dual_canonical_window(self.win, self.hop)
973
+ return self._dual_win
974
+
975
+ @property
976
+ def invertible(self) -> bool:
977
+ """Check if STFT is invertible.
978
+
979
+ This is achieved by trying to calculate the canonical dual window.
980
+
981
+ See Also
982
+ --------
983
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
984
+ m_num: Number of samples in window `win` and `dual_win`.
985
+ dual_win: Canonical dual window.
986
+ win: Window for STFT.
987
+ ShortTimeFFT: Class this property belongs to.
988
+ """
989
+ try:
990
+ return len(self.dual_win) > 0 # call self.dual_win()
991
+ except ValueError:
992
+ return False
993
+
994
+ def istft(self, S: np.ndarray, k0: int = 0, k1: int | None = None, *,
995
+ f_axis: int = -2, t_axis: int = -1) \
996
+ -> np.ndarray:
997
+ """Inverse short-time Fourier transform.
998
+
999
+ It returns an array of dimension ``S.ndim - 1`` which is real
1000
+ if `onesided_fft` is set, else complex. If the STFT is not
1001
+ `invertible`, or the parameters are out of bounds a ``ValueError`` is
1002
+ raised.
1003
+
1004
+ Parameters
1005
+ ----------
1006
+ S
1007
+ A complex valued array where `f_axis` denotes the frequency
1008
+ values and the `t-axis` dimension the temporal values of the
1009
+ STFT values.
1010
+ k0, k1
1011
+ The start and the end index of the reconstructed signal. The
1012
+ default (``k0 = 0``, ``k1 = None``) assumes that the maximum length
1013
+ signal should be reconstructed.
1014
+ f_axis, t_axis
1015
+ The axes in `S` denoting the frequency and the time dimension.
1016
+
1017
+ Notes
1018
+ -----
1019
+ It is required that `S` has `f_pts` entries along the `f_axis`. For
1020
+ the `t_axis` it is assumed that the first entry corresponds to
1021
+ `p_min` * `delta_t` (being <= 0). The length of `t_axis` needs to be
1022
+ compatible with `k1`. I.e., ``S.shape[t_axis] >= self.p_max(k1)`` must
1023
+ hold, if `k1` is not ``None``. Else `k1` is set to `k_max` with::
1024
+
1025
+ q_max = S.shape[t_range] + self.p_min
1026
+ k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid
1027
+
1028
+ The :ref:`tutorial_stft` section of the :ref:`user_guide` discussed the
1029
+ slicing behavior by means of an example.
1030
+
1031
+ See Also
1032
+ --------
1033
+ invertible: Check if STFT is invertible.
1034
+ :meth:`~ShortTimeFFT.stft`: Perform Short-time Fourier transform.
1035
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
1036
+ """
1037
+ if f_axis == t_axis:
1038
+ raise ValueError(f"{f_axis=} may not be equal to {t_axis=}!")
1039
+ if S.shape[f_axis] != self.f_pts:
1040
+ raise ValueError(f"{S.shape[f_axis]=} must be equal to " +
1041
+ f"{self.f_pts=} ({S.shape=})!")
1042
+ n_min = self.m_num-self.m_num_mid # minimum signal length
1043
+ if not (S.shape[t_axis] >= (q_num := self.p_num(n_min))):
1044
+ raise ValueError(f"{S.shape[t_axis]=} needs to have at least " +
1045
+ f"{q_num} slices ({S.shape=})!")
1046
+ if t_axis != S.ndim - 1 or f_axis != S.ndim - 2:
1047
+ t_axis = S.ndim + t_axis if t_axis < 0 else t_axis
1048
+ f_axis = S.ndim + f_axis if f_axis < 0 else f_axis
1049
+ S = np.moveaxis(S, (f_axis, t_axis), (-2, -1))
1050
+
1051
+ q_max = S.shape[-1] + self.p_min
1052
+ k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid
1053
+
1054
+ k1 = k_max if k1 is None else k1
1055
+ if not (self.k_min <= k0 < k1 <= k_max):
1056
+ raise ValueError(f"({self.k_min=}) <= ({k0=}) < ({k1=}) <= " +
1057
+ f"({k_max=}) is false!")
1058
+ if not (num_pts := k1 - k0) >= n_min:
1059
+ raise ValueError(f"({k1=}) - ({k0=}) = {num_pts} has to be at " +
1060
+ f"least the half the window length {n_min}!")
1061
+
1062
+ q0 = (k0 // self.hop + self.p_min if k0 >= 0 else # p_min always <= 0
1063
+ k0 // self.hop)
1064
+ q1 = min(self.p_max(k1), q_max)
1065
+ k_q0, k_q1 = self.nearest_k_p(k0), self.nearest_k_p(k1, left=False)
1066
+ n_pts = k_q1 - k_q0 + self.m_num - self.m_num_mid
1067
+ x = np.zeros(S.shape[:-2] + (n_pts,),
1068
+ dtype=float if self.onesided_fft else complex)
1069
+ for q_ in range(q0, q1):
1070
+ xs = self._ifft_func(S[..., :, q_ - self.p_min]) * self.dual_win
1071
+ i0 = q_ * self.hop - self.m_num_mid
1072
+ i1 = min(i0 + self.m_num, n_pts+k0)
1073
+ j0, j1 = 0, i1 - i0
1074
+ if i0 < k0: # xs sticks out to the left on x:
1075
+ j0 += k0 - i0
1076
+ i0 = k0
1077
+ x[..., i0-k0:i1-k0] += xs[..., j0:j1]
1078
+ x = x[..., :k1-k0]
1079
+ if x.ndim > 1:
1080
+ x = np.moveaxis(x, -1, f_axis if f_axis < x.ndim else t_axis)
1081
+ return x
1082
+
1083
+ @property
1084
+ def fac_magnitude(self) -> float:
1085
+ """Factor to multiply the STFT values by to scale each frequency slice
1086
+ to a magnitude spectrum.
1087
+
1088
+ It is 1 if attribute ``scaling == 'magnitude'``.
1089
+ The window can be scaled to a magnitude spectrum by using the method
1090
+ `scale_to`.
1091
+
1092
+ See Also
1093
+ --------
1094
+ fac_psd: Scaling factor for to a power spectral density spectrum.
1095
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
1096
+ scaling: Normalization applied to the window function.
1097
+ ShortTimeFFT: Class this property belongs to.
1098
+ """
1099
+ if self.scaling == 'magnitude':
1100
+ return 1
1101
+ if self._fac_mag is None:
1102
+ self._fac_mag = 1 / abs(sum(self.win))
1103
+ return self._fac_mag
1104
+
1105
+ @property
1106
+ def fac_psd(self) -> float:
1107
+ """Factor to multiply the STFT values by to scale each frequency slice
1108
+ to a power spectral density (PSD).
1109
+
1110
+ It is 1 if attribute ``scaling == 'psd'``.
1111
+ The window can be scaled to a psd spectrum by using the method
1112
+ `scale_to`.
1113
+
1114
+ See Also
1115
+ --------
1116
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
1117
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
1118
+ scaling: Normalization applied to the window function.
1119
+ ShortTimeFFT: Class this property belongs to.
1120
+ """
1121
+ if self.scaling == 'psd':
1122
+ return 1
1123
+ if self._fac_psd is None:
1124
+ self._fac_psd = 1 / np.sqrt(
1125
+ sum(self.win.real**2+self.win.imag**2) / self.T)
1126
+ return self._fac_psd
1127
+
1128
+ @property
1129
+ def m_num(self) -> int:
1130
+ """Number of samples in window `win`.
1131
+
1132
+ Note that the FFT can be oversampled by zero-padding. This is achieved
1133
+ by setting the `mfft` property.
1134
+
1135
+ See Also
1136
+ --------
1137
+ m_num_mid: Center index of window `win`.
1138
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
1139
+ hop: Time increment in signal samples for sliding window.
1140
+ win: Window function as real- or complex-valued 1d array.
1141
+ ShortTimeFFT: Class this property belongs to.
1142
+ """
1143
+ return len(self.win)
1144
+
1145
+ @property
1146
+ def m_num_mid(self) -> int:
1147
+ """Center index of window `win`.
1148
+
1149
+ For odd `m_num`, ``(m_num - 1) / 2`` is returned and
1150
+ for even `m_num` (per definition) ``m_num / 2`` is returned.
1151
+
1152
+ See Also
1153
+ --------
1154
+ m_num: Number of samples in window `win`.
1155
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
1156
+ hop: ime increment in signal samples for sliding window.
1157
+ win: Window function as real- or complex-valued 1d array.
1158
+ ShortTimeFFT: Class this property belongs to.
1159
+ """
1160
+ return self.m_num // 2
1161
+
1162
+ @cache
1163
+ def _pre_padding(self) -> tuple[int, int]:
1164
+ """Smallest signal index and slice index due to padding.
1165
+
1166
+ Since, per convention, for time t=0, n,q is zero, the returned values
1167
+ are negative or zero.
1168
+ """
1169
+ w2 = self.win.real**2 + self.win.imag**2
1170
+ # move window to the left until the overlap with t >= 0 vanishes:
1171
+ n0 = -self.m_num_mid
1172
+ for q_, n_ in enumerate(range(n0, n0-self.m_num-1, -self.hop)):
1173
+ n_next = n_ - self.hop
1174
+ if n_next + self.m_num <= 0 or all(w2[n_next:] == 0):
1175
+ return n_, -q_
1176
+ raise RuntimeError("This is code line should not have been reached!")
1177
+ # If this case is reached, it probably means the first slice should be
1178
+ # returned, i.e.: return n0, 0
1179
+
1180
+ @property
1181
+ def k_min(self) -> int:
1182
+ """The smallest possible signal index of the STFT.
1183
+
1184
+ `k_min` is the index of the left-most non-zero value of the lowest
1185
+ slice `p_min`. Since the zeroth slice is centered over the zeroth
1186
+ sample of the input signal, `k_min` is never positive.
1187
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
1188
+ section of the :ref:`user_guide`.
1189
+
1190
+ See Also
1191
+ --------
1192
+ k_max: First sample index after signal end not touched by a time slice.
1193
+ lower_border_end: Where pre-padding effects end.
1194
+ p_min: The smallest possible slice index.
1195
+ p_max: Index of first non-overlapping upper time slice.
1196
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
1197
+ p_range: Determine and validate slice index range.
1198
+ upper_border_begin: Where post-padding effects start.
1199
+ ShortTimeFFT: Class this property belongs to.
1200
+ """
1201
+ return self._pre_padding()[0]
1202
+
1203
+ @property
1204
+ def p_min(self) -> int:
1205
+ """The smallest possible slice index.
1206
+
1207
+ `p_min` is the index of the left-most slice, where the window still
1208
+ sticks into the signal, i.e., has non-zero part for t >= 0.
1209
+ `k_min` is the smallest index where the window function of the slice
1210
+ `p_min` is non-zero.
1211
+
1212
+ Since, per convention the zeroth slice is centered at t=0,
1213
+ `p_min` <= 0 always holds.
1214
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
1215
+ section of the :ref:`user_guide`.
1216
+
1217
+ See Also
1218
+ --------
1219
+ k_min: The smallest possible signal index.
1220
+ k_max: First sample index after signal end not touched by a time slice.
1221
+ p_max: Index of first non-overlapping upper time slice.
1222
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
1223
+ p_range: Determine and validate slice index range.
1224
+ ShortTimeFFT: Class this property belongs to.
1225
+ """
1226
+ return self._pre_padding()[1]
1227
+
1228
+ @lru_cache(maxsize=256)
1229
+ def _post_padding(self, n: int) -> tuple[int, int]:
1230
+ """Largest signal index and slice index due to padding."""
1231
+ w2 = self.win.real**2 + self.win.imag**2
1232
+ # move window to the right until the overlap for t < t[n] vanishes:
1233
+ q1 = n // self.hop # last slice index with t[p1] <= t[n]
1234
+ k1 = q1 * self.hop - self.m_num_mid
1235
+ for q_, k_ in enumerate(range(k1, n+self.m_num, self.hop), start=q1):
1236
+ n_next = k_ + self.hop
1237
+ if n_next >= n or all(w2[:n-n_next] == 0):
1238
+ return k_ + self.m_num, q_ + 1
1239
+ raise RuntimeError("This is code line should not have been reached!")
1240
+ # If this case is reached, it probably means the last slice should be
1241
+ # returned, i.e.: return k1 + self.m_num - self.m_num_mid, q1 + 1
1242
+
1243
+ def k_max(self, n: int) -> int:
1244
+ """First sample index after signal end not touched by a time slice.
1245
+
1246
+ `k_max` - 1 is the largest sample index of the slice `p_max` for a
1247
+ given input signal of `n` samples.
1248
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
1249
+ section of the :ref:`user_guide`.
1250
+
1251
+ See Also
1252
+ --------
1253
+ k_min: The smallest possible signal index.
1254
+ p_min: The smallest possible slice index.
1255
+ p_max: Index of first non-overlapping upper time slice.
1256
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
1257
+ p_range: Determine and validate slice index range.
1258
+ ShortTimeFFT: Class this method belongs to.
1259
+ """
1260
+ return self._post_padding(n)[0]
1261
+
1262
+ def p_max(self, n: int) -> int:
1263
+ """Index of first non-overlapping upper time slice for `n` sample
1264
+ input.
1265
+
1266
+ Note that center point t[p_max] = (p_max(n)-1) * `delta_t` is typically
1267
+ larger than last time index t[n-1] == (`n`-1) * `T`. The upper border
1268
+ of samples indexes covered by the window slices is given by `k_max`.
1269
+ Furthermore, `p_max` does not denote the number of slices `p_num` since
1270
+ `p_min` is typically less than zero.
1271
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
1272
+ section of the :ref:`user_guide`.
1273
+
1274
+ See Also
1275
+ --------
1276
+ k_min: The smallest possible signal index.
1277
+ k_max: First sample index after signal end not touched by a time slice.
1278
+ p_min: The smallest possible slice index.
1279
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
1280
+ p_range: Determine and validate slice index range.
1281
+ ShortTimeFFT: Class this method belongs to.
1282
+ """
1283
+ return self._post_padding(n)[1]
1284
+
1285
+ def p_num(self, n: int) -> int:
1286
+ """Number of time slices for an input signal with `n` samples.
1287
+
1288
+ It is given by `p_num` = `p_max` - `p_min` with `p_min` typically
1289
+ being negative.
1290
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
1291
+ section of the :ref:`user_guide`.
1292
+
1293
+ See Also
1294
+ --------
1295
+ k_min: The smallest possible signal index.
1296
+ k_max: First sample index after signal end not touched by a time slice.
1297
+ lower_border_end: Where pre-padding effects end.
1298
+ p_min: The smallest possible slice index.
1299
+ p_max: Index of first non-overlapping upper time slice.
1300
+ p_range: Determine and validate slice index range.
1301
+ upper_border_begin: Where post-padding effects start.
1302
+ ShortTimeFFT: Class this method belongs to.
1303
+ """
1304
+ return self.p_max(n) - self.p_min
1305
+
1306
+ @property
1307
+ def lower_border_end(self) -> tuple[int, int]:
1308
+ """First signal index and first slice index unaffected by pre-padding.
1309
+
1310
+ Describes the point where the window does not stick out to the left
1311
+ of the signal domain.
1312
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
1313
+ section of the :ref:`user_guide`.
1314
+
1315
+ See Also
1316
+ --------
1317
+ k_min: The smallest possible signal index.
1318
+ k_max: First sample index after signal end not touched by a time slice.
1319
+ lower_border_end: Where pre-padding effects end.
1320
+ p_min: The smallest possible slice index.
1321
+ p_max: Index of first non-overlapping upper time slice.
1322
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
1323
+ p_range: Determine and validate slice index range.
1324
+ upper_border_begin: Where post-padding effects start.
1325
+ ShortTimeFFT: Class this property belongs to.
1326
+ """
1327
+ # not using @cache decorator due to MyPy limitations
1328
+ if self._lower_border_end is not None:
1329
+ return self._lower_border_end
1330
+
1331
+ # first non-zero element in self.win:
1332
+ m0 = np.flatnonzero(self.win.real**2 + self.win.imag**2)[0]
1333
+
1334
+ # move window to the right until does not stick out to the left:
1335
+ k0 = -self.m_num_mid + m0
1336
+ for q_, k_ in enumerate(range(k0, self.hop + 1, self.hop)):
1337
+ if k_ + self.hop >= 0: # next entry does not stick out anymore
1338
+ self._lower_border_end = (k_ + self.m_num, q_ + 1)
1339
+ return self._lower_border_end
1340
+ self._lower_border_end = (0, max(self.p_min, 0)) # ends at first slice
1341
+ return self._lower_border_end
1342
+
1343
+ @lru_cache(maxsize=256)
1344
+ def upper_border_begin(self, n: int) -> tuple[int, int]:
1345
+ """First signal index and first slice index affected by post-padding.
1346
+
1347
+ Describes the point where the window does begin stick out to the right
1348
+ of the signal domain.
1349
+ A detailed example is given :ref:`tutorial_stft_sliding_win` section
1350
+ of the :ref:`user_guide`.
1351
+
1352
+ See Also
1353
+ --------
1354
+ k_min: The smallest possible signal index.
1355
+ k_max: First sample index after signal end not touched by a time slice.
1356
+ lower_border_end: Where pre-padding effects end.
1357
+ p_min: The smallest possible slice index.
1358
+ p_max: Index of first non-overlapping upper time slice.
1359
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
1360
+ p_range: Determine and validate slice index range.
1361
+ ShortTimeFFT: Class this method belongs to.
1362
+ """
1363
+ w2 = self.win.real**2 + self.win.imag**2
1364
+ q2 = n // self.hop + 1 # first t[q] >= t[n]
1365
+ q1 = max((n-self.m_num) // self.hop - 1, -1)
1366
+ # move window left until does not stick out to the right:
1367
+ for q_ in range(q2, q1, -1):
1368
+ k_ = q_ * self.hop + (self.m_num - self.m_num_mid)
1369
+ if k_ < n or all(w2[n-k_:] == 0):
1370
+ return (q_ + 1) * self.hop - self.m_num_mid, q_ + 1
1371
+ return 0, 0 # border starts at first slice
1372
+
1373
+ @property
1374
+ def delta_t(self) -> float:
1375
+ """Time increment of STFT.
1376
+
1377
+ The time increment `delta_t` = `T` * `hop` represents the sample
1378
+ increment `hop` converted to time based on the sampling interval `T`.
1379
+
1380
+ See Also
1381
+ --------
1382
+ delta_f: Width of the frequency bins of the STFT.
1383
+ hop: Hop size in signal samples for sliding window.
1384
+ t: Times of STFT for an input signal with `n` samples.
1385
+ T: Sampling interval of input signal and window `win`.
1386
+ ShortTimeFFT: Class this property belongs to
1387
+ """
1388
+ return self.T * self.hop
1389
+
1390
+ def p_range(self, n: int, p0: int | None = None,
1391
+ p1: int | None = None) -> tuple[int, int]:
1392
+ """Determine and validate slice index range.
1393
+
1394
+ Parameters
1395
+ ----------
1396
+ n : int
1397
+ Number of samples of input signal, assuming t[0] = 0.
1398
+ p0 : int | None
1399
+ First slice index. If 0 then the first slice is centered at t = 0.
1400
+ If ``None`` then `p_min` is used. Note that p0 may be < 0 if
1401
+ slices are left of t = 0.
1402
+ p1 : int | None
1403
+ End of interval (last value is p1-1).
1404
+ If ``None`` then `p_max(n)` is used.
1405
+
1406
+
1407
+ Returns
1408
+ -------
1409
+ p0_ : int
1410
+ The fist slice index
1411
+ p1_ : int
1412
+ End of interval (last value is p1-1).
1413
+
1414
+ Notes
1415
+ -----
1416
+ A ``ValueError`` is raised if ``p_min <= p0 < p1 <= p_max(n)`` does not
1417
+ hold.
1418
+
1419
+ See Also
1420
+ --------
1421
+ k_min: The smallest possible signal index.
1422
+ k_max: First sample index after signal end not touched by a time slice.
1423
+ lower_border_end: Where pre-padding effects end.
1424
+ p_min: The smallest possible slice index.
1425
+ p_max: Index of first non-overlapping upper time slice.
1426
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
1427
+ upper_border_begin: Where post-padding effects start.
1428
+ ShortTimeFFT: Class this property belongs to.
1429
+ """
1430
+ p_max = self.p_max(n) # shorthand
1431
+ p0_ = self.p_min if p0 is None else p0
1432
+ p1_ = p_max if p1 is None else p1
1433
+ if not (self.p_min <= p0_ < p1_ <= p_max):
1434
+ raise ValueError(f"Invalid Parameter {p0=}, {p1=}, i.e., " +
1435
+ f"{self.p_min=} <= p0 < p1 <= {p_max=} " +
1436
+ f"does not hold for signal length {n=}!")
1437
+ return p0_, p1_
1438
+
1439
+ @lru_cache(maxsize=1)
1440
+ def t(self, n: int, p0: int | None = None, p1: int | None = None,
1441
+ k_offset: int = 0) -> np.ndarray:
1442
+ """Times of STFT for an input signal with `n` samples.
1443
+
1444
+ Returns a 1d array with times of the `~ShortTimeFFT.stft` values with
1445
+ the same parametrization. Note that the slices are
1446
+ ``delta_t = hop * T`` time units apart.
1447
+
1448
+ Parameters
1449
+ ----------
1450
+ n
1451
+ Number of sample of the input signal.
1452
+ p0
1453
+ The first element of the range of slices to calculate. If ``None``
1454
+ then it is set to :attr:`p_min`, which is the smallest possible
1455
+ slice.
1456
+ p1
1457
+ The end of the array. If ``None`` then `p_max(n)` is used.
1458
+ k_offset
1459
+ Index of first sample (t = 0) in `x`.
1460
+
1461
+
1462
+ See Also
1463
+ --------
1464
+ delta_t: Time increment of STFT (``hop*T``)
1465
+ hop: Time increment in signal samples for sliding window.
1466
+ nearest_k_p: Nearest sample index k_p for which t[k_p] == t[p] holds.
1467
+ T: Sampling interval of input signal and of the window (``1/fs``).
1468
+ fs: Sampling frequency (being ``1/T``)
1469
+ ShortTimeFFT: Class this method belongs to.
1470
+ """
1471
+ p0, p1 = self.p_range(n, p0, p1)
1472
+ return np.arange(p0, p1) * self.delta_t + k_offset * self.T
1473
+
1474
+ def nearest_k_p(self, k: int, left: bool = True) -> int:
1475
+ """Return nearest sample index k_p for which t[k_p] == t[p] holds.
1476
+
1477
+ The nearest next smaller time sample p (where t[p] is the center
1478
+ position of the window of the p-th slice) is p_k = k // `hop`.
1479
+ If `hop` is a divisor of `k` than `k` is returned.
1480
+ If `left` is set than p_k * `hop` is returned else (p_k+1) * `hop`.
1481
+
1482
+ This method can be used to slice an input signal into chunks for
1483
+ calculating the STFT and iSTFT incrementally.
1484
+
1485
+ See Also
1486
+ --------
1487
+ delta_t: Time increment of STFT (``hop*T``)
1488
+ hop: Time increment in signal samples for sliding window.
1489
+ T: Sampling interval of input signal and of the window (``1/fs``).
1490
+ fs: Sampling frequency (being ``1/T``)
1491
+ t: Times of STFT for an input signal with `n` samples.
1492
+ ShortTimeFFT: Class this method belongs to.
1493
+ """
1494
+ p_q, remainder = divmod(k, self.hop)
1495
+ if remainder == 0:
1496
+ return k
1497
+ return p_q * self.hop if left else (p_q + 1) * self.hop
1498
+
1499
+ @property
1500
+ def delta_f(self) -> float:
1501
+ """Width of the frequency bins of the STFT.
1502
+
1503
+ Return the frequency interval `delta_f` = 1 / (`mfft` * `T`).
1504
+
1505
+ See Also
1506
+ --------
1507
+ delta_t: Time increment of STFT.
1508
+ f_pts: Number of points along the frequency axis.
1509
+ f: Frequencies values of the STFT.
1510
+ mfft: Length of the input for FFT used.
1511
+ T: Sampling interval.
1512
+ t: Times of STFT for an input signal with `n` samples.
1513
+ ShortTimeFFT: Class this property belongs to.
1514
+ """
1515
+ return 1 / (self.mfft * self.T)
1516
+
1517
+ @property
1518
+ def f_pts(self) -> int:
1519
+ """Number of points along the frequency axis.
1520
+
1521
+ See Also
1522
+ --------
1523
+ delta_f: Width of the frequency bins of the STFT.
1524
+ f: Frequencies values of the STFT.
1525
+ mfft: Length of the input for FFT used.
1526
+ ShortTimeFFT: Class this property belongs to.
1527
+ """
1528
+ return self.mfft // 2 + 1 if self.onesided_fft else self.mfft
1529
+
1530
+ @property
1531
+ def onesided_fft(self) -> bool:
1532
+ """Return True if a one-sided FFT is used.
1533
+
1534
+ Returns ``True`` if `fft_mode` is either 'onesided' or 'onesided2X'.
1535
+
1536
+ See Also
1537
+ --------
1538
+ fft_mode: Utilized FFT ('twosided', 'centered', 'onesided' or
1539
+ 'onesided2X')
1540
+ ShortTimeFFT: Class this property belongs to.
1541
+ """
1542
+ return self.fft_mode in {'onesided', 'onesided2X'}
1543
+
1544
+ @property
1545
+ def f(self) -> np.ndarray:
1546
+ """Frequencies values of the STFT.
1547
+
1548
+ A 1d array of length `f_pts` with `delta_f` spaced entries is returned.
1549
+
1550
+ See Also
1551
+ --------
1552
+ delta_f: Width of the frequency bins of the STFT.
1553
+ f_pts: Number of points along the frequency axis.
1554
+ mfft: Length of the input for FFT used.
1555
+ ShortTimeFFT: Class this property belongs to.
1556
+ """
1557
+ if self.fft_mode in {'onesided', 'onesided2X'}:
1558
+ return fft_lib.rfftfreq(self.mfft, self.T)
1559
+ elif self.fft_mode == 'twosided':
1560
+ return fft_lib.fftfreq(self.mfft, self.T)
1561
+ elif self.fft_mode == 'centered':
1562
+ return fft_lib.fftshift(fft_lib.fftfreq(self.mfft, self.T))
1563
+ # This should never happen but makes the Linters happy:
1564
+ fft_modes = get_args(FFT_MODE_TYPE)
1565
+ raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!")
1566
+
1567
+ def _fft_func(self, x: np.ndarray) -> np.ndarray:
1568
+ """FFT based on the `fft_mode`, `mfft`, `scaling` and `phase_shift`
1569
+ attributes.
1570
+
1571
+ For multidimensional arrays the transformation is carried out on the
1572
+ last axis.
1573
+ """
1574
+ if self.phase_shift is not None:
1575
+ if x.shape[-1] < self.mfft: # zero pad if needed
1576
+ z_shape = list(x.shape)
1577
+ z_shape[-1] = self.mfft - x.shape[-1]
1578
+ x = np.hstack((x, np.zeros(z_shape, dtype=x.dtype)))
1579
+ p_s = (self.phase_shift + self.m_num_mid) % self.m_num
1580
+ x = np.roll(x, -p_s, axis=-1)
1581
+
1582
+ if self.fft_mode == 'twosided':
1583
+ return fft_lib.fft(x, n=self.mfft, axis=-1)
1584
+ if self.fft_mode == 'centered':
1585
+ return fft_lib.fftshift(fft_lib.fft(x, self.mfft, axis=-1), axes=-1)
1586
+ if self.fft_mode == 'onesided':
1587
+ return fft_lib.rfft(x, n=self.mfft, axis=-1)
1588
+ if self.fft_mode == 'onesided2X':
1589
+ X = fft_lib.rfft(x, n=self.mfft, axis=-1)
1590
+ # Either squared magnitude (psd) or magnitude is doubled:
1591
+ fac = np.sqrt(2) if self.scaling == 'psd' else 2
1592
+ # For even input length, the last entry is unpaired:
1593
+ X[..., 1: -1 if self.mfft % 2 == 0 else None] *= fac
1594
+ return X
1595
+ # This should never happen but makes the Linter happy:
1596
+ fft_modes = get_args(FFT_MODE_TYPE)
1597
+ raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!")
1598
+
1599
+ def _ifft_func(self, X: np.ndarray) -> np.ndarray:
1600
+ """Inverse to `_fft_func`.
1601
+
1602
+ Returned is an array of length `m_num`. If the FFT is `onesided`
1603
+ then a float array is returned else a complex array is returned.
1604
+ For multidimensional arrays the transformation is carried out on the
1605
+ last axis.
1606
+ """
1607
+ if self.fft_mode == 'twosided':
1608
+ x = fft_lib.ifft(X, n=self.mfft, axis=-1)
1609
+ elif self.fft_mode == 'centered':
1610
+ x = fft_lib.ifft(fft_lib.ifftshift(X, axes=-1), n=self.mfft, axis=-1)
1611
+ elif self.fft_mode == 'onesided':
1612
+ x = fft_lib.irfft(X, n=self.mfft, axis=-1)
1613
+ elif self.fft_mode == 'onesided2X':
1614
+ Xc = X.copy() # we do not want to modify function parameters
1615
+ fac = np.sqrt(2) if self.scaling == 'psd' else 2
1616
+ # For even length X the last value is not paired with a negative
1617
+ # value on the two-sided FFT:
1618
+ q1 = -1 if self.mfft % 2 == 0 else None
1619
+ Xc[..., 1:q1] /= fac
1620
+ x = fft_lib.irfft(Xc, n=self.mfft, axis=-1)
1621
+ else: # This should never happen but makes the Linter happy:
1622
+ error_str = f"{self.fft_mode=} not in {get_args(FFT_MODE_TYPE)}!"
1623
+ raise RuntimeError(error_str)
1624
+
1625
+ if self.phase_shift is None:
1626
+ return x[:self.m_num]
1627
+ p_s = (self.phase_shift + self.m_num_mid) % self.m_num
1628
+ return np.roll(x, p_s, axis=-1)[:self.m_num]
1629
+
1630
+ def extent(self, n: int, axes_seq: Literal['tf', 'ft'] = 'tf',
1631
+ center_bins: bool = False) -> tuple[float, float, float, float]:
1632
+ """Return minimum and maximum values time-frequency values.
1633
+
1634
+ A tuple with four floats ``(t0, t1, f0, f1)`` for 'tf' and
1635
+ ``(f0, f1, t0, t1)`` for 'ft' is returned describing the corners
1636
+ of the time-frequency domain of the `~ShortTimeFFT.stft`.
1637
+ That tuple can be passed to `matplotlib.pyplot.imshow` as a parameter
1638
+ with the same name.
1639
+
1640
+ Parameters
1641
+ ----------
1642
+ n : int
1643
+ Number of samples in input signal.
1644
+ axes_seq : {'tf', 'ft'}
1645
+ Return time extent first and then frequency extent or vice-versa.
1646
+ center_bins: bool
1647
+ If set (default ``False``), the values of the time slots and
1648
+ frequency bins are moved from the side the middle. This is useful,
1649
+ when plotting the `~ShortTimeFFT.stft` values as step functions,
1650
+ i.e., with no interpolation.
1651
+
1652
+ See Also
1653
+ --------
1654
+ :func:`matplotlib.pyplot.imshow`: Display data as an image.
1655
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
1656
+ """
1657
+ if axes_seq not in ('tf', 'ft'):
1658
+ raise ValueError(f"Parameter {axes_seq=} not in ['tf', 'ft']!")
1659
+
1660
+ if self.onesided_fft:
1661
+ q0, q1 = 0, self.f_pts
1662
+ elif self.fft_mode == 'centered':
1663
+ q0 = -self.mfft // 2
1664
+ q1 = self.mfft // 2 - 1 if self.mfft % 2 == 0 else self.mfft // 2
1665
+ else:
1666
+ raise ValueError(f"Attribute fft_mode={self.fft_mode} must be " +
1667
+ "in ['centered', 'onesided', 'onesided2X']")
1668
+
1669
+ p0, p1 = self.p_min, self.p_max(n) # shorthand
1670
+ if center_bins:
1671
+ t0, t1 = self.delta_t * (p0 - 0.5), self.delta_t * (p1 - 0.5)
1672
+ f0, f1 = self.delta_f * (q0 - 0.5), self.delta_f * (q1 - 0.5)
1673
+ else:
1674
+ t0, t1 = self.delta_t * p0, self.delta_t * p1
1675
+ f0, f1 = self.delta_f * q0, self.delta_f * q1
1676
+ return (t0, t1, f0, f1) if axes_seq == 'tf' else (f0, f1, t0, t1)
llmeval-env/lib/python3.10/site-packages/scipy/signal/_signaltools.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/scipy/signal/_sigtools.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (109 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/signal/_spline.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (85.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/signal/_upfirdn.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code adapted from "upfirdn" python library with permission:
2
+ #
3
+ # Copyright (c) 2009, Motorola, Inc
4
+ #
5
+ # All Rights Reserved.
6
+ #
7
+ # Redistribution and use in source and binary forms, with or without
8
+ # modification, are permitted provided that the following conditions are
9
+ # met:
10
+ #
11
+ # * Redistributions of source code must retain the above copyright notice,
12
+ # this list of conditions and the following disclaimer.
13
+ #
14
+ # * Redistributions in binary form must reproduce the above copyright
15
+ # notice, this list of conditions and the following disclaimer in the
16
+ # documentation and/or other materials provided with the distribution.
17
+ #
18
+ # * Neither the name of Motorola nor the names of its contributors may be
19
+ # used to endorse or promote products derived from this software without
20
+ # specific prior written permission.
21
+ #
22
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
23
+ # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
24
+ # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25
+ # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
26
+ # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
27
+ # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28
+ # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
29
+ # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30
+ # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
31
+ # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33
+
34
+ import numpy as np
35
+
36
+ from ._upfirdn_apply import _output_len, _apply, mode_enum
37
+
38
+ __all__ = ['upfirdn', '_output_len']
39
+
40
+ _upfirdn_modes = [
41
+ 'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect',
42
+ 'antisymmetric', 'antireflect', 'line',
43
+ ]
44
+
45
+
46
+ def _pad_h(h, up):
47
+ """Store coefficients in a transposed, flipped arrangement.
48
+
49
+ For example, suppose upRate is 3, and the
50
+ input number of coefficients is 10, represented as h[0], ..., h[9].
51
+
52
+ Then the internal buffer will look like this::
53
+
54
+ h[9], h[6], h[3], h[0], // flipped phase 0 coefs
55
+ 0, h[7], h[4], h[1], // flipped phase 1 coefs (zero-padded)
56
+ 0, h[8], h[5], h[2], // flipped phase 2 coefs (zero-padded)
57
+
58
+ """
59
+ h_padlen = len(h) + (-len(h) % up)
60
+ h_full = np.zeros(h_padlen, h.dtype)
61
+ h_full[:len(h)] = h
62
+ h_full = h_full.reshape(-1, up).T[:, ::-1].ravel()
63
+ return h_full
64
+
65
+
66
+ def _check_mode(mode):
67
+ mode = mode.lower()
68
+ enum = mode_enum(mode)
69
+ return enum
70
+
71
+
72
+ class _UpFIRDn:
73
+ """Helper for resampling."""
74
+
75
+ def __init__(self, h, x_dtype, up, down):
76
+ h = np.asarray(h)
77
+ if h.ndim != 1 or h.size == 0:
78
+ raise ValueError('h must be 1-D with non-zero length')
79
+ self._output_type = np.result_type(h.dtype, x_dtype, np.float32)
80
+ h = np.asarray(h, self._output_type)
81
+ self._up = int(up)
82
+ self._down = int(down)
83
+ if self._up < 1 or self._down < 1:
84
+ raise ValueError('Both up and down must be >= 1')
85
+ # This both transposes, and "flips" each phase for filtering
86
+ self._h_trans_flip = _pad_h(h, self._up)
87
+ self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip)
88
+ self._h_len_orig = len(h)
89
+
90
+ def apply_filter(self, x, axis=-1, mode='constant', cval=0):
91
+ """Apply the prepared filter to the specified axis of N-D signal x."""
92
+ output_len = _output_len(self._h_len_orig, x.shape[axis],
93
+ self._up, self._down)
94
+ # Explicit use of np.int64 for output_shape dtype avoids OverflowError
95
+ # when allocating large array on platforms where intp is 32 bits.
96
+ output_shape = np.asarray(x.shape, dtype=np.int64)
97
+ output_shape[axis] = output_len
98
+ out = np.zeros(output_shape, dtype=self._output_type, order='C')
99
+ axis = axis % x.ndim
100
+ mode = _check_mode(mode)
101
+ _apply(np.asarray(x, self._output_type),
102
+ self._h_trans_flip, out,
103
+ self._up, self._down, axis, mode, cval)
104
+ return out
105
+
106
+
107
+ def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):
108
+ """Upsample, FIR filter, and downsample.
109
+
110
+ Parameters
111
+ ----------
112
+ h : array_like
113
+ 1-D FIR (finite-impulse response) filter coefficients.
114
+ x : array_like
115
+ Input signal array.
116
+ up : int, optional
117
+ Upsampling rate. Default is 1.
118
+ down : int, optional
119
+ Downsampling rate. Default is 1.
120
+ axis : int, optional
121
+ The axis of the input data array along which to apply the
122
+ linear filter. The filter is applied to each subarray along
123
+ this axis. Default is -1.
124
+ mode : str, optional
125
+ The signal extension mode to use. The set
126
+ ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to
127
+ modes provided by `numpy.pad`. ``"smooth"`` implements a smooth
128
+ extension by extending based on the slope of the last 2 points at each
129
+ end of the array. ``"antireflect"`` and ``"antisymmetric"`` are
130
+ anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode
131
+ `"line"` extends the signal based on a linear trend defined by the
132
+ first and last points along the ``axis``.
133
+
134
+ .. versionadded:: 1.4.0
135
+ cval : float, optional
136
+ The constant value to use when ``mode == "constant"``.
137
+
138
+ .. versionadded:: 1.4.0
139
+
140
+ Returns
141
+ -------
142
+ y : ndarray
143
+ The output signal array. Dimensions will be the same as `x` except
144
+ for along `axis`, which will change size according to the `h`,
145
+ `up`, and `down` parameters.
146
+
147
+ Notes
148
+ -----
149
+ The algorithm is an implementation of the block diagram shown on page 129
150
+ of the Vaidyanathan text [1]_ (Figure 4.3-8d).
151
+
152
+ The direct approach of upsampling by factor of P with zero insertion,
153
+ FIR filtering of length ``N``, and downsampling by factor of Q is
154
+ O(N*Q) per output sample. The polyphase implementation used here is
155
+ O(N/P).
156
+
157
+ .. versionadded:: 0.18
158
+
159
+ References
160
+ ----------
161
+ .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,
162
+ Prentice Hall, 1993.
163
+
164
+ Examples
165
+ --------
166
+ Simple operations:
167
+
168
+ >>> import numpy as np
169
+ >>> from scipy.signal import upfirdn
170
+ >>> upfirdn([1, 1, 1], [1, 1, 1]) # FIR filter
171
+ array([ 1., 2., 3., 2., 1.])
172
+ >>> upfirdn([1], [1, 2, 3], 3) # upsampling with zeros insertion
173
+ array([ 1., 0., 0., 2., 0., 0., 3.])
174
+ >>> upfirdn([1, 1, 1], [1, 2, 3], 3) # upsampling with sample-and-hold
175
+ array([ 1., 1., 1., 2., 2., 2., 3., 3., 3.])
176
+ >>> upfirdn([.5, 1, .5], [1, 1, 1], 2) # linear interpolation
177
+ array([ 0.5, 1. , 1. , 1. , 1. , 1. , 0.5])
178
+ >>> upfirdn([1], np.arange(10), 1, 3) # decimation by 3
179
+ array([ 0., 3., 6., 9.])
180
+ >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3) # linear interp, rate 2/3
181
+ array([ 0. , 1. , 2.5, 4. , 5.5, 7. , 8.5])
182
+
183
+ Apply a single filter to multiple signals:
184
+
185
+ >>> x = np.reshape(np.arange(8), (4, 2))
186
+ >>> x
187
+ array([[0, 1],
188
+ [2, 3],
189
+ [4, 5],
190
+ [6, 7]])
191
+
192
+ Apply along the last dimension of ``x``:
193
+
194
+ >>> h = [1, 1]
195
+ >>> upfirdn(h, x, 2)
196
+ array([[ 0., 0., 1., 1.],
197
+ [ 2., 2., 3., 3.],
198
+ [ 4., 4., 5., 5.],
199
+ [ 6., 6., 7., 7.]])
200
+
201
+ Apply along the 0th dimension of ``x``:
202
+
203
+ >>> upfirdn(h, x, 2, axis=0)
204
+ array([[ 0., 1.],
205
+ [ 0., 1.],
206
+ [ 2., 3.],
207
+ [ 2., 3.],
208
+ [ 4., 5.],
209
+ [ 4., 5.],
210
+ [ 6., 7.],
211
+ [ 6., 7.]])
212
+ """
213
+ x = np.asarray(x)
214
+ ufd = _UpFIRDn(h, x.dtype, up, down)
215
+ # This is equivalent to (but faster than) using np.apply_along_axis
216
+ return ufd.apply_filter(x, axis, mode, cval)
llmeval-env/lib/python3.10/site-packages/scipy/signal/_upfirdn_apply.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (395 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/signal/_waveforms.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Author: Travis Oliphant
2
+ # 2003
3
+ #
4
+ # Feb. 2010: Updated by Warren Weckesser:
5
+ # Rewrote much of chirp()
6
+ # Added sweep_poly()
7
+ import numpy as np
8
+ from numpy import asarray, zeros, place, nan, mod, pi, extract, log, sqrt, \
9
+ exp, cos, sin, polyval, polyint
10
+
11
+
12
+ __all__ = ['sawtooth', 'square', 'gausspulse', 'chirp', 'sweep_poly',
13
+ 'unit_impulse']
14
+
15
+
16
+ def sawtooth(t, width=1):
17
+ """
18
+ Return a periodic sawtooth or triangle waveform.
19
+
20
+ The sawtooth waveform has a period ``2*pi``, rises from -1 to 1 on the
21
+ interval 0 to ``width*2*pi``, then drops from 1 to -1 on the interval
22
+ ``width*2*pi`` to ``2*pi``. `width` must be in the interval [0, 1].
23
+
24
+ Note that this is not band-limited. It produces an infinite number
25
+ of harmonics, which are aliased back and forth across the frequency
26
+ spectrum.
27
+
28
+ Parameters
29
+ ----------
30
+ t : array_like
31
+ Time.
32
+ width : array_like, optional
33
+ Width of the rising ramp as a proportion of the total cycle.
34
+ Default is 1, producing a rising ramp, while 0 produces a falling
35
+ ramp. `width` = 0.5 produces a triangle wave.
36
+ If an array, causes wave shape to change over time, and must be the
37
+ same length as t.
38
+
39
+ Returns
40
+ -------
41
+ y : ndarray
42
+ Output array containing the sawtooth waveform.
43
+
44
+ Examples
45
+ --------
46
+ A 5 Hz waveform sampled at 500 Hz for 1 second:
47
+
48
+ >>> import numpy as np
49
+ >>> from scipy import signal
50
+ >>> import matplotlib.pyplot as plt
51
+ >>> t = np.linspace(0, 1, 500)
52
+ >>> plt.plot(t, signal.sawtooth(2 * np.pi * 5 * t))
53
+
54
+ """
55
+ t, w = asarray(t), asarray(width)
56
+ w = asarray(w + (t - t))
57
+ t = asarray(t + (w - w))
58
+ if t.dtype.char in ['fFdD']:
59
+ ytype = t.dtype.char
60
+ else:
61
+ ytype = 'd'
62
+ y = zeros(t.shape, ytype)
63
+
64
+ # width must be between 0 and 1 inclusive
65
+ mask1 = (w > 1) | (w < 0)
66
+ place(y, mask1, nan)
67
+
68
+ # take t modulo 2*pi
69
+ tmod = mod(t, 2 * pi)
70
+
71
+ # on the interval 0 to width*2*pi function is
72
+ # tmod / (pi*w) - 1
73
+ mask2 = (1 - mask1) & (tmod < w * 2 * pi)
74
+ tsub = extract(mask2, tmod)
75
+ wsub = extract(mask2, w)
76
+ place(y, mask2, tsub / (pi * wsub) - 1)
77
+
78
+ # on the interval width*2*pi to 2*pi function is
79
+ # (pi*(w+1)-tmod) / (pi*(1-w))
80
+
81
+ mask3 = (1 - mask1) & (1 - mask2)
82
+ tsub = extract(mask3, tmod)
83
+ wsub = extract(mask3, w)
84
+ place(y, mask3, (pi * (wsub + 1) - tsub) / (pi * (1 - wsub)))
85
+ return y
86
+
87
+
88
+ def square(t, duty=0.5):
89
+ """
90
+ Return a periodic square-wave waveform.
91
+
92
+ The square wave has a period ``2*pi``, has value +1 from 0 to
93
+ ``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in
94
+ the interval [0,1].
95
+
96
+ Note that this is not band-limited. It produces an infinite number
97
+ of harmonics, which are aliased back and forth across the frequency
98
+ spectrum.
99
+
100
+ Parameters
101
+ ----------
102
+ t : array_like
103
+ The input time array.
104
+ duty : array_like, optional
105
+ Duty cycle. Default is 0.5 (50% duty cycle).
106
+ If an array, causes wave shape to change over time, and must be the
107
+ same length as t.
108
+
109
+ Returns
110
+ -------
111
+ y : ndarray
112
+ Output array containing the square waveform.
113
+
114
+ Examples
115
+ --------
116
+ A 5 Hz waveform sampled at 500 Hz for 1 second:
117
+
118
+ >>> import numpy as np
119
+ >>> from scipy import signal
120
+ >>> import matplotlib.pyplot as plt
121
+ >>> t = np.linspace(0, 1, 500, endpoint=False)
122
+ >>> plt.plot(t, signal.square(2 * np.pi * 5 * t))
123
+ >>> plt.ylim(-2, 2)
124
+
125
+ A pulse-width modulated sine wave:
126
+
127
+ >>> plt.figure()
128
+ >>> sig = np.sin(2 * np.pi * t)
129
+ >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
130
+ >>> plt.subplot(2, 1, 1)
131
+ >>> plt.plot(t, sig)
132
+ >>> plt.subplot(2, 1, 2)
133
+ >>> plt.plot(t, pwm)
134
+ >>> plt.ylim(-1.5, 1.5)
135
+
136
+ """
137
+ t, w = asarray(t), asarray(duty)
138
+ w = asarray(w + (t - t))
139
+ t = asarray(t + (w - w))
140
+ if t.dtype.char in ['fFdD']:
141
+ ytype = t.dtype.char
142
+ else:
143
+ ytype = 'd'
144
+
145
+ y = zeros(t.shape, ytype)
146
+
147
+ # width must be between 0 and 1 inclusive
148
+ mask1 = (w > 1) | (w < 0)
149
+ place(y, mask1, nan)
150
+
151
+ # on the interval 0 to duty*2*pi function is 1
152
+ tmod = mod(t, 2 * pi)
153
+ mask2 = (1 - mask1) & (tmod < w * 2 * pi)
154
+ place(y, mask2, 1)
155
+
156
+ # on the interval duty*2*pi to 2*pi function is
157
+ # (pi*(w+1)-tmod) / (pi*(1-w))
158
+ mask3 = (1 - mask1) & (1 - mask2)
159
+ place(y, mask3, -1)
160
+ return y
161
+
162
+
163
+ def gausspulse(t, fc=1000, bw=0.5, bwr=-6, tpr=-60, retquad=False,
164
+ retenv=False):
165
+ """
166
+ Return a Gaussian modulated sinusoid:
167
+
168
+ ``exp(-a t^2) exp(1j*2*pi*fc*t).``
169
+
170
+ If `retquad` is True, then return the real and imaginary parts
171
+ (in-phase and quadrature).
172
+ If `retenv` is True, then return the envelope (unmodulated signal).
173
+ Otherwise, return the real part of the modulated sinusoid.
174
+
175
+ Parameters
176
+ ----------
177
+ t : ndarray or the string 'cutoff'
178
+ Input array.
179
+ fc : float, optional
180
+ Center frequency (e.g. Hz). Default is 1000.
181
+ bw : float, optional
182
+ Fractional bandwidth in frequency domain of pulse (e.g. Hz).
183
+ Default is 0.5.
184
+ bwr : float, optional
185
+ Reference level at which fractional bandwidth is calculated (dB).
186
+ Default is -6.
187
+ tpr : float, optional
188
+ If `t` is 'cutoff', then the function returns the cutoff
189
+ time for when the pulse amplitude falls below `tpr` (in dB).
190
+ Default is -60.
191
+ retquad : bool, optional
192
+ If True, return the quadrature (imaginary) as well as the real part
193
+ of the signal. Default is False.
194
+ retenv : bool, optional
195
+ If True, return the envelope of the signal. Default is False.
196
+
197
+ Returns
198
+ -------
199
+ yI : ndarray
200
+ Real part of signal. Always returned.
201
+ yQ : ndarray
202
+ Imaginary part of signal. Only returned if `retquad` is True.
203
+ yenv : ndarray
204
+ Envelope of signal. Only returned if `retenv` is True.
205
+
206
+ See Also
207
+ --------
208
+ scipy.signal.morlet
209
+
210
+ Examples
211
+ --------
212
+ Plot real component, imaginary component, and envelope for a 5 Hz pulse,
213
+ sampled at 100 Hz for 2 seconds:
214
+
215
+ >>> import numpy as np
216
+ >>> from scipy import signal
217
+ >>> import matplotlib.pyplot as plt
218
+ >>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)
219
+ >>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)
220
+ >>> plt.plot(t, i, t, q, t, e, '--')
221
+
222
+ """
223
+ if fc < 0:
224
+ raise ValueError("Center frequency (fc=%.2f) must be >=0." % fc)
225
+ if bw <= 0:
226
+ raise ValueError("Fractional bandwidth (bw=%.2f) must be > 0." % bw)
227
+ if bwr >= 0:
228
+ raise ValueError("Reference level for bandwidth (bwr=%.2f) must "
229
+ "be < 0 dB" % bwr)
230
+
231
+ # exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f)
232
+
233
+ ref = pow(10.0, bwr / 20.0)
234
+ # fdel = fc*bw/2: g(fdel) = ref --- solve this for a
235
+ #
236
+ # pi^2/a * fc^2 * bw^2 /4=-log(ref)
237
+ a = -(pi * fc * bw) ** 2 / (4.0 * log(ref))
238
+
239
+ if isinstance(t, str):
240
+ if t == 'cutoff': # compute cut_off point
241
+ # Solve exp(-a tc**2) = tref for tc
242
+ # tc = sqrt(-log(tref) / a) where tref = 10^(tpr/20)
243
+ if tpr >= 0:
244
+ raise ValueError("Reference level for time cutoff must "
245
+ "be < 0 dB")
246
+ tref = pow(10.0, tpr / 20.0)
247
+ return sqrt(-log(tref) / a)
248
+ else:
249
+ raise ValueError("If `t` is a string, it must be 'cutoff'")
250
+
251
+ yenv = exp(-a * t * t)
252
+ yI = yenv * cos(2 * pi * fc * t)
253
+ yQ = yenv * sin(2 * pi * fc * t)
254
+ if not retquad and not retenv:
255
+ return yI
256
+ if not retquad and retenv:
257
+ return yI, yenv
258
+ if retquad and not retenv:
259
+ return yI, yQ
260
+ if retquad and retenv:
261
+ return yI, yQ, yenv
262
+
263
+
264
+ def chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True):
265
+ """Frequency-swept cosine generator.
266
+
267
+ In the following, 'Hz' should be interpreted as 'cycles per unit';
268
+ there is no requirement here that the unit is one second. The
269
+ important distinction is that the units of rotation are cycles, not
270
+ radians. Likewise, `t` could be a measurement of space instead of time.
271
+
272
+ Parameters
273
+ ----------
274
+ t : array_like
275
+ Times at which to evaluate the waveform.
276
+ f0 : float
277
+ Frequency (e.g. Hz) at time t=0.
278
+ t1 : float
279
+ Time at which `f1` is specified.
280
+ f1 : float
281
+ Frequency (e.g. Hz) of the waveform at time `t1`.
282
+ method : {'linear', 'quadratic', 'logarithmic', 'hyperbolic'}, optional
283
+ Kind of frequency sweep. If not given, `linear` is assumed. See
284
+ Notes below for more details.
285
+ phi : float, optional
286
+ Phase offset, in degrees. Default is 0.
287
+ vertex_zero : bool, optional
288
+ This parameter is only used when `method` is 'quadratic'.
289
+ It determines whether the vertex of the parabola that is the graph
290
+ of the frequency is at t=0 or t=t1.
291
+
292
+ Returns
293
+ -------
294
+ y : ndarray
295
+ A numpy array containing the signal evaluated at `t` with the
296
+ requested time-varying frequency. More precisely, the function
297
+ returns ``cos(phase + (pi/180)*phi)`` where `phase` is the integral
298
+ (from 0 to `t`) of ``2*pi*f(t)``. ``f(t)`` is defined below.
299
+
300
+ See Also
301
+ --------
302
+ sweep_poly
303
+
304
+ Notes
305
+ -----
306
+ There are four options for the `method`. The following formulas give
307
+ the instantaneous frequency (in Hz) of the signal generated by
308
+ `chirp()`. For convenience, the shorter names shown below may also be
309
+ used.
310
+
311
+ linear, lin, li:
312
+
313
+ ``f(t) = f0 + (f1 - f0) * t / t1``
314
+
315
+ quadratic, quad, q:
316
+
317
+ The graph of the frequency f(t) is a parabola through (0, f0) and
318
+ (t1, f1). By default, the vertex of the parabola is at (0, f0).
319
+ If `vertex_zero` is False, then the vertex is at (t1, f1). The
320
+ formula is:
321
+
322
+ if vertex_zero is True:
323
+
324
+ ``f(t) = f0 + (f1 - f0) * t**2 / t1**2``
325
+
326
+ else:
327
+
328
+ ``f(t) = f1 - (f1 - f0) * (t1 - t)**2 / t1**2``
329
+
330
+ To use a more general quadratic function, or an arbitrary
331
+ polynomial, use the function `scipy.signal.sweep_poly`.
332
+
333
+ logarithmic, log, lo:
334
+
335
+ ``f(t) = f0 * (f1/f0)**(t/t1)``
336
+
337
+ f0 and f1 must be nonzero and have the same sign.
338
+
339
+ This signal is also known as a geometric or exponential chirp.
340
+
341
+ hyperbolic, hyp:
342
+
343
+ ``f(t) = f0*f1*t1 / ((f0 - f1)*t + f1*t1)``
344
+
345
+ f0 and f1 must be nonzero.
346
+
347
+ Examples
348
+ --------
349
+ The following will be used in the examples:
350
+
351
+ >>> import numpy as np
352
+ >>> from scipy.signal import chirp, spectrogram
353
+ >>> import matplotlib.pyplot as plt
354
+
355
+ For the first example, we'll plot the waveform for a linear chirp
356
+ from 6 Hz to 1 Hz over 10 seconds:
357
+
358
+ >>> t = np.linspace(0, 10, 1500)
359
+ >>> w = chirp(t, f0=6, f1=1, t1=10, method='linear')
360
+ >>> plt.plot(t, w)
361
+ >>> plt.title("Linear Chirp, f(0)=6, f(10)=1")
362
+ >>> plt.xlabel('t (sec)')
363
+ >>> plt.show()
364
+
365
+ For the remaining examples, we'll use higher frequency ranges,
366
+ and demonstrate the result using `scipy.signal.spectrogram`.
367
+ We'll use a 4 second interval sampled at 7200 Hz.
368
+
369
+ >>> fs = 7200
370
+ >>> T = 4
371
+ >>> t = np.arange(0, int(T*fs)) / fs
372
+
373
+ We'll use this function to plot the spectrogram in each example.
374
+
375
+ >>> def plot_spectrogram(title, w, fs):
376
+ ... ff, tt, Sxx = spectrogram(w, fs=fs, nperseg=256, nfft=576)
377
+ ... fig, ax = plt.subplots()
378
+ ... ax.pcolormesh(tt, ff[:145], Sxx[:145], cmap='gray_r',
379
+ ... shading='gouraud')
380
+ ... ax.set_title(title)
381
+ ... ax.set_xlabel('t (sec)')
382
+ ... ax.set_ylabel('Frequency (Hz)')
383
+ ... ax.grid(True)
384
+ ...
385
+
386
+ Quadratic chirp from 1500 Hz to 250 Hz
387
+ (vertex of the parabolic curve of the frequency is at t=0):
388
+
389
+ >>> w = chirp(t, f0=1500, f1=250, t1=T, method='quadratic')
390
+ >>> plot_spectrogram(f'Quadratic Chirp, f(0)=1500, f({T})=250', w, fs)
391
+ >>> plt.show()
392
+
393
+ Quadratic chirp from 1500 Hz to 250 Hz
394
+ (vertex of the parabolic curve of the frequency is at t=T):
395
+
396
+ >>> w = chirp(t, f0=1500, f1=250, t1=T, method='quadratic',
397
+ ... vertex_zero=False)
398
+ >>> plot_spectrogram(f'Quadratic Chirp, f(0)=1500, f({T})=250\\n' +
399
+ ... '(vertex_zero=False)', w, fs)
400
+ >>> plt.show()
401
+
402
+ Logarithmic chirp from 1500 Hz to 250 Hz:
403
+
404
+ >>> w = chirp(t, f0=1500, f1=250, t1=T, method='logarithmic')
405
+ >>> plot_spectrogram(f'Logarithmic Chirp, f(0)=1500, f({T})=250', w, fs)
406
+ >>> plt.show()
407
+
408
+ Hyperbolic chirp from 1500 Hz to 250 Hz:
409
+
410
+ >>> w = chirp(t, f0=1500, f1=250, t1=T, method='hyperbolic')
411
+ >>> plot_spectrogram(f'Hyperbolic Chirp, f(0)=1500, f({T})=250', w, fs)
412
+ >>> plt.show()
413
+
414
+ """
415
+ # 'phase' is computed in _chirp_phase, to make testing easier.
416
+ phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero)
417
+ # Convert phi to radians.
418
+ phi *= pi / 180
419
+ return cos(phase + phi)
420
+
421
+
422
+ def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True):
423
+ """
424
+ Calculate the phase used by `chirp` to generate its output.
425
+
426
+ See `chirp` for a description of the arguments.
427
+
428
+ """
429
+ t = asarray(t)
430
+ f0 = float(f0)
431
+ t1 = float(t1)
432
+ f1 = float(f1)
433
+ if method in ['linear', 'lin', 'li']:
434
+ beta = (f1 - f0) / t1
435
+ phase = 2 * pi * (f0 * t + 0.5 * beta * t * t)
436
+
437
+ elif method in ['quadratic', 'quad', 'q']:
438
+ beta = (f1 - f0) / (t1 ** 2)
439
+ if vertex_zero:
440
+ phase = 2 * pi * (f0 * t + beta * t ** 3 / 3)
441
+ else:
442
+ phase = 2 * pi * (f1 * t + beta * ((t1 - t) ** 3 - t1 ** 3) / 3)
443
+
444
+ elif method in ['logarithmic', 'log', 'lo']:
445
+ if f0 * f1 <= 0.0:
446
+ raise ValueError("For a logarithmic chirp, f0 and f1 must be "
447
+ "nonzero and have the same sign.")
448
+ if f0 == f1:
449
+ phase = 2 * pi * f0 * t
450
+ else:
451
+ beta = t1 / log(f1 / f0)
452
+ phase = 2 * pi * beta * f0 * (pow(f1 / f0, t / t1) - 1.0)
453
+
454
+ elif method in ['hyperbolic', 'hyp']:
455
+ if f0 == 0 or f1 == 0:
456
+ raise ValueError("For a hyperbolic chirp, f0 and f1 must be "
457
+ "nonzero.")
458
+ if f0 == f1:
459
+ # Degenerate case: constant frequency.
460
+ phase = 2 * pi * f0 * t
461
+ else:
462
+ # Singular point: the instantaneous frequency blows up
463
+ # when t == sing.
464
+ sing = -f1 * t1 / (f0 - f1)
465
+ phase = 2 * pi * (-sing * f0) * log(np.abs(1 - t/sing))
466
+
467
+ else:
468
+ raise ValueError("method must be 'linear', 'quadratic', 'logarithmic',"
469
+ " or 'hyperbolic', but a value of %r was given."
470
+ % method)
471
+
472
+ return phase
473
+
474
+
475
+ def sweep_poly(t, poly, phi=0):
476
+ """
477
+ Frequency-swept cosine generator, with a time-dependent frequency.
478
+
479
+ This function generates a sinusoidal function whose instantaneous
480
+ frequency varies with time. The frequency at time `t` is given by
481
+ the polynomial `poly`.
482
+
483
+ Parameters
484
+ ----------
485
+ t : ndarray
486
+ Times at which to evaluate the waveform.
487
+ poly : 1-D array_like or instance of numpy.poly1d
488
+ The desired frequency expressed as a polynomial. If `poly` is
489
+ a list or ndarray of length n, then the elements of `poly` are
490
+ the coefficients of the polynomial, and the instantaneous
491
+ frequency is
492
+
493
+ ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]``
494
+
495
+ If `poly` is an instance of numpy.poly1d, then the
496
+ instantaneous frequency is
497
+
498
+ ``f(t) = poly(t)``
499
+
500
+ phi : float, optional
501
+ Phase offset, in degrees, Default: 0.
502
+
503
+ Returns
504
+ -------
505
+ sweep_poly : ndarray
506
+ A numpy array containing the signal evaluated at `t` with the
507
+ requested time-varying frequency. More precisely, the function
508
+ returns ``cos(phase + (pi/180)*phi)``, where `phase` is the integral
509
+ (from 0 to t) of ``2 * pi * f(t)``; ``f(t)`` is defined above.
510
+
511
+ See Also
512
+ --------
513
+ chirp
514
+
515
+ Notes
516
+ -----
517
+ .. versionadded:: 0.8.0
518
+
519
+ If `poly` is a list or ndarray of length `n`, then the elements of
520
+ `poly` are the coefficients of the polynomial, and the instantaneous
521
+ frequency is:
522
+
523
+ ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]``
524
+
525
+ If `poly` is an instance of `numpy.poly1d`, then the instantaneous
526
+ frequency is:
527
+
528
+ ``f(t) = poly(t)``
529
+
530
+ Finally, the output `s` is:
531
+
532
+ ``cos(phase + (pi/180)*phi)``
533
+
534
+ where `phase` is the integral from 0 to `t` of ``2 * pi * f(t)``,
535
+ ``f(t)`` as defined above.
536
+
537
+ Examples
538
+ --------
539
+ Compute the waveform with instantaneous frequency::
540
+
541
+ f(t) = 0.025*t**3 - 0.36*t**2 + 1.25*t + 2
542
+
543
+ over the interval 0 <= t <= 10.
544
+
545
+ >>> import numpy as np
546
+ >>> from scipy.signal import sweep_poly
547
+ >>> p = np.poly1d([0.025, -0.36, 1.25, 2.0])
548
+ >>> t = np.linspace(0, 10, 5001)
549
+ >>> w = sweep_poly(t, p)
550
+
551
+ Plot it:
552
+
553
+ >>> import matplotlib.pyplot as plt
554
+ >>> plt.subplot(2, 1, 1)
555
+ >>> plt.plot(t, w)
556
+ >>> plt.title("Sweep Poly\\nwith frequency " +
557
+ ... "$f(t) = 0.025t^3 - 0.36t^2 + 1.25t + 2$")
558
+ >>> plt.subplot(2, 1, 2)
559
+ >>> plt.plot(t, p(t), 'r', label='f(t)')
560
+ >>> plt.legend()
561
+ >>> plt.xlabel('t')
562
+ >>> plt.tight_layout()
563
+ >>> plt.show()
564
+
565
+ """
566
+ # 'phase' is computed in _sweep_poly_phase, to make testing easier.
567
+ phase = _sweep_poly_phase(t, poly)
568
+ # Convert to radians.
569
+ phi *= pi / 180
570
+ return cos(phase + phi)
571
+
572
+
573
+ def _sweep_poly_phase(t, poly):
574
+ """
575
+ Calculate the phase used by sweep_poly to generate its output.
576
+
577
+ See `sweep_poly` for a description of the arguments.
578
+
579
+ """
580
+ # polyint handles lists, ndarrays and instances of poly1d automatically.
581
+ intpoly = polyint(poly)
582
+ phase = 2 * pi * polyval(intpoly, t)
583
+ return phase
584
+
585
+
586
+ def unit_impulse(shape, idx=None, dtype=float):
587
+ """
588
+ Unit impulse signal (discrete delta function) or unit basis vector.
589
+
590
+ Parameters
591
+ ----------
592
+ shape : int or tuple of int
593
+ Number of samples in the output (1-D), or a tuple that represents the
594
+ shape of the output (N-D).
595
+ idx : None or int or tuple of int or 'mid', optional
596
+ Index at which the value is 1. If None, defaults to the 0th element.
597
+ If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in
598
+ all dimensions. If an int, the impulse will be at `idx` in all
599
+ dimensions.
600
+ dtype : data-type, optional
601
+ The desired data-type for the array, e.g., ``numpy.int8``. Default is
602
+ ``numpy.float64``.
603
+
604
+ Returns
605
+ -------
606
+ y : ndarray
607
+ Output array containing an impulse signal.
608
+
609
+ Notes
610
+ -----
611
+ The 1D case is also known as the Kronecker delta.
612
+
613
+ .. versionadded:: 0.19.0
614
+
615
+ Examples
616
+ --------
617
+ An impulse at the 0th element (:math:`\\delta[n]`):
618
+
619
+ >>> from scipy import signal
620
+ >>> signal.unit_impulse(8)
621
+ array([ 1., 0., 0., 0., 0., 0., 0., 0.])
622
+
623
+ Impulse offset by 2 samples (:math:`\\delta[n-2]`):
624
+
625
+ >>> signal.unit_impulse(7, 2)
626
+ array([ 0., 0., 1., 0., 0., 0., 0.])
627
+
628
+ 2-dimensional impulse, centered:
629
+
630
+ >>> signal.unit_impulse((3, 3), 'mid')
631
+ array([[ 0., 0., 0.],
632
+ [ 0., 1., 0.],
633
+ [ 0., 0., 0.]])
634
+
635
+ Impulse at (2, 2), using broadcasting:
636
+
637
+ >>> signal.unit_impulse((4, 4), 2)
638
+ array([[ 0., 0., 0., 0.],
639
+ [ 0., 0., 0., 0.],
640
+ [ 0., 0., 1., 0.],
641
+ [ 0., 0., 0., 0.]])
642
+
643
+ Plot the impulse response of a 4th-order Butterworth lowpass filter:
644
+
645
+ >>> imp = signal.unit_impulse(100, 'mid')
646
+ >>> b, a = signal.butter(4, 0.2)
647
+ >>> response = signal.lfilter(b, a, imp)
648
+
649
+ >>> import numpy as np
650
+ >>> import matplotlib.pyplot as plt
651
+ >>> plt.plot(np.arange(-50, 50), imp)
652
+ >>> plt.plot(np.arange(-50, 50), response)
653
+ >>> plt.margins(0.1, 0.1)
654
+ >>> plt.xlabel('Time [samples]')
655
+ >>> plt.ylabel('Amplitude')
656
+ >>> plt.grid(True)
657
+ >>> plt.show()
658
+
659
+ """
660
+ out = zeros(shape, dtype)
661
+
662
+ shape = np.atleast_1d(shape)
663
+
664
+ if idx is None:
665
+ idx = (0,) * len(shape)
666
+ elif idx == 'mid':
667
+ idx = tuple(shape // 2)
668
+ elif not hasattr(idx, "__iter__"):
669
+ idx = (idx,) * len(shape)
670
+
671
+ out[idx] = 1
672
+ return out
llmeval-env/lib/python3.10/site-packages/scipy/signal/_wavelets.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import numpy as np
4
+ from scipy.linalg import eig
5
+ from scipy.special import comb
6
+ from scipy.signal import convolve
7
+
8
+ __all__ = ['daub', 'qmf', 'cascade', 'morlet', 'ricker', 'morlet2', 'cwt']
9
+
10
+
11
+ _msg="""scipy.signal.%s is deprecated in SciPy 1.12 and will be removed
12
+ in SciPy 1.15. We recommend using PyWavelets instead.
13
+ """
14
+
15
+
16
+ def daub(p):
17
+ """
18
+ The coefficients for the FIR low-pass filter producing Daubechies wavelets.
19
+
20
+ .. deprecated:: 1.12.0
21
+
22
+ scipy.signal.daub is deprecated in SciPy 1.12 and will be removed
23
+ in SciPy 1.15. We recommend using PyWavelets instead.
24
+
25
+ p>=1 gives the order of the zero at f=1/2.
26
+ There are 2p filter coefficients.
27
+
28
+ Parameters
29
+ ----------
30
+ p : int
31
+ Order of the zero at f=1/2, can have values from 1 to 34.
32
+
33
+ Returns
34
+ -------
35
+ daub : ndarray
36
+ Return
37
+
38
+ """
39
+ warnings.warn(_msg % 'daub', DeprecationWarning, stacklevel=2)
40
+
41
+ sqrt = np.sqrt
42
+ if p < 1:
43
+ raise ValueError("p must be at least 1.")
44
+ if p == 1:
45
+ c = 1 / sqrt(2)
46
+ return np.array([c, c])
47
+ elif p == 2:
48
+ f = sqrt(2) / 8
49
+ c = sqrt(3)
50
+ return f * np.array([1 + c, 3 + c, 3 - c, 1 - c])
51
+ elif p == 3:
52
+ tmp = 12 * sqrt(10)
53
+ z1 = 1.5 + sqrt(15 + tmp) / 6 - 1j * (sqrt(15) + sqrt(tmp - 15)) / 6
54
+ z1c = np.conj(z1)
55
+ f = sqrt(2) / 8
56
+ d0 = np.real((1 - z1) * (1 - z1c))
57
+ a0 = np.real(z1 * z1c)
58
+ a1 = 2 * np.real(z1)
59
+ return f / d0 * np.array([a0, 3 * a0 - a1, 3 * a0 - 3 * a1 + 1,
60
+ a0 - 3 * a1 + 3, 3 - a1, 1])
61
+ elif p < 35:
62
+ # construct polynomial and factor it
63
+ if p < 35:
64
+ P = [comb(p - 1 + k, k, exact=1) for k in range(p)][::-1]
65
+ yj = np.roots(P)
66
+ else: # try different polynomial --- needs work
67
+ P = [comb(p - 1 + k, k, exact=1) / 4.0**k
68
+ for k in range(p)][::-1]
69
+ yj = np.roots(P) / 4
70
+ # for each root, compute two z roots, select the one with |z|>1
71
+ # Build up final polynomial
72
+ c = np.poly1d([1, 1])**p
73
+ q = np.poly1d([1])
74
+ for k in range(p - 1):
75
+ yval = yj[k]
76
+ part = 2 * sqrt(yval * (yval - 1))
77
+ const = 1 - 2 * yval
78
+ z1 = const + part
79
+ if (abs(z1)) < 1:
80
+ z1 = const - part
81
+ q = q * [1, -z1]
82
+
83
+ q = c * np.real(q)
84
+ # Normalize result
85
+ q = q / np.sum(q) * sqrt(2)
86
+ return q.c[::-1]
87
+ else:
88
+ raise ValueError("Polynomial factorization does not work "
89
+ "well for p too large.")
90
+
91
+
92
+ def qmf(hk):
93
+ """
94
+ Return high-pass qmf filter from low-pass
95
+
96
+ .. deprecated:: 1.12.0
97
+
98
+ scipy.signal.qmf is deprecated in SciPy 1.12 and will be removed
99
+ in SciPy 1.15. We recommend using PyWavelets instead.
100
+
101
+ Parameters
102
+ ----------
103
+ hk : array_like
104
+ Coefficients of high-pass filter.
105
+
106
+ Returns
107
+ -------
108
+ array_like
109
+ High-pass filter coefficients.
110
+
111
+ """
112
+ warnings.warn(_msg % 'qmf', DeprecationWarning, stacklevel=2)
113
+
114
+ N = len(hk) - 1
115
+ asgn = [{0: 1, 1: -1}[k % 2] for k in range(N + 1)]
116
+ return hk[::-1] * np.array(asgn)
117
+
118
+
119
+ def cascade(hk, J=7):
120
+ """
121
+ Return (x, phi, psi) at dyadic points ``K/2**J`` from filter coefficients.
122
+
123
+ .. deprecated:: 1.12.0
124
+
125
+ scipy.signal.cascade is deprecated in SciPy 1.12 and will be removed
126
+ in SciPy 1.15. We recommend using PyWavelets instead.
127
+
128
+ Parameters
129
+ ----------
130
+ hk : array_like
131
+ Coefficients of low-pass filter.
132
+ J : int, optional
133
+ Values will be computed at grid points ``K/2**J``. Default is 7.
134
+
135
+ Returns
136
+ -------
137
+ x : ndarray
138
+ The dyadic points ``K/2**J`` for ``K=0...N * (2**J)-1`` where
139
+ ``len(hk) = len(gk) = N+1``.
140
+ phi : ndarray
141
+ The scaling function ``phi(x)`` at `x`:
142
+ ``phi(x) = sum(hk * phi(2x-k))``, where k is from 0 to N.
143
+ psi : ndarray, optional
144
+ The wavelet function ``psi(x)`` at `x`:
145
+ ``phi(x) = sum(gk * phi(2x-k))``, where k is from 0 to N.
146
+ `psi` is only returned if `gk` is not None.
147
+
148
+ Notes
149
+ -----
150
+ The algorithm uses the vector cascade algorithm described by Strang and
151
+ Nguyen in "Wavelets and Filter Banks". It builds a dictionary of values
152
+ and slices for quick reuse. Then inserts vectors into final vector at the
153
+ end.
154
+
155
+ """
156
+ warnings.warn(_msg % 'cascade', DeprecationWarning, stacklevel=2)
157
+
158
+ N = len(hk) - 1
159
+
160
+ if (J > 30 - np.log2(N + 1)):
161
+ raise ValueError("Too many levels.")
162
+ if (J < 1):
163
+ raise ValueError("Too few levels.")
164
+
165
+ # construct matrices needed
166
+ nn, kk = np.ogrid[:N, :N]
167
+ s2 = np.sqrt(2)
168
+ # append a zero so that take works
169
+ thk = np.r_[hk, 0]
170
+ gk = qmf(hk)
171
+ tgk = np.r_[gk, 0]
172
+
173
+ indx1 = np.clip(2 * nn - kk, -1, N + 1)
174
+ indx2 = np.clip(2 * nn - kk + 1, -1, N + 1)
175
+ m = np.empty((2, 2, N, N), 'd')
176
+ m[0, 0] = np.take(thk, indx1, 0)
177
+ m[0, 1] = np.take(thk, indx2, 0)
178
+ m[1, 0] = np.take(tgk, indx1, 0)
179
+ m[1, 1] = np.take(tgk, indx2, 0)
180
+ m *= s2
181
+
182
+ # construct the grid of points
183
+ x = np.arange(0, N * (1 << J), dtype=float) / (1 << J)
184
+ phi = 0 * x
185
+
186
+ psi = 0 * x
187
+
188
+ # find phi0, and phi1
189
+ lam, v = eig(m[0, 0])
190
+ ind = np.argmin(np.absolute(lam - 1))
191
+ # a dictionary with a binary representation of the
192
+ # evaluation points x < 1 -- i.e. position is 0.xxxx
193
+ v = np.real(v[:, ind])
194
+ # need scaling function to integrate to 1 so find
195
+ # eigenvector normalized to sum(v,axis=0)=1
196
+ sm = np.sum(v)
197
+ if sm < 0: # need scaling function to integrate to 1
198
+ v = -v
199
+ sm = -sm
200
+ bitdic = {'0': v / sm}
201
+ bitdic['1'] = np.dot(m[0, 1], bitdic['0'])
202
+ step = 1 << J
203
+ phi[::step] = bitdic['0']
204
+ phi[(1 << (J - 1))::step] = bitdic['1']
205
+ psi[::step] = np.dot(m[1, 0], bitdic['0'])
206
+ psi[(1 << (J - 1))::step] = np.dot(m[1, 1], bitdic['0'])
207
+ # descend down the levels inserting more and more values
208
+ # into bitdic -- store the values in the correct location once we
209
+ # have computed them -- stored in the dictionary
210
+ # for quicker use later.
211
+ prevkeys = ['1']
212
+ for level in range(2, J + 1):
213
+ newkeys = ['%d%s' % (xx, yy) for xx in [0, 1] for yy in prevkeys]
214
+ fac = 1 << (J - level)
215
+ for key in newkeys:
216
+ # convert key to number
217
+ num = 0
218
+ for pos in range(level):
219
+ if key[pos] == '1':
220
+ num += (1 << (level - 1 - pos))
221
+ pastphi = bitdic[key[1:]]
222
+ ii = int(key[0])
223
+ temp = np.dot(m[0, ii], pastphi)
224
+ bitdic[key] = temp
225
+ phi[num * fac::step] = temp
226
+ psi[num * fac::step] = np.dot(m[1, ii], pastphi)
227
+ prevkeys = newkeys
228
+
229
+ return x, phi, psi
230
+
231
+
232
+ def morlet(M, w=5.0, s=1.0, complete=True):
233
+ """
234
+ Complex Morlet wavelet.
235
+
236
+ .. deprecated:: 1.12.0
237
+
238
+ scipy.signal.morlet is deprecated in SciPy 1.12 and will be removed
239
+ in SciPy 1.15. We recommend using PyWavelets instead.
240
+
241
+ Parameters
242
+ ----------
243
+ M : int
244
+ Length of the wavelet.
245
+ w : float, optional
246
+ Omega0. Default is 5
247
+ s : float, optional
248
+ Scaling factor, windowed from ``-s*2*pi`` to ``+s*2*pi``. Default is 1.
249
+ complete : bool, optional
250
+ Whether to use the complete or the standard version.
251
+
252
+ Returns
253
+ -------
254
+ morlet : (M,) ndarray
255
+
256
+ See Also
257
+ --------
258
+ morlet2 : Implementation of Morlet wavelet, compatible with `cwt`.
259
+ scipy.signal.gausspulse
260
+
261
+ Notes
262
+ -----
263
+ The standard version::
264
+
265
+ pi**-0.25 * exp(1j*w*x) * exp(-0.5*(x**2))
266
+
267
+ This commonly used wavelet is often referred to simply as the
268
+ Morlet wavelet. Note that this simplified version can cause
269
+ admissibility problems at low values of `w`.
270
+
271
+ The complete version::
272
+
273
+ pi**-0.25 * (exp(1j*w*x) - exp(-0.5*(w**2))) * exp(-0.5*(x**2))
274
+
275
+ This version has a correction
276
+ term to improve admissibility. For `w` greater than 5, the
277
+ correction term is negligible.
278
+
279
+ Note that the energy of the return wavelet is not normalised
280
+ according to `s`.
281
+
282
+ The fundamental frequency of this wavelet in Hz is given
283
+ by ``f = 2*s*w*r / M`` where `r` is the sampling rate.
284
+
285
+ Note: This function was created before `cwt` and is not compatible
286
+ with it.
287
+
288
+ Examples
289
+ --------
290
+ >>> from scipy import signal
291
+ >>> import matplotlib.pyplot as plt
292
+
293
+ >>> M = 100
294
+ >>> s = 4.0
295
+ >>> w = 2.0
296
+ >>> wavelet = signal.morlet(M, s, w)
297
+ >>> plt.plot(wavelet.real, label="real")
298
+ >>> plt.plot(wavelet.imag, label="imag")
299
+ >>> plt.legend()
300
+ >>> plt.show()
301
+
302
+ """
303
+ warnings.warn(_msg % 'morlet', DeprecationWarning, stacklevel=2)
304
+
305
+ x = np.linspace(-s * 2 * np.pi, s * 2 * np.pi, M)
306
+ output = np.exp(1j * w * x)
307
+
308
+ if complete:
309
+ output -= np.exp(-0.5 * (w**2))
310
+
311
+ output *= np.exp(-0.5 * (x**2)) * np.pi**(-0.25)
312
+
313
+ return output
314
+
315
+
316
+ def ricker(points, a):
317
+ """
318
+ Return a Ricker wavelet, also known as the "Mexican hat wavelet".
319
+
320
+ .. deprecated:: 1.12.0
321
+
322
+ scipy.signal.ricker is deprecated in SciPy 1.12 and will be removed
323
+ in SciPy 1.15. We recommend using PyWavelets instead.
324
+
325
+ It models the function:
326
+
327
+ ``A * (1 - (x/a)**2) * exp(-0.5*(x/a)**2)``,
328
+
329
+ where ``A = 2/(sqrt(3*a)*(pi**0.25))``.
330
+
331
+ Parameters
332
+ ----------
333
+ points : int
334
+ Number of points in `vector`.
335
+ Will be centered around 0.
336
+ a : scalar
337
+ Width parameter of the wavelet.
338
+
339
+ Returns
340
+ -------
341
+ vector : (N,) ndarray
342
+ Array of length `points` in shape of ricker curve.
343
+
344
+ Examples
345
+ --------
346
+ >>> from scipy import signal
347
+ >>> import matplotlib.pyplot as plt
348
+
349
+ >>> points = 100
350
+ >>> a = 4.0
351
+ >>> vec2 = signal.ricker(points, a)
352
+ >>> print(len(vec2))
353
+ 100
354
+ >>> plt.plot(vec2)
355
+ >>> plt.show()
356
+
357
+ """
358
+ warnings.warn(_msg % 'ricker', DeprecationWarning, stacklevel=2)
359
+ return _ricker(points, a)
360
+
361
+
362
+ def _ricker(points, a):
363
+ A = 2 / (np.sqrt(3 * a) * (np.pi**0.25))
364
+ wsq = a**2
365
+ vec = np.arange(0, points) - (points - 1.0) / 2
366
+ xsq = vec**2
367
+ mod = (1 - xsq / wsq)
368
+ gauss = np.exp(-xsq / (2 * wsq))
369
+ total = A * mod * gauss
370
+ return total
371
+
372
+
373
+ def morlet2(M, s, w=5):
374
+ """
375
+ Complex Morlet wavelet, designed to work with `cwt`.
376
+
377
+ .. deprecated:: 1.12.0
378
+
379
+ scipy.signal.morlet2 is deprecated in SciPy 1.12 and will be removed
380
+ in SciPy 1.15. We recommend using PyWavelets instead.
381
+
382
+ Returns the complete version of morlet wavelet, normalised
383
+ according to `s`::
384
+
385
+ exp(1j*w*x/s) * exp(-0.5*(x/s)**2) * pi**(-0.25) * sqrt(1/s)
386
+
387
+ Parameters
388
+ ----------
389
+ M : int
390
+ Length of the wavelet.
391
+ s : float
392
+ Width parameter of the wavelet.
393
+ w : float, optional
394
+ Omega0. Default is 5
395
+
396
+ Returns
397
+ -------
398
+ morlet : (M,) ndarray
399
+
400
+ See Also
401
+ --------
402
+ morlet : Implementation of Morlet wavelet, incompatible with `cwt`
403
+
404
+ Notes
405
+ -----
406
+
407
+ .. versionadded:: 1.4.0
408
+
409
+ This function was designed to work with `cwt`. Because `morlet2`
410
+ returns an array of complex numbers, the `dtype` argument of `cwt`
411
+ should be set to `complex128` for best results.
412
+
413
+ Note the difference in implementation with `morlet`.
414
+ The fundamental frequency of this wavelet in Hz is given by::
415
+
416
+ f = w*fs / (2*s*np.pi)
417
+
418
+ where ``fs`` is the sampling rate and `s` is the wavelet width parameter.
419
+ Similarly we can get the wavelet width parameter at ``f``::
420
+
421
+ s = w*fs / (2*f*np.pi)
422
+
423
+ Examples
424
+ --------
425
+ >>> import numpy as np
426
+ >>> from scipy import signal
427
+ >>> import matplotlib.pyplot as plt
428
+
429
+ >>> M = 100
430
+ >>> s = 4.0
431
+ >>> w = 2.0
432
+ >>> wavelet = signal.morlet2(M, s, w)
433
+ >>> plt.plot(abs(wavelet))
434
+ >>> plt.show()
435
+
436
+ This example shows basic use of `morlet2` with `cwt` in time-frequency
437
+ analysis:
438
+
439
+ >>> t, dt = np.linspace(0, 1, 200, retstep=True)
440
+ >>> fs = 1/dt
441
+ >>> w = 6.
442
+ >>> sig = np.cos(2*np.pi*(50 + 10*t)*t) + np.sin(40*np.pi*t)
443
+ >>> freq = np.linspace(1, fs/2, 100)
444
+ >>> widths = w*fs / (2*freq*np.pi)
445
+ >>> cwtm = signal.cwt(sig, signal.morlet2, widths, w=w)
446
+ >>> plt.pcolormesh(t, freq, np.abs(cwtm), cmap='viridis', shading='gouraud')
447
+ >>> plt.show()
448
+
449
+ """
450
+ warnings.warn(_msg % 'morlet2', DeprecationWarning, stacklevel=2)
451
+
452
+ x = np.arange(0, M) - (M - 1.0) / 2
453
+ x = x / s
454
+ wavelet = np.exp(1j * w * x) * np.exp(-0.5 * x**2) * np.pi**(-0.25)
455
+ output = np.sqrt(1/s) * wavelet
456
+ return output
457
+
458
+
459
+ def cwt(data, wavelet, widths, dtype=None, **kwargs):
460
+ """
461
+ Continuous wavelet transform.
462
+
463
+ .. deprecated:: 1.12.0
464
+
465
+ scipy.signal.cwt is deprecated in SciPy 1.12 and will be removed
466
+ in SciPy 1.15. We recommend using PyWavelets instead.
467
+
468
+ Performs a continuous wavelet transform on `data`,
469
+ using the `wavelet` function. A CWT performs a convolution
470
+ with `data` using the `wavelet` function, which is characterized
471
+ by a width parameter and length parameter. The `wavelet` function
472
+ is allowed to be complex.
473
+
474
+ Parameters
475
+ ----------
476
+ data : (N,) ndarray
477
+ data on which to perform the transform.
478
+ wavelet : function
479
+ Wavelet function, which should take 2 arguments.
480
+ The first argument is the number of points that the returned vector
481
+ will have (len(wavelet(length,width)) == length).
482
+ The second is a width parameter, defining the size of the wavelet
483
+ (e.g. standard deviation of a gaussian). See `ricker`, which
484
+ satisfies these requirements.
485
+ widths : (M,) sequence
486
+ Widths to use for transform.
487
+ dtype : data-type, optional
488
+ The desired data type of output. Defaults to ``float64`` if the
489
+ output of `wavelet` is real and ``complex128`` if it is complex.
490
+
491
+ .. versionadded:: 1.4.0
492
+
493
+ kwargs
494
+ Keyword arguments passed to wavelet function.
495
+
496
+ .. versionadded:: 1.4.0
497
+
498
+ Returns
499
+ -------
500
+ cwt: (M, N) ndarray
501
+ Will have shape of (len(widths), len(data)).
502
+
503
+ Notes
504
+ -----
505
+
506
+ .. versionadded:: 1.4.0
507
+
508
+ For non-symmetric, complex-valued wavelets, the input signal is convolved
509
+ with the time-reversed complex-conjugate of the wavelet data [1].
510
+
511
+ ::
512
+
513
+ length = min(10 * width[ii], len(data))
514
+ cwt[ii,:] = signal.convolve(data, np.conj(wavelet(length, width[ii],
515
+ **kwargs))[::-1], mode='same')
516
+
517
+ References
518
+ ----------
519
+ .. [1] S. Mallat, "A Wavelet Tour of Signal Processing (3rd Edition)",
520
+ Academic Press, 2009.
521
+
522
+ Examples
523
+ --------
524
+ >>> import numpy as np
525
+ >>> from scipy import signal
526
+ >>> import matplotlib.pyplot as plt
527
+ >>> t = np.linspace(-1, 1, 200, endpoint=False)
528
+ >>> sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2)
529
+ >>> widths = np.arange(1, 31)
530
+ >>> cwtmatr = signal.cwt(sig, signal.ricker, widths)
531
+
532
+ .. note:: For cwt matrix plotting it is advisable to flip the y-axis
533
+
534
+ >>> cwtmatr_yflip = np.flipud(cwtmatr)
535
+ >>> plt.imshow(cwtmatr_yflip, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',
536
+ ... vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max())
537
+ >>> plt.show()
538
+ """
539
+ warnings.warn(_msg % 'cwt', DeprecationWarning, stacklevel=2)
540
+ return _cwt(data, wavelet, widths, dtype, **kwargs)
541
+
542
+
543
+ def _cwt(data, wavelet, widths, dtype=None, **kwargs):
544
+ # Determine output type
545
+ if dtype is None:
546
+ if np.asarray(wavelet(1, widths[0], **kwargs)).dtype.char in 'FDG':
547
+ dtype = np.complex128
548
+ else:
549
+ dtype = np.float64
550
+
551
+ output = np.empty((len(widths), len(data)), dtype=dtype)
552
+ for ind, width in enumerate(widths):
553
+ N = np.min([10 * width, len(data)])
554
+ wavelet_data = np.conj(wavelet(N, width, **kwargs)[::-1])
555
+ output[ind] = convolve(data, wavelet_data, mode='same')
556
+ return output
llmeval-env/lib/python3.10/site-packages/scipy/signal/bsplines.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.signal` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'spline_filter', 'gauss_spline',
9
+ 'cspline1d', 'qspline1d', 'cspline1d_eval', 'qspline1d_eval',
10
+ 'zeros_like', 'array', 'arctan2',
11
+ 'tan', 'arange', 'floor', 'exp', 'greater', 'add',
12
+ 'cspline2d', 'sepfir2d'
13
+ ]
14
+
15
+
16
+ def __dir__():
17
+ return __all__
18
+
19
+
20
+ def __getattr__(name):
21
+ return _sub_module_deprecation(sub_package="signal", module="bsplines",
22
+ private_modules=["_bsplines"], all=__all__,
23
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/signal/filter_design.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.signal` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize',
9
+ 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign',
10
+ 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel',
11
+ 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord',
12
+ 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap',
13
+ 'BadCoefficients', 'freqs_zpk', 'freqz_zpk',
14
+ 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay',
15
+ 'sosfreqz', 'iirnotch', 'iirpeak', 'bilinear_zpk',
16
+ 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk',
17
+ 'gammatone', 'iircomb',
18
+ 'atleast_1d', 'poly', 'polyval', 'roots', 'resize', 'absolute',
19
+ 'tan', 'log10', 'arcsinh', 'exp', 'arccosh',
20
+ 'ceil', 'conjugate', 'append', 'prod', 'full', 'array', 'mintypecode',
21
+ 'npp_polyval', 'polyvalfromroots', 'optimize', 'sp_fft', 'comb',
22
+ 'float_factorial', 'abs', 'maxflat', 'yulewalk',
23
+ 'EPSILON', 'filter_dict', 'band_dict', 'bessel_norms'
24
+ ]
25
+
26
+
27
+ def __dir__():
28
+ return __all__
29
+
30
+
31
+ def __getattr__(name):
32
+ return _sub_module_deprecation(sub_package="signal", module="filter_design",
33
+ private_modules=["_filter_design"], all=__all__,
34
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/signal/fir_filter_design.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.signal` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'kaiser_beta', 'kaiser_atten', 'kaiserord',
9
+ 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase',
10
+ 'ceil', 'log', 'irfft', 'fft', 'ifft', 'sinc', 'toeplitz',
11
+ 'hankel', 'solve', 'LinAlgError', 'LinAlgWarning', 'lstsq'
12
+ ]
13
+
14
+
15
+ def __dir__():
16
+ return __all__
17
+
18
+
19
+ def __getattr__(name):
20
+ return _sub_module_deprecation(sub_package="signal", module="fir_filter_design",
21
+ private_modules=["_fir_filter_design"], all=__all__,
22
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/signal/lti_conversion.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.signal` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk',
9
+ 'cont2discrete','eye', 'atleast_2d',
10
+ 'poly', 'prod', 'array', 'outer', 'linalg', 'tf2zpk', 'zpk2tf', 'normalize'
11
+ ]
12
+
13
+
14
+ def __dir__():
15
+ return __all__
16
+
17
+
18
+ def __getattr__(name):
19
+ return _sub_module_deprecation(sub_package="signal", module="lti_conversion",
20
+ private_modules=["_lti_conversion"], all=__all__,
21
+ attribute=name)