From dde4d42b369cb854834bf1f28ac4d19acc857c18 Mon Sep 17 00:00:00 2001 From: Travis Prescott Date: Wed, 15 Dec 2021 15:13:40 -0800 Subject: [PATCH 1/4] Regenerate SDK. --- .../azure/ai/anomalydetector/__init__.py | 9 +- .../_anomaly_detector_client.py | 61 +- .../ai/anomalydetector/_configuration.py | 9 +- .../azure/ai/anomalydetector/_patch.py | 31 + .../azure/ai/anomalydetector/_vendor.py | 27 + .../azure/ai/anomalydetector/aio/__init__.py | 5 + .../aio/_anomaly_detector_client.py | 55 +- .../ai/anomalydetector/aio/_configuration.py | 9 +- .../azure/ai/anomalydetector/aio/_patch.py | 31 + .../_anomaly_detector_client_operations.py | 577 ++++++----- .../ai/anomalydetector/models/__init__.py | 20 +- .../models/_anomaly_detector_client_enums.py | 58 +- .../ai/anomalydetector/models/_models.py | 934 ++++++++++++----- .../ai/anomalydetector/models/_models_py3.py | 965 +++++++++++++----- .../_anomaly_detector_client_operations.py | 852 +++++++++++----- 15 files changed, 2603 insertions(+), 1040 deletions(-) create mode 100644 sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_patch.py create mode 100644 sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py create mode 100644 sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_patch.py diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/__init__.py index a55b787999fc..3134fb639863 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/__init__.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/__init__.py @@ -12,8 +12,7 @@ __version__ = VERSION __all__ = ['AnomalyDetectorClient'] -try: - from ._patch import patch_sdk # type: ignore - patch_sdk() -except ImportError: - pass +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_anomaly_detector_client.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_anomaly_detector_client.py index 1a5a5e097b33..5f45a7d069de 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_anomaly_detector_client.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_anomaly_detector_client.py @@ -6,30 +6,34 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from copy import deepcopy from typing import TYPE_CHECKING from azure.core import PipelineClient from msrest import Deserializer, Serializer +from . import models +from ._configuration import AnomalyDetectorClientConfiguration +from .operations import AnomalyDetectorClientOperationsMixin + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any from azure.core.credentials import AzureKeyCredential - from azure.core.pipeline.transport import HttpRequest, HttpResponse - -from ._configuration import AnomalyDetectorClientConfiguration -from .operations import AnomalyDetectorClientOperationsMixin -from . import models - + from azure.core.rest import HttpRequest, HttpResponse class AnomalyDetectorClient(AnomalyDetectorClientOperationsMixin): """The Anomaly Detector API detects anomalies automatically in time series data. It supports two kinds of mode, one is for stateless using, another is for stateful using. In stateless mode, there are three functionalities. Entire Detect is for detecting the whole series with model trained by the time series, Last Detect is detecting last point with model trained by points before. ChangePoint Detect is for detecting trend changes in time series. In stateful mode, user can store time series, the stored time series will be used for detection anomalies. Under this mode, user can still use the above three functionalities by only giving a time range without preparing time series in client side. Besides the above three functionalities, stateful model also provide group based detection and labeling service. By leveraging labeling service user can provide labels for each detection result, these labels will be used for retuning or regenerating detection models. Inconsistency detection is a kind of group based detection, this detection will find inconsistency ones in a set of time series. By using anomaly detector service, business customers can discover incidents and establish a logic flow for root cause analysis. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.AzureKeyCredential - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). + :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + https://westus2.api.cognitive.microsoft.com). :type endpoint: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -39,33 +43,46 @@ def __init__( **kwargs # type: Any ): # type: (...) -> None - base_url = '{Endpoint}/anomalydetector/v1.1-preview' - self._config = AnomalyDetectorClientConfiguration(credential, endpoint, **kwargs) - self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs) + _base_url = '{Endpoint}/anomalydetector/{ApiVersion}' + self._config = AnomalyDetectorClientConfiguration(credential=credential, endpoint=endpoint, **kwargs) + self._client = PipelineClient(base_url=_base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False - def _send_request(self, http_request, **kwargs): - # type: (HttpRequest, Any) -> HttpResponse + def _send_request( + self, + request, # type: HttpRequest + **kwargs # type: Any + ): + # type: (...) -> HttpResponse """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.HttpResponse + :rtype: ~azure.core.rest.HttpResponse """ + + request_copy = deepcopy(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, **kwargs) def close(self): # type: () -> None diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py index 1db866bdb626..d44f17043076 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py @@ -30,6 +30,8 @@ class AnomalyDetectorClientConfiguration(Configuration): :type credential: ~azure.core.credentials.AzureKeyCredential :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). :type endpoint: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -39,14 +41,17 @@ def __init__( **kwargs # type: Any ): # type: (...) -> None + super(AnomalyDetectorClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") - super(AnomalyDetectorClientConfiguration, self).__init__(**kwargs) self.credential = credential self.endpoint = endpoint + self.api_version = api_version kwargs.setdefault('sdk_moniker', 'ai-anomalydetector/{}'.format(VERSION)) self._configure(**kwargs) @@ -65,4 +70,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AzureKeyCredentialPolicy(self.credential, 'Ocp-Apim-Subscription-Key', **kwargs) + self.authentication_policy = policies.AzureKeyCredentialPolicy(self.credential, "Ocp-Apim-Subscription-Key", **kwargs) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_patch.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_patch.py new file mode 100644 index 000000000000..74e48ecd07cf --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py new file mode 100644 index 000000000000..138f663c53a4 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.core.pipeline.transport import HttpRequest + +def _convert_request(request, files=None): + data = request.content if not files else None + request = HttpRequest(method=request.method, url=request.url, headers=request.headers, data=data) + if files: + request.set_formdata_body(files) + return request + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + formatted_components = template.split("/") + components = [ + c for c in formatted_components if "{}".format(key.args[0]) not in c + ] + template = "/".join(components) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/__init__.py index a01b4ad9ad82..b644683032c1 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/__init__.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/__init__.py @@ -8,3 +8,8 @@ from ._anomaly_detector_client import AnomalyDetectorClient __all__ = ['AnomalyDetectorClient'] + +# `._patch.py` is used for handwritten extensions to the generated code +# Example: https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +from ._patch import patch_sdk +patch_sdk() diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_anomaly_detector_client.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_anomaly_detector_client.py index e767cb886f63..cebbc49d580c 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_anomaly_detector_client.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_anomaly_detector_client.py @@ -6,25 +6,29 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from copy import deepcopy +from typing import Any, Awaitable from azure.core import AsyncPipelineClient from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.rest import AsyncHttpResponse, HttpRequest from msrest import Deserializer, Serializer +from .. import models from ._configuration import AnomalyDetectorClientConfiguration from .operations import AnomalyDetectorClientOperationsMixin -from .. import models - class AnomalyDetectorClient(AnomalyDetectorClientOperationsMixin): """The Anomaly Detector API detects anomalies automatically in time series data. It supports two kinds of mode, one is for stateless using, another is for stateful using. In stateless mode, there are three functionalities. Entire Detect is for detecting the whole series with model trained by the time series, Last Detect is detecting last point with model trained by points before. ChangePoint Detect is for detecting trend changes in time series. In stateful mode, user can store time series, the stored time series will be used for detection anomalies. Under this mode, user can still use the above three functionalities by only giving a time range without preparing time series in client side. Besides the above three functionalities, stateful model also provide group based detection and labeling service. By leveraging labeling service user can provide labels for each detection result, these labels will be used for retuning or regenerating detection models. Inconsistency detection is a kind of group based detection, this detection will find inconsistency ones in a set of time series. By using anomaly detector service, business customers can discover incidents and establish a logic flow for root cause analysis. :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.AzureKeyCredential - :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). + :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: + https://westus2.api.cognitive.microsoft.com). :type endpoint: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -33,32 +37,45 @@ def __init__( endpoint: str, **kwargs: Any ) -> None: - base_url = '{Endpoint}/anomalydetector/v1.1-preview' - self._config = AnomalyDetectorClientConfiguration(credential, endpoint, **kwargs) - self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) + _base_url = '{Endpoint}/anomalydetector/{ApiVersion}' + self._config = AnomalyDetectorClientConfiguration(credential=credential, endpoint=endpoint, **kwargs) + self._client = AsyncPipelineClient(base_url=_base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) - self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False - async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: + def _send_request( + self, + request: HttpRequest, + **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. - :param http_request: The network request you want to make. Required. - :type http_request: ~azure.core.pipeline.transport.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to True. + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client._send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse + :rtype: ~azure.core.rest.AsyncHttpResponse """ + + request_copy = deepcopy(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - http_request.url = self._client.format_url(http_request.url, **path_format_arguments) - stream = kwargs.pop("stream", True) - pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) - return pipeline_response.http_response + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py index 1554cc3e4cc6..6fae84c7db5c 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration.py @@ -25,6 +25,8 @@ class AnomalyDetectorClientConfiguration(Configuration): :type credential: ~azure.core.credentials.AzureKeyCredential :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com). :type endpoint: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -33,14 +35,17 @@ def __init__( endpoint: str, **kwargs: Any ) -> None: + super(AnomalyDetectorClientConfiguration, self).__init__(**kwargs) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + if credential is None: raise ValueError("Parameter 'credential' must not be None.") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") - super(AnomalyDetectorClientConfiguration, self).__init__(**kwargs) self.credential = credential self.endpoint = endpoint + self.api_version = api_version kwargs.setdefault('sdk_moniker', 'ai-anomalydetector/{}'.format(VERSION)) self._configure(**kwargs) @@ -58,4 +63,4 @@ def _configure( self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AzureKeyCredentialPolicy(self.credential, 'Ocp-Apim-Subscription-Key', **kwargs) + self.authentication_policy = policies.AzureKeyCredentialPolicy(self.credential, "Ocp-Apim-Subscription-Key", **kwargs) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_patch.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_patch.py new file mode 100644 index 000000000000..74e48ecd07cf --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_patch.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# This file is used for handwritten extensions to the generated code. Example: +# https://github.com/Azure/azure-sdk-for-python/blob/main/doc/dev/customize_code/how-to-patch-sdk-code.md +def patch_sdk(): + pass \ No newline at end of file diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations/_anomaly_detector_client_operations.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations/_anomaly_detector_client_operations.py index 2115a246633a..6294a30a38f2 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations/_anomaly_detector_client_operations.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations/_anomaly_detector_client_operations.py @@ -5,25 +5,31 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import functools from typing import Any, AsyncIterable, Callable, Dict, Generic, IO, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest +from azure.core.pipeline.transport import AsyncHttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from azure.core.tracing.decorator_async import distributed_trace_async from ... import models as _models - +from ..._vendor import _convert_request +from ...operations._anomaly_detector_client_operations import build_delete_multivariate_model_request, build_detect_anomaly_request, build_detect_change_point_request, build_detect_entire_series_request, build_detect_last_point_request, build_export_model_request, build_get_detection_result_request, build_get_multivariate_model_request, build_last_detect_anomaly_request, build_list_multivariate_model_request, build_train_multivariate_model_request T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class AnomalyDetectorClientOperationsMixin: + @distributed_trace_async async def detect_entire_series( self, body: "_models.DetectRequest", - **kwargs + **kwargs: Any ) -> "_models.EntireDetectResponse": """Detect anomalies for the entire series in batch. @@ -34,6 +40,9 @@ async def detect_entire_series( :param body: Time series points and period if needed. Advanced model parameters can also be set in the request. :type body: ~azure.ai.anomalydetector.models.DetectRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: EntireDetectResponse, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.EntireDetectResponse @@ -44,34 +53,30 @@ async def detect_entire_series( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_entire_series.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'DetectRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_entire_series_request( + content_type=content_type, + json=_json, + template_url=self.detect_entire_series.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(body, 'DetectRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, response) + error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('EntireDetectResponse', pipeline_response) @@ -80,12 +85,15 @@ async def detect_entire_series( return cls(pipeline_response, deserialized, {}) return deserialized + detect_entire_series.metadata = {'url': '/timeseries/entire/detect'} # type: ignore + + @distributed_trace_async async def detect_last_point( self, body: "_models.DetectRequest", - **kwargs + **kwargs: Any ) -> "_models.LastDetectResponse": """Detect anomaly status of the latest point in time series. @@ -96,6 +104,9 @@ async def detect_last_point( :param body: Time series points and period if needed. Advanced model parameters can also be set in the request. :type body: ~azure.ai.anomalydetector.models.DetectRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: LastDetectResponse, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.LastDetectResponse @@ -106,34 +117,30 @@ async def detect_last_point( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_last_point.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'DetectRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_last_point_request( + content_type=content_type, + json=_json, + template_url=self.detect_last_point.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(body, 'DetectRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, response) + error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('LastDetectResponse', pipeline_response) @@ -142,12 +149,15 @@ async def detect_last_point( return cls(pipeline_response, deserialized, {}) return deserialized + detect_last_point.metadata = {'url': '/timeseries/last/detect'} # type: ignore + + @distributed_trace_async async def detect_change_point( self, body: "_models.ChangePointDetectRequest", - **kwargs + **kwargs: Any ) -> "_models.ChangePointDetectResponse": """Detect change point for the entire series. @@ -156,6 +166,9 @@ async def detect_change_point( :param body: Time series points and granularity is needed. Advanced model parameters can also be set in the request if needed. :type body: ~azure.ai.anomalydetector.models.ChangePointDetectRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ChangePointDetectResponse, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.ChangePointDetectResponse @@ -166,34 +179,30 @@ async def detect_change_point( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_change_point.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'ChangePointDetectRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_change_point_request( + content_type=content_type, + json=_json, + template_url=self.detect_change_point.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(body, 'ChangePointDetectRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, response) + error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('ChangePointDetectResponse', pipeline_response) @@ -202,12 +211,15 @@ async def detect_change_point( return cls(pipeline_response, deserialized, {}) return deserialized + detect_change_point.metadata = {'url': '/timeseries/changepoint/detect'} # type: ignore + + @distributed_trace_async async def train_multivariate_model( self, - model_request: "_models.ModelInfo", - **kwargs + body: "_models.ModelInfo", + **kwargs: Any ) -> None: """Train a Multivariate Anomaly Detection Model. @@ -217,8 +229,11 @@ async def train_multivariate_model( Each time-series will be in a single CSV file in which the first column is timestamp and the second column is value. - :param model_request: Training request. - :type model_request: ~azure.ai.anomalydetector.models.ModelInfo + :param body: Training request. + :type body: ~azure.ai.anomalydetector.models.ModelInfo + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None @@ -229,48 +244,139 @@ async def train_multivariate_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.train_multivariate_model.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'ModelInfo') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_train_multivariate_model_request( + content_type=content_type, + json=_json, + template_url=self.train_multivariate_model.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(model_request, 'ModelInfo') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Location']=self._deserialize('str', response.headers.get('Location')) + if cls: return cls(pipeline_response, None, response_headers) train_multivariate_model.metadata = {'url': '/multivariate/models'} # type: ignore + + @distributed_trace + def list_multivariate_model( + self, + skip: Optional[int] = 0, + top: Optional[int] = 5, + **kwargs: Any + ) -> AsyncIterable["_models.ModelList"]: + """List Multivariate Models. + + List models of a subscription. + + :param skip: $skip indicates how many models will be skipped. + :type skip: int + :param top: $top indicates how many models will be fetched. + :type top: int + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ModelList or the result of cls(response) + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.anomalydetector.models.ModelList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + cls = kwargs.pop('cls', None) # type: ClsType["_models.ModelList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_multivariate_model_request( + skip=skip, + top=top, + template_url=self.list_multivariate_model.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) + + else: + + request = build_list_multivariate_model_request( + skip=skip, + top=top, + template_url=next_link, + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) + + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.method = "GET" + return request + + async def extract_data(pipeline_response): + deserialized = self._deserialize("ModelList", pipeline_response) + list_of_elem = deserialized.models + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + + return AsyncItemPaged( + get_next, extract_data + ) + list_multivariate_model.metadata = {'url': '/multivariate/models'} # type: ignore + + @distributed_trace_async async def get_multivariate_model( self, model_id: str, - **kwargs + **kwargs: Any ) -> "_models.Model": """Get Multivariate Model. @@ -279,6 +385,9 @@ async def get_multivariate_model( :param model_id: Model identifier. :type model_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Model, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.Model @@ -289,30 +398,27 @@ async def get_multivariate_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - # Construct URL - url = self.get_multivariate_model.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_get_multivariate_model_request( + model_id=model_id, + template_url=self.get_multivariate_model.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('Model', pipeline_response) @@ -321,12 +427,15 @@ async def get_multivariate_model( return cls(pipeline_response, deserialized, {}) return deserialized + get_multivariate_model.metadata = {'url': '/multivariate/models/{modelId}'} # type: ignore + + @distributed_trace_async async def delete_multivariate_model( self, model_id: str, - **kwargs + **kwargs: Any ) -> None: """Delete Multivariate Model. @@ -334,6 +443,9 @@ async def delete_multivariate_model( :param model_id: Model identifier. :type model_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None @@ -344,30 +456,27 @@ async def delete_multivariate_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - # Construct URL - url = self.delete_multivariate_model.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_delete_multivariate_model_request( + model_id=model_id, + template_url=self.delete_multivariate_model.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request.url = self._client.format_url(request.url, **path_format_arguments) - request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: @@ -375,11 +484,13 @@ async def delete_multivariate_model( delete_multivariate_model.metadata = {'url': '/multivariate/models/{modelId}'} # type: ignore + + @distributed_trace_async async def detect_anomaly( self, model_id: str, - detection_request: "_models.DetectionRequest", - **kwargs + body: "_models.DetectionRequest", + **kwargs: Any ) -> None: """Detect Multivariate Anomaly. @@ -392,8 +503,11 @@ async def detect_anomaly( :param model_id: Model identifier. :type model_id: str - :param detection_request: Detect anomaly request. - :type detection_request: ~azure.ai.anomalydetector.models.DetectionRequest + :param body: Detect anomaly request. + :type body: ~azure.ai.anomalydetector.models.DetectionRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None @@ -404,49 +518,48 @@ async def detect_anomaly( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_anomaly.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'DetectionRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_anomaly_request( + model_id=model_id, + content_type=content_type, + json=_json, + template_url=self.detect_anomaly.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(detection_request, 'DetectionRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Location']=self._deserialize('str', response.headers.get('Location')) + if cls: return cls(pipeline_response, None, response_headers) detect_anomaly.metadata = {'url': '/multivariate/models/{modelId}/detect'} # type: ignore + + @distributed_trace_async async def get_detection_result( self, result_id: str, - **kwargs + **kwargs: Any ) -> "_models.DetectionResult": """Get Multivariate Anomaly Detection Result. @@ -455,6 +568,9 @@ async def get_detection_result( :param result_id: Result identifier. :type result_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DetectionResult, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.DetectionResult @@ -465,30 +581,27 @@ async def get_detection_result( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - # Construct URL - url = self.get_detection_result.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_get_detection_result_request( + result_id=result_id, + template_url=self.get_detection_result.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'resultId': self._serialize.url("result_id", result_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + request.url = self._client.format_url(request.url, **path_format_arguments) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('DetectionResult', pipeline_response) @@ -497,12 +610,15 @@ async def get_detection_result( return cls(pipeline_response, deserialized, {}) return deserialized + get_detection_result.metadata = {'url': '/multivariate/results/{resultId}'} # type: ignore + + @distributed_trace_async async def export_model( self, model_id: str, - **kwargs + **kwargs: Any ) -> IO: """Export Multivariate Anomaly Detection Model as Zip file. @@ -510,6 +626,9 @@ async def export_model( :param model_id: Model identifier. :type model_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: IO, or the result of cls(response) :rtype: IO @@ -520,118 +639,100 @@ async def export_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/zip" - # Construct URL - url = self.export_model.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_export_model_request( + model_id=model_id, + template_url=self.export_model.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + request.url = self._client.format_url(request.url, **path_format_arguments) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=True, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) - response_headers = {} - response_headers['content-type']=self._deserialize('str', response.headers.get('content-type')) deserialized = response.stream_download(self._client._pipeline) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, {}) return deserialized + export_model.metadata = {'url': '/multivariate/models/{modelId}/export'} # type: ignore - def list_multivariate_model( + + @distributed_trace_async + async def last_detect_anomaly( self, - skip: Optional[int] = 0, - top: Optional[int] = 5, - **kwargs - ) -> AsyncIterable["_models.ModelList"]: - """List Multivariate Models. + model_id: str, + body: "_models.LastDetectionRequest", + **kwargs: Any + ) -> "_models.LastDetectionResult": + """Detect anomalies in the last a few points of the request body. - List models of a subscription. + Synchronized API for anomaly detection. - :param skip: $skip indicates how many models will be skipped. - :type skip: int - :param top: $top indicates how many models will be fetched. - :type top: int + :param model_id: Model identifier. + :type model_id: str + :param body: Request for last detection. + :type body: ~azure.ai.anomalydetector.models.LastDetectionRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ModelList or the result of cls(response) - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.anomalydetector.models.ModelList] + :return: LastDetectionResult, or the result of cls(response) + :rtype: ~azure.ai.anomalydetector.models.LastDetectionResult :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ModelList"] + cls = kwargs.pop('cls', None) # type: ClsType["_models.LastDetectionResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - if not next_link: - # Construct URL - url = self.list_multivariate_model.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if skip is not None: - query_parameters['$skip'] = self._serialize.query("skip", skip, 'int') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - - request = self._client.get(url, query_parameters, header_parameters) - else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - request = self._client.get(url, query_parameters, header_parameters) - return request + _json = self._serialize.body(body, 'LastDetectionRequest') - async def extract_data(pipeline_response): - deserialized = self._deserialize('ModelList', pipeline_response) - list_of_elem = deserialized.models - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, AsyncList(list_of_elem) + request = build_last_detect_anomaly_request( + model_id=model_id, + content_type=content_type, + json=_json, + template_url=self.last_detect_anomaly.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - async def get_next(next_link=None): - request = prepare_request(next_link) + pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error) + deserialized = self._deserialize('LastDetectionResult', pipeline_response) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + last_detect_anomaly.metadata = {'url': '/multivariate/models/{modelId}/last/detect'} # type: ignore - return AsyncItemPaged( - get_next, extract_data - ) - list_multivariate_model.metadata = {'url': '/multivariate/models'} # type: ignore diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py index 62062731c9f0..b9040ec2873e 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py @@ -8,12 +8,13 @@ try: from ._models_py3 import AlignPolicy - from ._models_py3 import AnomalyContributor from ._models_py3 import AnomalyDetectorError + from ._models_py3 import AnomalyInterpretation from ._models_py3 import AnomalyState from ._models_py3 import AnomalyValue from ._models_py3 import ChangePointDetectRequest from ._models_py3 import ChangePointDetectResponse + from ._models_py3 import CorrelationChanges from ._models_py3 import DetectRequest from ._models_py3 import DetectionRequest from ._models_py3 import DetectionResult @@ -22,6 +23,8 @@ from ._models_py3 import EntireDetectResponse from ._models_py3 import ErrorResponse from ._models_py3 import LastDetectResponse + from ._models_py3 import LastDetectionRequest + from ._models_py3 import LastDetectionResult from ._models_py3 import Model from ._models_py3 import ModelInfo from ._models_py3 import ModelList @@ -29,14 +32,16 @@ from ._models_py3 import ModelState from ._models_py3 import TimeSeriesPoint from ._models_py3 import VariableState + from ._models_py3 import VariableValues except (SyntaxError, ImportError): from ._models import AlignPolicy # type: ignore - from ._models import AnomalyContributor # type: ignore from ._models import AnomalyDetectorError # type: ignore + from ._models import AnomalyInterpretation # type: ignore from ._models import AnomalyState # type: ignore from ._models import AnomalyValue # type: ignore from ._models import ChangePointDetectRequest # type: ignore from ._models import ChangePointDetectResponse # type: ignore + from ._models import CorrelationChanges # type: ignore from ._models import DetectRequest # type: ignore from ._models import DetectionRequest # type: ignore from ._models import DetectionResult # type: ignore @@ -45,6 +50,8 @@ from ._models import EntireDetectResponse # type: ignore from ._models import ErrorResponse # type: ignore from ._models import LastDetectResponse # type: ignore + from ._models import LastDetectionRequest # type: ignore + from ._models import LastDetectionResult # type: ignore from ._models import Model # type: ignore from ._models import ModelInfo # type: ignore from ._models import ModelList # type: ignore @@ -52,24 +59,27 @@ from ._models import ModelState # type: ignore from ._models import TimeSeriesPoint # type: ignore from ._models import VariableState # type: ignore + from ._models import VariableValues # type: ignore from ._anomaly_detector_client_enums import ( AlignMode, AnomalyDetectorErrorCodes, DetectionStatus, FillNAMethod, + ImputeMode, ModelStatus, TimeGranularity, ) __all__ = [ 'AlignPolicy', - 'AnomalyContributor', 'AnomalyDetectorError', + 'AnomalyInterpretation', 'AnomalyState', 'AnomalyValue', 'ChangePointDetectRequest', 'ChangePointDetectResponse', + 'CorrelationChanges', 'DetectRequest', 'DetectionRequest', 'DetectionResult', @@ -78,6 +88,8 @@ 'EntireDetectResponse', 'ErrorResponse', 'LastDetectResponse', + 'LastDetectionRequest', + 'LastDetectionResult', 'Model', 'ModelInfo', 'ModelList', @@ -85,10 +97,12 @@ 'ModelState', 'TimeSeriesPoint', 'VariableState', + 'VariableValues', 'AlignMode', 'AnomalyDetectorErrorCodes', 'DetectionStatus', 'FillNAMethod', + 'ImputeMode', 'ModelStatus', 'TimeGranularity', ] diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_anomaly_detector_client_enums.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_anomaly_detector_client_enums.py index aad093d58a43..38411bb0081d 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_anomaly_detector_client_enums.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_anomaly_detector_client_enums.py @@ -6,35 +6,20 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from enum import Enum, EnumMeta +from enum import Enum from six import with_metaclass +from azure.core import CaseInsensitiveEnumMeta -class _CaseInsensitiveEnumMeta(EnumMeta): - def __getitem__(self, name): - return super().__getitem__(name.upper()) - - def __getattr__(cls, name): - """Return the enum member matching `name` - We use __getattr__ instead of descriptors or inserting into the enum - class' __dict__ in order to support `name` and `value` being both - properties for enum members (which live in the class' __dict__) and - enum members themselves. - """ - try: - return cls._member_map_[name.upper()] - except KeyError: - raise AttributeError(name) - - -class AlignMode(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """An optional field, indicates how we align different variables into the same time-range which is - required by the model.{Inner, Outer} + +class AlignMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """An optional field, indicating how we align different variables to the same time-range. Either + Inner or Outer. """ INNER = "Inner" OUTER = "Outer" -class AnomalyDetectorErrorCodes(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class AnomalyDetectorErrorCodes(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """The error code. """ @@ -47,9 +32,11 @@ class AnomalyDetectorErrorCodes(with_metaclass(_CaseInsensitiveEnumMeta, str, En INVALID_JSON_FORMAT = "InvalidJsonFormat" REQUIRED_GRANULARITY = "RequiredGranularity" REQUIRED_SERIES = "RequiredSeries" + INVALID_IMPUTE_MODE = "InvalidImputeMode" + INVALID_IMPUTE_FIXED_VALUE = "InvalidImputeFixedValue" -class DetectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """Multivariate anomaly detection status +class DetectionStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Status of detection results. One of CREATED, RUNNING, READY, and FAILED. """ CREATED = "CREATED" @@ -57,19 +44,30 @@ class DetectionStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): READY = "READY" FAILED = "FAILED" -class FillNAMethod(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): - """An optional field, indicates how missed values will be filled with. Can not be set to NotFill, - when alignMode is Outer.{Previous, Subsequent, Linear, Zero, Fix, NotFill} +class FillNAMethod(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """An optional field, indicating how missing values will be filled. One of Previous, Subsequent, + Linear, Zero, Fixed, and NotFill. Cannot be set to NotFill, when the alignMode is Outer. """ PREVIOUS = "Previous" SUBSEQUENT = "Subsequent" LINEAR = "Linear" ZERO = "Zero" - PAD = "Pad" + FIXED = "Fixed" NOT_FILL = "NotFill" -class ModelStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class ImputeMode(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): + """Define the impute method, can be one of auto, previous, linear, fixed, zero, notFill. + """ + + AUTO = "auto" + PREVIOUS = "previous" + LINEAR = "linear" + FIXED = "fixed" + ZERO = "zero" + NOT_FILL = "notFill" + +class ModelStatus(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """Model training status. """ @@ -78,7 +76,7 @@ class ModelStatus(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): READY = "READY" FAILED = "FAILED" -class TimeGranularity(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): +class TimeGranularity(with_metaclass(CaseInsensitiveEnumMeta, str, Enum)): """Optional argument, can be one of yearly, monthly, weekly, daily, hourly, minutely, secondly, microsecond or none. If granularity is not present, it will be none by default. If granularity is none, the timestamp property in time series point can be absent. diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py index 3b435cae1a7e..f970cebd6f0a 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py @@ -13,86 +13,114 @@ class AlignPolicy(msrest.serialization.Model): """AlignPolicy. - :param align_mode: An optional field, indicates how we align different variables into the same - time-range which is required by the model.{Inner, Outer}. Possible values include: "Inner", - "Outer". - :type align_mode: str or ~azure.ai.anomalydetector.models.AlignMode - :param fill_na_method: An optional field, indicates how missed values will be filled with. Can - not be set to NotFill, when alignMode is Outer.{Previous, Subsequent, Linear, Zero, Fix, - NotFill}. Possible values include: "Previous", "Subsequent", "Linear", "Zero", "Pad", - "NotFill". - :type fill_na_method: str or ~azure.ai.anomalydetector.models.FillNAMethod - :param padding_value: optional field, only be useful if FillNAMethod is set to Pad. - :type padding_value: int + :ivar align_mode: An optional field, indicating how we align different variables to the same + time-range. Either Inner or Outer. Possible values include: "Inner", "Outer". + :vartype align_mode: str or ~azure.ai.anomalydetector.models.AlignMode + :ivar fill_na_method: An optional field, indicating how missing values will be filled. One of + Previous, Subsequent, Linear, Zero, Fixed, and NotFill. Cannot be set to NotFill, when the + alignMode is Outer. Possible values include: "Previous", "Subsequent", "Linear", "Zero", + "Fixed", "NotFill". + :vartype fill_na_method: str or ~azure.ai.anomalydetector.models.FillNAMethod + :ivar padding_value: An optional field. Required when fillNAMethod is Fixed. + :vartype padding_value: float """ _attribute_map = { 'align_mode': {'key': 'alignMode', 'type': 'str'}, 'fill_na_method': {'key': 'fillNAMethod', 'type': 'str'}, - 'padding_value': {'key': 'paddingValue', 'type': 'int'}, + 'padding_value': {'key': 'paddingValue', 'type': 'float'}, } def __init__( self, **kwargs ): + """ + :keyword align_mode: An optional field, indicating how we align different variables to the same + time-range. Either Inner or Outer. Possible values include: "Inner", "Outer". + :paramtype align_mode: str or ~azure.ai.anomalydetector.models.AlignMode + :keyword fill_na_method: An optional field, indicating how missing values will be filled. One + of Previous, Subsequent, Linear, Zero, Fixed, and NotFill. Cannot be set to NotFill, when the + alignMode is Outer. Possible values include: "Previous", "Subsequent", "Linear", "Zero", + "Fixed", "NotFill". + :paramtype fill_na_method: str or ~azure.ai.anomalydetector.models.FillNAMethod + :keyword padding_value: An optional field. Required when fillNAMethod is Fixed. + :paramtype padding_value: float + """ super(AlignPolicy, self).__init__(**kwargs) self.align_mode = kwargs.get('align_mode', None) self.fill_na_method = kwargs.get('fill_na_method', None) self.padding_value = kwargs.get('padding_value', None) -class AnomalyContributor(msrest.serialization.Model): - """AnomalyContributor. +class AnomalyDetectorError(msrest.serialization.Model): + """Error information returned by the API. - :param contribution_score: The higher the contribution score is, the more likely the variable - to be the root cause of a anomaly. - :type contribution_score: float - :param variable: Variable name of a contributor. - :type variable: str + :ivar code: The error code. Possible values include: "InvalidCustomInterval", "BadArgument", + "InvalidGranularity", "InvalidPeriod", "InvalidModelArgument", "InvalidSeries", + "InvalidJsonFormat", "RequiredGranularity", "RequiredSeries", "InvalidImputeMode", + "InvalidImputeFixedValue". + :vartype code: str or ~azure.ai.anomalydetector.models.AnomalyDetectorErrorCodes + :ivar message: A message explaining the error reported by the service. + :vartype message: str """ - _validation = { - 'contribution_score': {'maximum': 2, 'minimum': 0}, - } - _attribute_map = { - 'contribution_score': {'key': 'contributionScore', 'type': 'float'}, - 'variable': {'key': 'variable', 'type': 'str'}, + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, } def __init__( self, **kwargs ): - super(AnomalyContributor, self).__init__(**kwargs) - self.contribution_score = kwargs.get('contribution_score', None) - self.variable = kwargs.get('variable', None) + """ + :keyword code: The error code. Possible values include: "InvalidCustomInterval", "BadArgument", + "InvalidGranularity", "InvalidPeriod", "InvalidModelArgument", "InvalidSeries", + "InvalidJsonFormat", "RequiredGranularity", "RequiredSeries", "InvalidImputeMode", + "InvalidImputeFixedValue". + :paramtype code: str or ~azure.ai.anomalydetector.models.AnomalyDetectorErrorCodes + :keyword message: A message explaining the error reported by the service. + :paramtype message: str + """ + super(AnomalyDetectorError, self).__init__(**kwargs) + self.code = kwargs.get('code', None) + self.message = kwargs.get('message', None) -class AnomalyDetectorError(msrest.serialization.Model): - """Error information returned by the API. +class AnomalyInterpretation(msrest.serialization.Model): + """AnomalyInterpretation. - :param code: The error code. Possible values include: "InvalidCustomInterval", "BadArgument", - "InvalidGranularity", "InvalidPeriod", "InvalidModelArgument", "InvalidSeries", - "InvalidJsonFormat", "RequiredGranularity", "RequiredSeries". - :type code: str or ~azure.ai.anomalydetector.models.AnomalyDetectorErrorCodes - :param message: A message explaining the error reported by the service. - :type message: str + :ivar variable: + :vartype variable: str + :ivar contribution_score: + :vartype contribution_score: float + :ivar correlation_changes: + :vartype correlation_changes: ~azure.ai.anomalydetector.models.CorrelationChanges """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + 'variable': {'key': 'variable', 'type': 'str'}, + 'contribution_score': {'key': 'contributionScore', 'type': 'float'}, + 'correlation_changes': {'key': 'correlationChanges', 'type': 'CorrelationChanges'}, } def __init__( self, **kwargs ): - super(AnomalyDetectorError, self).__init__(**kwargs) - self.code = kwargs.get('code', None) - self.message = kwargs.get('message', None) + """ + :keyword variable: + :paramtype variable: str + :keyword contribution_score: + :paramtype contribution_score: float + :keyword correlation_changes: + :paramtype correlation_changes: ~azure.ai.anomalydetector.models.CorrelationChanges + """ + super(AnomalyInterpretation, self).__init__(**kwargs) + self.variable = kwargs.get('variable', None) + self.contribution_score = kwargs.get('contribution_score', None) + self.correlation_changes = kwargs.get('correlation_changes', None) class AnomalyState(msrest.serialization.Model): @@ -100,12 +128,12 @@ class AnomalyState(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param timestamp: Required. timestamp. - :type timestamp: ~datetime.datetime - :param value: - :type value: ~azure.ai.anomalydetector.models.AnomalyValue - :param errors: Error message when inference this timestamp. - :type errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar timestamp: Required. timestamp. + :vartype timestamp: ~datetime.datetime + :ivar value: + :vartype value: ~azure.ai.anomalydetector.models.AnomalyValue + :ivar errors: Error message for the current timestamp. + :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] """ _validation = { @@ -122,6 +150,14 @@ def __init__( self, **kwargs ): + """ + :keyword timestamp: Required. timestamp. + :paramtype timestamp: ~datetime.datetime + :keyword value: + :paramtype value: ~azure.ai.anomalydetector.models.AnomalyValue + :keyword errors: Error message for the current timestamp. + :paramtype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + """ super(AnomalyState, self).__init__(**kwargs) self.timestamp = kwargs['timestamp'] self.value = kwargs.get('value', None) @@ -133,70 +169,78 @@ class AnomalyValue(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param contributors: If current timestamp is an anomaly, contributors will show potential root - cause for thus anomaly. Contributors can help us understand why current timestamp has been - detected as an anomaly. - :type contributors: list[~azure.ai.anomalydetector.models.AnomalyContributor] - :param is_anomaly: Required. To indicate whether current timestamp is anomaly or not. - :type is_anomaly: bool - :param severity: Required. anomaly score of the current timestamp, the more significant an - anomaly is, the higher the score will be. - :type severity: float - :param score: anomaly score of the current timestamp, the more significant an anomaly is, the - higher the score will be, score measures global significance. - :type score: float + :ivar is_anomaly: Required. True if an anomaly is detected at the current timestamp. + :vartype is_anomaly: bool + :ivar severity: Required. Indicates the significance of the anomaly. The higher the severity, + the more significant the anomaly. + :vartype severity: float + :ivar score: Required. Raw score from the model. + :vartype score: float + :ivar interpretation: + :vartype interpretation: list[~azure.ai.anomalydetector.models.AnomalyInterpretation] """ _validation = { 'is_anomaly': {'required': True}, 'severity': {'required': True, 'maximum': 1, 'minimum': 0}, - 'score': {'maximum': 2, 'minimum': 0}, + 'score': {'required': True, 'maximum': 2, 'minimum': 0}, } _attribute_map = { - 'contributors': {'key': 'contributors', 'type': '[AnomalyContributor]'}, 'is_anomaly': {'key': 'isAnomaly', 'type': 'bool'}, 'severity': {'key': 'severity', 'type': 'float'}, 'score': {'key': 'score', 'type': 'float'}, + 'interpretation': {'key': 'interpretation', 'type': '[AnomalyInterpretation]'}, } def __init__( self, **kwargs ): + """ + :keyword is_anomaly: Required. True if an anomaly is detected at the current timestamp. + :paramtype is_anomaly: bool + :keyword severity: Required. Indicates the significance of the anomaly. The higher the + severity, the more significant the anomaly. + :paramtype severity: float + :keyword score: Required. Raw score from the model. + :paramtype score: float + :keyword interpretation: + :paramtype interpretation: list[~azure.ai.anomalydetector.models.AnomalyInterpretation] + """ super(AnomalyValue, self).__init__(**kwargs) - self.contributors = kwargs.get('contributors', None) self.is_anomaly = kwargs['is_anomaly'] self.severity = kwargs['severity'] - self.score = kwargs.get('score', None) + self.score = kwargs['score'] + self.interpretation = kwargs.get('interpretation', None) class ChangePointDetectRequest(msrest.serialization.Model): - """ChangePointDetectRequest. + """The request of change point detection. All required parameters must be populated in order to send to Azure. - :param series: Required. Time series data points. Points should be sorted by timestamp in + :ivar series: Required. Time series data points. Points should be sorted by timestamp in ascending order to match the change point detection result. - :type series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] - :param granularity: Required. Can only be one of yearly, monthly, weekly, daily, hourly, + :vartype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :ivar granularity: Required. Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid. Possible values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", "none". - :type granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity - :param custom_interval: Custom Interval is used to set non-standard time interval, for example, + :vartype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :ivar custom_interval: Custom Interval is used to set non-standard time interval, for example, if the series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}. - :type custom_interval: int - :param period: Optional argument, periodic value of a time series. If the value is null or does + :vartype custom_interval: int + :ivar period: Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - :type period: int - :param stable_trend_window: Optional argument, advanced model parameter, a default + :vartype period: int + :ivar stable_trend_window: Optional argument, advanced model parameter, a default stableTrendWindow will be used in detection. - :type stable_trend_window: int - :param threshold: Optional argument, advanced model parameter, between 0.0-1.0, the lower the + :vartype stable_trend_window: int + :ivar threshold: Optional argument, advanced model parameter, between 0.0-1.0, the lower the value is, the larger the trend error will be which means less change point will be accepted. - :type threshold: float + :vartype threshold: float """ _validation = { @@ -217,6 +261,29 @@ def __init__( self, **kwargs ): + """ + :keyword series: Required. Time series data points. Points should be sorted by timestamp in + ascending order to match the change point detection result. + :paramtype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :keyword granularity: Required. Can only be one of yearly, monthly, weekly, daily, hourly, + minutely or secondly. Granularity is used for verify whether input series is valid. Possible + values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", + "microsecond", "none". + :paramtype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :keyword custom_interval: Custom Interval is used to set non-standard time interval, for + example, if the series is 5 minutes, request can be set as {"granularity":"minutely", + "customInterval":5}. + :paramtype custom_interval: int + :keyword period: Optional argument, periodic value of a time series. If the value is null or + does not present, the API will determine the period automatically. + :paramtype period: int + :keyword stable_trend_window: Optional argument, advanced model parameter, a default + stableTrendWindow will be used in detection. + :paramtype stable_trend_window: int + :keyword threshold: Optional argument, advanced model parameter, between 0.0-1.0, the lower the + value is, the larger the trend error will be which means less change point will be accepted. + :paramtype threshold: float + """ super(ChangePointDetectRequest, self).__init__(**kwargs) self.series = kwargs['series'] self.granularity = kwargs['granularity'] @@ -227,19 +294,19 @@ def __init__( class ChangePointDetectResponse(msrest.serialization.Model): - """ChangePointDetectResponse. + """The response of change point detection. Variables are only populated by the server, and will be ignored when sending a request. :ivar period: Frequency extracted from the series, zero means no recurrent pattern has been found. :vartype period: int - :param is_change_point: isChangePoint contains change point properties for each input point. + :ivar is_change_point: isChangePoint contains change point properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. - :type is_change_point: list[bool] - :param confidence_scores: the change point confidence of each point. - :type confidence_scores: list[float] + :vartype is_change_point: list[bool] + :ivar confidence_scores: the change point confidence of each point. + :vartype confidence_scores: list[float] """ _validation = { @@ -256,30 +323,65 @@ def __init__( self, **kwargs ): + """ + :keyword is_change_point: isChangePoint contains change point properties for each input point. + True means an anomaly either negative or positive has been detected. The index of the array is + consistent with the input series. + :paramtype is_change_point: list[bool] + :keyword confidence_scores: the change point confidence of each point. + :paramtype confidence_scores: list[float] + """ super(ChangePointDetectResponse, self).__init__(**kwargs) self.period = None self.is_change_point = kwargs.get('is_change_point', None) self.confidence_scores = kwargs.get('confidence_scores', None) +class CorrelationChanges(msrest.serialization.Model): + """CorrelationChanges. + + :ivar changed_variables: correlated variables. + :vartype changed_variables: list[str] + :ivar changed_values: changes in correlation. + :vartype changed_values: list[float] + """ + + _attribute_map = { + 'changed_variables': {'key': 'changedVariables', 'type': '[str]'}, + 'changed_values': {'key': 'changedValues', 'type': '[float]'}, + } + + def __init__( + self, + **kwargs + ): + """ + :keyword changed_variables: correlated variables. + :paramtype changed_variables: list[str] + :keyword changed_values: changes in correlation. + :paramtype changed_values: list[float] + """ + super(CorrelationChanges, self).__init__(**kwargs) + self.changed_variables = kwargs.get('changed_variables', None) + self.changed_values = kwargs.get('changed_values', None) + + class DetectionRequest(msrest.serialization.Model): - """Request to submit a detection. + """Detection request. All required parameters must be populated in order to send to Azure. - :param source: Required. source file link of the input variables, each variable will be a csv - with two columns, the first column will be timestamp, the second column will be value.Besides - these variable csv files, a extra meta.json can be included in th zip file if you would like to - rename a variable.Be default, the file name of the variable will be used as the variable name. - The variables used in detection should be consistent with variables in the model used for - detection. - :type source: str - :param start_time: Required. A require field, start time of data be used for detection, should - be date-time. - :type start_time: ~datetime.datetime - :param end_time: Required. A require field, end time of data be used for detection, should be - date-time. - :type end_time: ~datetime.datetime + :ivar source: Required. Source link to the input variables. Each variable should be a csv with + two columns, ``timestamp`` and ``value``. The file name of the variable will be used as its + name. The variables used in detection should be exactly the same with those used in the + training phase. + :vartype source: str + :ivar start_time: Required. A required field, indicating the start time of data for detection. + Should be date-time. + :vartype start_time: ~datetime.datetime + :ivar end_time: Required. A required field, indicating the end time of data for detection. + Should be date-time. + :vartype end_time: ~datetime.datetime """ _validation = { @@ -298,6 +400,19 @@ def __init__( self, **kwargs ): + """ + :keyword source: Required. Source link to the input variables. Each variable should be a csv + with two columns, ``timestamp`` and ``value``. The file name of the variable will be used as + its name. The variables used in detection should be exactly the same with those used in the + training phase. + :paramtype source: str + :keyword start_time: Required. A required field, indicating the start time of data for + detection. Should be date-time. + :paramtype start_time: ~datetime.datetime + :keyword end_time: Required. A required field, indicating the end time of data for detection. + Should be date-time. + :paramtype end_time: ~datetime.datetime + """ super(DetectionRequest, self).__init__(**kwargs) self.source = kwargs['source'] self.start_time = kwargs['start_time'] @@ -305,16 +420,16 @@ def __init__( class DetectionResult(msrest.serialization.Model): - """Anomaly Response of one detection corresponds to a resultId. + """Response of the given resultId. All required parameters must be populated in order to send to Azure. - :param result_id: Required. - :type result_id: str - :param summary: Required. Multivariate anomaly detection status. - :type summary: ~azure.ai.anomalydetector.models.DetectionResultSummary - :param results: Required. anomaly status of each timestamp. - :type results: list[~azure.ai.anomalydetector.models.AnomalyState] + :ivar result_id: Required. + :vartype result_id: str + :ivar summary: Required. + :vartype summary: ~azure.ai.anomalydetector.models.DetectionResultSummary + :ivar results: Required. Detection result for each timestamp. + :vartype results: list[~azure.ai.anomalydetector.models.AnomalyState] """ _validation = { @@ -333,6 +448,14 @@ def __init__( self, **kwargs ): + """ + :keyword result_id: Required. + :paramtype result_id: str + :keyword summary: Required. + :paramtype summary: ~azure.ai.anomalydetector.models.DetectionResultSummary + :keyword results: Required. Detection result for each timestamp. + :paramtype results: list[~azure.ai.anomalydetector.models.AnomalyState] + """ super(DetectionResult, self).__init__(**kwargs) self.result_id = kwargs['result_id'] self.summary = kwargs['summary'] @@ -344,15 +467,15 @@ class DetectionResultSummary(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param status: Required. Multivariate anomaly detection status. Possible values include: - "CREATED", "RUNNING", "READY", "FAILED". - :type status: str or ~azure.ai.anomalydetector.models.DetectionStatus - :param errors: Error message when creating or training model fails. - :type errors: list[~azure.ai.anomalydetector.models.ErrorResponse] - :param variable_states: - :type variable_states: list[~azure.ai.anomalydetector.models.VariableState] - :param setup_info: Required. Request when creating the model. - :type setup_info: ~azure.ai.anomalydetector.models.DetectionRequest + :ivar status: Required. Status of detection results. One of CREATED, RUNNING, READY, and + FAILED. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". + :vartype status: str or ~azure.ai.anomalydetector.models.DetectionStatus + :ivar errors: Error message when detection is failed. + :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar variable_states: + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :ivar setup_info: Required. Detection request. + :vartype setup_info: ~azure.ai.anomalydetector.models.DetectionRequest """ _validation = { @@ -371,6 +494,17 @@ def __init__( self, **kwargs ): + """ + :keyword status: Required. Status of detection results. One of CREATED, RUNNING, READY, and + FAILED. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". + :paramtype status: str or ~azure.ai.anomalydetector.models.DetectionStatus + :keyword errors: Error message when detection is failed. + :paramtype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :keyword variable_states: + :paramtype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :keyword setup_info: Required. Detection request. + :paramtype setup_info: ~azure.ai.anomalydetector.models.DetectionRequest + """ super(DetectionResultSummary, self).__init__(**kwargs) self.status = kwargs['status'] self.errors = kwargs.get('errors', None) @@ -379,34 +513,41 @@ def __init__( class DetectRequest(msrest.serialization.Model): - """DetectRequest. + """The request of entire or last anomaly detection. All required parameters must be populated in order to send to Azure. - :param series: Required. Time series data points. Points should be sorted by timestamp in + :ivar series: Required. Time series data points. Points should be sorted by timestamp in ascending order to match the anomaly detection result. If the data is not sorted correctly or there is duplicated timestamp, the API will not work. In such case, an error message will be returned. - :type series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] - :param granularity: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, + :vartype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :ivar granularity: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, minutely, secondly, microsecond or none. If granularity is not present, it will be none by default. If granularity is none, the timestamp property in time series point can be absent. Possible values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", "none". - :type granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity - :param custom_interval: Custom Interval is used to set non-standard time interval, for example, + :vartype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :ivar custom_interval: Custom Interval is used to set non-standard time interval, for example, if the series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}. - :type custom_interval: int - :param period: Optional argument, periodic value of a time series. If the value is null or does + :vartype custom_interval: int + :ivar period: Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - :type period: int - :param max_anomaly_ratio: Optional argument, advanced model parameter, max anomaly ratio in a + :vartype period: int + :ivar max_anomaly_ratio: Optional argument, advanced model parameter, max anomaly ratio in a time series. - :type max_anomaly_ratio: float - :param sensitivity: Optional argument, advanced model parameter, between 0-99, the lower the + :vartype max_anomaly_ratio: float + :ivar sensitivity: Optional argument, advanced model parameter, between 0-99, the lower the value is, the larger the margin value will be which means less anomalies will be accepted. - :type sensitivity: int + :vartype sensitivity: int + :ivar impute_mode: Used to specify how to deal with missing values in the input series, it's + used when granularity is not "none". Possible values include: "auto", "previous", "linear", + "fixed", "zero", "notFill". + :vartype impute_mode: str or ~azure.ai.anomalydetector.models.ImputeMode + :ivar impute_fixed_value: Used to specify the value to fill, it's used when granularity is not + "none" and imputeMode is "fixed". + :vartype impute_fixed_value: float """ _validation = { @@ -420,12 +561,47 @@ class DetectRequest(msrest.serialization.Model): 'period': {'key': 'period', 'type': 'int'}, 'max_anomaly_ratio': {'key': 'maxAnomalyRatio', 'type': 'float'}, 'sensitivity': {'key': 'sensitivity', 'type': 'int'}, + 'impute_mode': {'key': 'imputeMode', 'type': 'str'}, + 'impute_fixed_value': {'key': 'imputeFixedValue', 'type': 'float'}, } def __init__( self, **kwargs ): + """ + :keyword series: Required. Time series data points. Points should be sorted by timestamp in + ascending order to match the anomaly detection result. If the data is not sorted correctly or + there is duplicated timestamp, the API will not work. In such case, an error message will be + returned. + :paramtype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :keyword granularity: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, + minutely, secondly, microsecond or none. If granularity is not present, it will be none by + default. If granularity is none, the timestamp property in time series point can be absent. + Possible values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", + "secondly", "microsecond", "none". + :paramtype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :keyword custom_interval: Custom Interval is used to set non-standard time interval, for + example, if the series is 5 minutes, request can be set as {"granularity":"minutely", + "customInterval":5}. + :paramtype custom_interval: int + :keyword period: Optional argument, periodic value of a time series. If the value is null or + does not present, the API will determine the period automatically. + :paramtype period: int + :keyword max_anomaly_ratio: Optional argument, advanced model parameter, max anomaly ratio in a + time series. + :paramtype max_anomaly_ratio: float + :keyword sensitivity: Optional argument, advanced model parameter, between 0-99, the lower the + value is, the larger the margin value will be which means less anomalies will be accepted. + :paramtype sensitivity: int + :keyword impute_mode: Used to specify how to deal with missing values in the input series, it's + used when granularity is not "none". Possible values include: "auto", "previous", "linear", + "fixed", "zero", "notFill". + :paramtype impute_mode: str or ~azure.ai.anomalydetector.models.ImputeMode + :keyword impute_fixed_value: Used to specify the value to fill, it's used when granularity is + not "none" and imputeMode is "fixed". + :paramtype impute_fixed_value: float + """ super(DetectRequest, self).__init__(**kwargs) self.series = kwargs['series'] self.granularity = kwargs.get('granularity', None) @@ -433,15 +609,17 @@ def __init__( self.period = kwargs.get('period', None) self.max_anomaly_ratio = kwargs.get('max_anomaly_ratio', None) self.sensitivity = kwargs.get('sensitivity', None) + self.impute_mode = kwargs.get('impute_mode', None) + self.impute_fixed_value = kwargs.get('impute_fixed_value', None) class DiagnosticsInfo(msrest.serialization.Model): """DiagnosticsInfo. - :param model_state: - :type model_state: ~azure.ai.anomalydetector.models.ModelState - :param variable_states: - :type variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :ivar model_state: + :vartype model_state: ~azure.ai.anomalydetector.models.ModelState + :ivar variable_states: + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] """ _attribute_map = { @@ -453,47 +631,56 @@ def __init__( self, **kwargs ): + """ + :keyword model_state: + :paramtype model_state: ~azure.ai.anomalydetector.models.ModelState + :keyword variable_states: + :paramtype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + """ super(DiagnosticsInfo, self).__init__(**kwargs) self.model_state = kwargs.get('model_state', None) self.variable_states = kwargs.get('variable_states', None) class EntireDetectResponse(msrest.serialization.Model): - """EntireDetectResponse. + """The response of entire anomaly detection. All required parameters must be populated in order to send to Azure. - :param period: Required. Frequency extracted from the series, zero means no recurrent pattern + :ivar period: Required. Frequency extracted from the series, zero means no recurrent pattern has been found. - :type period: int - :param expected_values: Required. ExpectedValues contain expected value for each input point. + :vartype period: int + :ivar expected_values: Required. ExpectedValues contain expected value for each input point. The index of the array is consistent with the input series. - :type expected_values: list[float] - :param upper_margins: Required. UpperMargins contain upper margin of each input point. + :vartype expected_values: list[float] + :ivar upper_margins: Required. UpperMargins contain upper margin of each input point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. Anomalies in response can be filtered by upperBoundary and lowerBoundary. By adjusting marginScale value, less significant anomalies can be filtered in client side. The index of the array is consistent with the input series. - :type upper_margins: list[float] - :param lower_margins: Required. LowerMargins contain lower margin of each input point. + :vartype upper_margins: list[float] + :ivar lower_margins: Required. LowerMargins contain lower margin of each input point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. Points between the boundary can be marked as normal ones in client side. The index of the array is consistent with the input series. - :type lower_margins: list[float] - :param is_anomaly: Required. IsAnomaly contains anomaly properties for each input point. True + :vartype lower_margins: list[float] + :ivar is_anomaly: Required. IsAnomaly contains anomaly properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. - :type is_anomaly: list[bool] - :param is_negative_anomaly: Required. IsNegativeAnomaly contains anomaly status in negative + :vartype is_anomaly: list[bool] + :ivar is_negative_anomaly: Required. IsNegativeAnomaly contains anomaly status in negative direction for each input point. True means a negative anomaly has been detected. A negative anomaly means the point is detected as an anomaly and its real value is smaller than the expected one. The index of the array is consistent with the input series. - :type is_negative_anomaly: list[bool] - :param is_positive_anomaly: Required. IsPositiveAnomaly contain anomaly status in positive + :vartype is_negative_anomaly: list[bool] + :ivar is_positive_anomaly: Required. IsPositiveAnomaly contain anomaly status in positive direction for each input point. True means a positive anomaly has been detected. A positive anomaly means the point is detected as an anomaly and its real value is larger than the expected one. The index of the array is consistent with the input series. - :type is_positive_anomaly: list[bool] + :vartype is_positive_anomaly: list[bool] + :ivar severity: The severity score for each input point. The larger the value is, the more + sever the anomaly is. For normal points, the "severity" is always 0. + :vartype severity: list[float] """ _validation = { @@ -514,12 +701,49 @@ class EntireDetectResponse(msrest.serialization.Model): 'is_anomaly': {'key': 'isAnomaly', 'type': '[bool]'}, 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': '[bool]'}, 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': '[bool]'}, + 'severity': {'key': 'severity', 'type': '[float]'}, } def __init__( self, **kwargs ): + """ + :keyword period: Required. Frequency extracted from the series, zero means no recurrent pattern + has been found. + :paramtype period: int + :keyword expected_values: Required. ExpectedValues contain expected value for each input point. + The index of the array is consistent with the input series. + :paramtype expected_values: list[float] + :keyword upper_margins: Required. UpperMargins contain upper margin of each input point. + UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - + marginScale)*upperMargin. Anomalies in response can be filtered by upperBoundary and + lowerBoundary. By adjusting marginScale value, less significant anomalies can be filtered in + client side. The index of the array is consistent with the input series. + :paramtype upper_margins: list[float] + :keyword lower_margins: Required. LowerMargins contain lower margin of each input point. + LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - + marginScale)*lowerMargin. Points between the boundary can be marked as normal ones in client + side. The index of the array is consistent with the input series. + :paramtype lower_margins: list[float] + :keyword is_anomaly: Required. IsAnomaly contains anomaly properties for each input point. True + means an anomaly either negative or positive has been detected. The index of the array is + consistent with the input series. + :paramtype is_anomaly: list[bool] + :keyword is_negative_anomaly: Required. IsNegativeAnomaly contains anomaly status in negative + direction for each input point. True means a negative anomaly has been detected. A negative + anomaly means the point is detected as an anomaly and its real value is smaller than the + expected one. The index of the array is consistent with the input series. + :paramtype is_negative_anomaly: list[bool] + :keyword is_positive_anomaly: Required. IsPositiveAnomaly contain anomaly status in positive + direction for each input point. True means a positive anomaly has been detected. A positive + anomaly means the point is detected as an anomaly and its real value is larger than the + expected one. The index of the array is consistent with the input series. + :paramtype is_positive_anomaly: list[bool] + :keyword severity: The severity score for each input point. The larger the value is, the more + sever the anomaly is. For normal points, the "severity" is always 0. + :paramtype severity: list[float] + """ super(EntireDetectResponse, self).__init__(**kwargs) self.period = kwargs['period'] self.expected_values = kwargs['expected_values'] @@ -528,6 +752,7 @@ def __init__( self.is_anomaly = kwargs['is_anomaly'] self.is_negative_anomaly = kwargs['is_negative_anomaly'] self.is_positive_anomaly = kwargs['is_positive_anomaly'] + self.severity = kwargs.get('severity', None) class ErrorResponse(msrest.serialization.Model): @@ -535,10 +760,10 @@ class ErrorResponse(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param code: Required. The error Code. - :type code: str - :param message: Required. A message explaining the error reported by the service. - :type message: str + :ivar code: Required. The error code. + :vartype code: str + :ivar message: Required. The message explaining the error reported by the service. + :vartype message: str """ _validation = { @@ -555,41 +780,115 @@ def __init__( self, **kwargs ): + """ + :keyword code: Required. The error code. + :paramtype code: str + :keyword message: Required. The message explaining the error reported by the service. + :paramtype message: str + """ super(ErrorResponse, self).__init__(**kwargs) self.code = kwargs['code'] self.message = kwargs['message'] +class LastDetectionRequest(msrest.serialization.Model): + """LastDetectionRequest. + + All required parameters must be populated in order to send to Azure. + + :ivar variables: Required. variables. + :vartype variables: list[~azure.ai.anomalydetector.models.VariableValues] + :ivar detecting_points: Required. number of timestamps on which the model detects. + :vartype detecting_points: int + """ + + _validation = { + 'variables': {'required': True}, + 'detecting_points': {'required': True}, + } + + _attribute_map = { + 'variables': {'key': 'variables', 'type': '[VariableValues]'}, + 'detecting_points': {'key': 'detectingPoints', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + """ + :keyword variables: Required. variables. + :paramtype variables: list[~azure.ai.anomalydetector.models.VariableValues] + :keyword detecting_points: Required. number of timestamps on which the model detects. + :paramtype detecting_points: int + """ + super(LastDetectionRequest, self).__init__(**kwargs) + self.variables = kwargs['variables'] + self.detecting_points = kwargs['detecting_points'] + + +class LastDetectionResult(msrest.serialization.Model): + """LastDetectionResult. + + :ivar variable_states: + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :ivar results: + :vartype results: list[~azure.ai.anomalydetector.models.AnomalyState] + """ + + _attribute_map = { + 'variable_states': {'key': 'variableStates', 'type': '[VariableState]'}, + 'results': {'key': 'results', 'type': '[AnomalyState]'}, + } + + def __init__( + self, + **kwargs + ): + """ + :keyword variable_states: + :paramtype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :keyword results: + :paramtype results: list[~azure.ai.anomalydetector.models.AnomalyState] + """ + super(LastDetectionResult, self).__init__(**kwargs) + self.variable_states = kwargs.get('variable_states', None) + self.results = kwargs.get('results', None) + + class LastDetectResponse(msrest.serialization.Model): - """LastDetectResponse. + """The response of last anomaly detection. All required parameters must be populated in order to send to Azure. - :param period: Required. Frequency extracted from the series, zero means no recurrent pattern + :ivar period: Required. Frequency extracted from the series, zero means no recurrent pattern has been found. - :type period: int - :param suggested_window: Required. Suggested input series points needed for detecting the - latest point. - :type suggested_window: int - :param expected_value: Required. Expected value of the latest point. - :type expected_value: float - :param upper_margin: Required. Upper margin of the latest point. UpperMargin is used to + :vartype period: int + :ivar suggested_window: Required. Suggested input series points needed for detecting the latest + point. + :vartype suggested_window: int + :ivar expected_value: Required. Expected value of the latest point. + :vartype expected_value: float + :ivar upper_margin: Required. Upper margin of the latest point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. If the value of latest point is between upperBoundary and lowerBoundary, it should be treated as normal value. By adjusting marginScale value, anomaly status of latest point can be changed. - :type upper_margin: float - :param lower_margin: Required. Lower margin of the latest point. LowerMargin is used to + :vartype upper_margin: float + :ivar lower_margin: Required. Lower margin of the latest point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. - :type lower_margin: float - :param is_anomaly: Required. Anomaly status of the latest point, true means the latest point is + :vartype lower_margin: float + :ivar is_anomaly: Required. Anomaly status of the latest point, true means the latest point is an anomaly either in negative direction or positive direction. - :type is_anomaly: bool - :param is_negative_anomaly: Required. Anomaly status in negative direction of the latest point. + :vartype is_anomaly: bool + :ivar is_negative_anomaly: Required. Anomaly status in negative direction of the latest point. True means the latest point is an anomaly and its real value is smaller than the expected one. - :type is_negative_anomaly: bool - :param is_positive_anomaly: Required. Anomaly status in positive direction of the latest point. + :vartype is_negative_anomaly: bool + :ivar is_positive_anomaly: Required. Anomaly status in positive direction of the latest point. True means the latest point is an anomaly and its real value is larger than the expected one. - :type is_positive_anomaly: bool + :vartype is_positive_anomaly: bool + :ivar severity: The severity score for the last input point. The larger the value is, the more + sever the anomaly is. For normal points, the "severity" is always 0. + :vartype severity: float """ _validation = { @@ -612,12 +911,45 @@ class LastDetectResponse(msrest.serialization.Model): 'is_anomaly': {'key': 'isAnomaly', 'type': 'bool'}, 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': 'bool'}, 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': 'bool'}, + 'severity': {'key': 'severity', 'type': 'float'}, } def __init__( self, **kwargs ): + """ + :keyword period: Required. Frequency extracted from the series, zero means no recurrent pattern + has been found. + :paramtype period: int + :keyword suggested_window: Required. Suggested input series points needed for detecting the + latest point. + :paramtype suggested_window: int + :keyword expected_value: Required. Expected value of the latest point. + :paramtype expected_value: float + :keyword upper_margin: Required. Upper margin of the latest point. UpperMargin is used to + calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. If + the value of latest point is between upperBoundary and lowerBoundary, it should be treated as + normal value. By adjusting marginScale value, anomaly status of latest point can be changed. + :paramtype upper_margin: float + :keyword lower_margin: Required. Lower margin of the latest point. LowerMargin is used to + calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. + :paramtype lower_margin: float + :keyword is_anomaly: Required. Anomaly status of the latest point, true means the latest point + is an anomaly either in negative direction or positive direction. + :paramtype is_anomaly: bool + :keyword is_negative_anomaly: Required. Anomaly status in negative direction of the latest + point. True means the latest point is an anomaly and its real value is smaller than the + expected one. + :paramtype is_negative_anomaly: bool + :keyword is_positive_anomaly: Required. Anomaly status in positive direction of the latest + point. True means the latest point is an anomaly and its real value is larger than the expected + one. + :paramtype is_positive_anomaly: bool + :keyword severity: The severity score for the last input point. The larger the value is, the + more sever the anomaly is. For normal points, the "severity" is always 0. + :paramtype severity: float + """ super(LastDetectResponse, self).__init__(**kwargs) self.period = kwargs['period'] self.suggested_window = kwargs['suggested_window'] @@ -627,21 +959,23 @@ def __init__( self.is_anomaly = kwargs['is_anomaly'] self.is_negative_anomaly = kwargs['is_negative_anomaly'] self.is_positive_anomaly = kwargs['is_positive_anomaly'] + self.severity = kwargs.get('severity', None) class Model(msrest.serialization.Model): - """Response of get model. + """Response of getting a model. All required parameters must be populated in order to send to Azure. - :param model_id: Required. Model identifier. - :type model_id: str - :param created_time: Required. Date and time (UTC) when the model was created. - :type created_time: ~datetime.datetime - :param last_updated_time: Required. Date and time (UTC) when the model was last updated. - :type last_updated_time: ~datetime.datetime - :param model_info: Training Status of the model. - :type model_info: ~azure.ai.anomalydetector.models.ModelInfo + :ivar model_id: Required. Model identifier. + :vartype model_id: str + :ivar created_time: Required. Date and time (UTC) when the model was created. + :vartype created_time: ~datetime.datetime + :ivar last_updated_time: Required. Date and time (UTC) when the model was last updated. + :vartype last_updated_time: ~datetime.datetime + :ivar model_info: Train result of a model including status, errors and diagnose info for model + and variables. + :vartype model_info: ~azure.ai.anomalydetector.models.ModelInfo """ _validation = { @@ -661,6 +995,17 @@ def __init__( self, **kwargs ): + """ + :keyword model_id: Required. Model identifier. + :paramtype model_id: str + :keyword created_time: Required. Date and time (UTC) when the model was created. + :paramtype created_time: ~datetime.datetime + :keyword last_updated_time: Required. Date and time (UTC) when the model was last updated. + :paramtype last_updated_time: ~datetime.datetime + :keyword model_info: Train result of a model including status, errors and diagnose info for + model and variables. + :paramtype model_info: ~azure.ai.anomalydetector.models.ModelInfo + """ super(Model, self).__init__(**kwargs) self.model_id = kwargs['model_id'] self.created_time = kwargs['created_time'] @@ -675,32 +1020,29 @@ class ModelInfo(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param sliding_window: An optional field, indicates how many history points will be used to - determine the anomaly score of one subsequent point. - :type sliding_window: int - :param align_policy: An optional field, since those multivariate need to be aligned in the same - timestamp before starting the detection. - :type align_policy: ~azure.ai.anomalydetector.models.AlignPolicy - :param source: Required. source file link of the input variables, each variable will be a csv - with two columns, the first column will be timestamp, the second column will be value.Besides - these variable csv files, an extra meta.json can be included in th zip file if you would like - to rename a variable.Be default, the file name of the variable will be used as the variable - name. - :type source: str - :param start_time: Required. require field, start time of data be used for generating - multivariate anomaly detection model, should be data-time. - :type start_time: ~datetime.datetime - :param end_time: Required. require field, end time of data be used for generating multivariate - anomaly detection model, should be data-time. - :type end_time: ~datetime.datetime - :param display_name: optional field, name of the model. - :type display_name: str + :ivar sliding_window: An optional field, indicating how many previous points will be used to + compute the anomaly score of the subsequent point. + :vartype sliding_window: int + :ivar align_policy: + :vartype align_policy: ~azure.ai.anomalydetector.models.AlignPolicy + :ivar source: Required. Source link to the input variables. Each variable should be a csv file + with two columns, ``timestamp`` and ``value``. By default, the file name of the variable will + be used as its variable name. + :vartype source: str + :ivar start_time: Required. A required field, indicating the start time of training data. + Should be date-time. + :vartype start_time: ~datetime.datetime + :ivar end_time: Required. A required field, indicating the end time of training data. Should be + date-time. + :vartype end_time: ~datetime.datetime + :ivar display_name: An optional field. The name of the model whose maximum length is 24. + :vartype display_name: str :ivar status: Model training status. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". :vartype status: str or ~azure.ai.anomalydetector.models.ModelStatus - :ivar errors: Error message when fails to create a model. + :ivar errors: Error messages when failed to create a model. :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] - :ivar diagnostics_info: Used for deep analysis model and variables. + :ivar diagnostics_info: :vartype diagnostics_info: ~azure.ai.anomalydetector.models.DiagnosticsInfo """ @@ -730,6 +1072,25 @@ def __init__( self, **kwargs ): + """ + :keyword sliding_window: An optional field, indicating how many previous points will be used to + compute the anomaly score of the subsequent point. + :paramtype sliding_window: int + :keyword align_policy: + :paramtype align_policy: ~azure.ai.anomalydetector.models.AlignPolicy + :keyword source: Required. Source link to the input variables. Each variable should be a csv + file with two columns, ``timestamp`` and ``value``. By default, the file name of the variable + will be used as its variable name. + :paramtype source: str + :keyword start_time: Required. A required field, indicating the start time of training data. + Should be date-time. + :paramtype start_time: ~datetime.datetime + :keyword end_time: Required. A required field, indicating the end time of training data. Should + be date-time. + :paramtype end_time: ~datetime.datetime + :keyword display_name: An optional field. The name of the model whose maximum length is 24. + :paramtype display_name: str + """ super(ModelInfo, self).__init__(**kwargs) self.sliding_window = kwargs.get('sliding_window', None) self.align_policy = kwargs.get('align_policy', None) @@ -743,18 +1104,18 @@ def __init__( class ModelList(msrest.serialization.Model): - """Response to the list models operation. + """Response of listing models. All required parameters must be populated in order to send to Azure. - :param models: Required. List of models. - :type models: list[~azure.ai.anomalydetector.models.ModelSnapshot] - :param current_count: Required. Current count of trained multivariate models. - :type current_count: int - :param max_count: Required. Max number of models that can be trained for this subscription. - :type max_count: int - :param next_link: next link to fetch more models. - :type next_link: str + :ivar models: Required. List of models. + :vartype models: list[~azure.ai.anomalydetector.models.ModelSnapshot] + :ivar current_count: Required. Current count of trained multivariate models. + :vartype current_count: int + :ivar max_count: Required. Max number of models that can be trained for this subscription. + :vartype max_count: int + :ivar next_link: The link to fetch more models. + :vartype next_link: str """ _validation = { @@ -774,6 +1135,16 @@ def __init__( self, **kwargs ): + """ + :keyword models: Required. List of models. + :paramtype models: list[~azure.ai.anomalydetector.models.ModelSnapshot] + :keyword current_count: Required. Current count of trained multivariate models. + :paramtype current_count: int + :keyword max_count: Required. Max number of models that can be trained for this subscription. + :paramtype max_count: int + :keyword next_link: The link to fetch more models. + :paramtype next_link: str + """ super(ModelList, self).__init__(**kwargs) self.models = kwargs['models'] self.current_count = kwargs['current_count'] @@ -788,19 +1159,19 @@ class ModelSnapshot(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param model_id: Required. Model identifier. - :type model_id: str - :param created_time: Required. Date and time (UTC) when the model was created. - :type created_time: ~datetime.datetime - :param last_updated_time: Required. Date and time (UTC) when the model was last updated. - :type last_updated_time: ~datetime.datetime + :ivar model_id: Required. Model identifier. + :vartype model_id: str + :ivar created_time: Required. Date and time (UTC) when the model was created. + :vartype created_time: ~datetime.datetime + :ivar last_updated_time: Required. Date and time (UTC) when the model was last updated. + :vartype last_updated_time: ~datetime.datetime :ivar status: Required. Model training status. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". :vartype status: str or ~azure.ai.anomalydetector.models.ModelStatus - :param display_name: - :type display_name: str - :param variables_count: Required. Count of variables. - :type variables_count: int + :ivar display_name: + :vartype display_name: str + :ivar variables_count: Required. Total number of variables. + :vartype variables_count: int """ _validation = { @@ -824,6 +1195,18 @@ def __init__( self, **kwargs ): + """ + :keyword model_id: Required. Model identifier. + :paramtype model_id: str + :keyword created_time: Required. Date and time (UTC) when the model was created. + :paramtype created_time: ~datetime.datetime + :keyword last_updated_time: Required. Date and time (UTC) when the model was last updated. + :paramtype last_updated_time: ~datetime.datetime + :keyword display_name: + :paramtype display_name: str + :keyword variables_count: Required. Total number of variables. + :paramtype variables_count: int + """ super(ModelSnapshot, self).__init__(**kwargs) self.model_id = kwargs['model_id'] self.created_time = kwargs['created_time'] @@ -836,14 +1219,14 @@ def __init__( class ModelState(msrest.serialization.Model): """ModelState. - :param epoch_ids: Epoch id. - :type epoch_ids: list[int] - :param train_losses: - :type train_losses: list[float] - :param validation_losses: - :type validation_losses: list[float] - :param latencies_in_seconds: - :type latencies_in_seconds: list[float] + :ivar epoch_ids: Epoch id. + :vartype epoch_ids: list[int] + :ivar train_losses: + :vartype train_losses: list[float] + :ivar validation_losses: + :vartype validation_losses: list[float] + :ivar latencies_in_seconds: + :vartype latencies_in_seconds: list[float] """ _attribute_map = { @@ -857,6 +1240,16 @@ def __init__( self, **kwargs ): + """ + :keyword epoch_ids: Epoch id. + :paramtype epoch_ids: list[int] + :keyword train_losses: + :paramtype train_losses: list[float] + :keyword validation_losses: + :paramtype validation_losses: list[float] + :keyword latencies_in_seconds: + :paramtype latencies_in_seconds: list[float] + """ super(ModelState, self).__init__(**kwargs) self.epoch_ids = kwargs.get('epoch_ids', None) self.train_losses = kwargs.get('train_losses', None) @@ -865,14 +1258,14 @@ def __init__( class TimeSeriesPoint(msrest.serialization.Model): - """TimeSeriesPoint. + """The definition of input timeseries points. All required parameters must be populated in order to send to Azure. - :param timestamp: Optional argument, timestamp of a data point (ISO8601 format). - :type timestamp: ~datetime.datetime - :param value: Required. The measurement of that point, should be float. - :type value: float + :ivar timestamp: Optional argument, timestamp of a data point (ISO8601 format). + :vartype timestamp: ~datetime.datetime + :ivar value: Required. The measurement of that point, should be float. + :vartype value: float """ _validation = { @@ -888,6 +1281,12 @@ def __init__( self, **kwargs ): + """ + :keyword timestamp: Optional argument, timestamp of a data point (ISO8601 format). + :paramtype timestamp: ~datetime.datetime + :keyword value: Required. The measurement of that point, should be float. + :paramtype value: float + """ super(TimeSeriesPoint, self).__init__(**kwargs) self.timestamp = kwargs.get('timestamp', None) self.value = kwargs['value'] @@ -896,18 +1295,16 @@ def __init__( class VariableState(msrest.serialization.Model): """VariableState. - :param variable: Variable name. - :type variable: str - :param filled_na_ratio: Merged NA ratio of a variable. - :type filled_na_ratio: float - :param effective_count: Effective time-series points count. - :type effective_count: int - :param start_time: Start time of a variable. - :type start_time: ~datetime.datetime - :param end_time: End time of a variable. - :type end_time: ~datetime.datetime - :param errors: Error message when parse variable. - :type errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar variable: Variable name. + :vartype variable: str + :ivar filled_na_ratio: Proportion of NaN values filled of the variable. + :vartype filled_na_ratio: float + :ivar effective_count: Number of effective points counted. + :vartype effective_count: int + :ivar start_time: Start time of the variable. + :vartype start_time: ~datetime.datetime + :ivar end_time: End time of the variable. + :vartype end_time: ~datetime.datetime """ _validation = { @@ -920,17 +1317,70 @@ class VariableState(msrest.serialization.Model): 'effective_count': {'key': 'effectiveCount', 'type': 'int'}, 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, - 'errors': {'key': 'errors', 'type': '[ErrorResponse]'}, } def __init__( self, **kwargs ): + """ + :keyword variable: Variable name. + :paramtype variable: str + :keyword filled_na_ratio: Proportion of NaN values filled of the variable. + :paramtype filled_na_ratio: float + :keyword effective_count: Number of effective points counted. + :paramtype effective_count: int + :keyword start_time: Start time of the variable. + :paramtype start_time: ~datetime.datetime + :keyword end_time: End time of the variable. + :paramtype end_time: ~datetime.datetime + """ super(VariableState, self).__init__(**kwargs) self.variable = kwargs.get('variable', None) self.filled_na_ratio = kwargs.get('filled_na_ratio', None) self.effective_count = kwargs.get('effective_count', None) self.start_time = kwargs.get('start_time', None) self.end_time = kwargs.get('end_time', None) - self.errors = kwargs.get('errors', None) + + +class VariableValues(msrest.serialization.Model): + """VariableValues. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Required. variable name. + :vartype name: str + :ivar timestamps: Required. timestamps. + :vartype timestamps: list[str] + :ivar values: Required. values. + :vartype values: list[float] + """ + + _validation = { + 'name': {'required': True}, + 'timestamps': {'required': True}, + 'values': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'timestamps': {'key': 'timestamps', 'type': '[str]'}, + 'values': {'key': 'values', 'type': '[float]'}, + } + + def __init__( + self, + **kwargs + ): + """ + :keyword name: Required. variable name. + :paramtype name: str + :keyword timestamps: Required. timestamps. + :paramtype timestamps: list[str] + :keyword values: Required. values. + :paramtype values: list[float] + """ + super(VariableValues, self).__init__(**kwargs) + self.name = kwargs['name'] + self.timestamps = kwargs['timestamps'] + self.values = kwargs['values'] diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models_py3.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models_py3.py index 7b1adadf5817..31b20ba2b36c 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models_py3.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models_py3.py @@ -18,23 +18,22 @@ class AlignPolicy(msrest.serialization.Model): """AlignPolicy. - :param align_mode: An optional field, indicates how we align different variables into the same - time-range which is required by the model.{Inner, Outer}. Possible values include: "Inner", - "Outer". - :type align_mode: str or ~azure.ai.anomalydetector.models.AlignMode - :param fill_na_method: An optional field, indicates how missed values will be filled with. Can - not be set to NotFill, when alignMode is Outer.{Previous, Subsequent, Linear, Zero, Fix, - NotFill}. Possible values include: "Previous", "Subsequent", "Linear", "Zero", "Pad", - "NotFill". - :type fill_na_method: str or ~azure.ai.anomalydetector.models.FillNAMethod - :param padding_value: optional field, only be useful if FillNAMethod is set to Pad. - :type padding_value: int + :ivar align_mode: An optional field, indicating how we align different variables to the same + time-range. Either Inner or Outer. Possible values include: "Inner", "Outer". + :vartype align_mode: str or ~azure.ai.anomalydetector.models.AlignMode + :ivar fill_na_method: An optional field, indicating how missing values will be filled. One of + Previous, Subsequent, Linear, Zero, Fixed, and NotFill. Cannot be set to NotFill, when the + alignMode is Outer. Possible values include: "Previous", "Subsequent", "Linear", "Zero", + "Fixed", "NotFill". + :vartype fill_na_method: str or ~azure.ai.anomalydetector.models.FillNAMethod + :ivar padding_value: An optional field. Required when fillNAMethod is Fixed. + :vartype padding_value: float """ _attribute_map = { 'align_mode': {'key': 'alignMode', 'type': 'str'}, 'fill_na_method': {'key': 'fillNAMethod', 'type': 'str'}, - 'padding_value': {'key': 'paddingValue', 'type': 'int'}, + 'padding_value': {'key': 'paddingValue', 'type': 'float'}, } def __init__( @@ -42,72 +41,102 @@ def __init__( *, align_mode: Optional[Union[str, "AlignMode"]] = None, fill_na_method: Optional[Union[str, "FillNAMethod"]] = None, - padding_value: Optional[int] = None, + padding_value: Optional[float] = None, **kwargs ): + """ + :keyword align_mode: An optional field, indicating how we align different variables to the same + time-range. Either Inner or Outer. Possible values include: "Inner", "Outer". + :paramtype align_mode: str or ~azure.ai.anomalydetector.models.AlignMode + :keyword fill_na_method: An optional field, indicating how missing values will be filled. One + of Previous, Subsequent, Linear, Zero, Fixed, and NotFill. Cannot be set to NotFill, when the + alignMode is Outer. Possible values include: "Previous", "Subsequent", "Linear", "Zero", + "Fixed", "NotFill". + :paramtype fill_na_method: str or ~azure.ai.anomalydetector.models.FillNAMethod + :keyword padding_value: An optional field. Required when fillNAMethod is Fixed. + :paramtype padding_value: float + """ super(AlignPolicy, self).__init__(**kwargs) self.align_mode = align_mode self.fill_na_method = fill_na_method self.padding_value = padding_value -class AnomalyContributor(msrest.serialization.Model): - """AnomalyContributor. +class AnomalyDetectorError(msrest.serialization.Model): + """Error information returned by the API. - :param contribution_score: The higher the contribution score is, the more likely the variable - to be the root cause of a anomaly. - :type contribution_score: float - :param variable: Variable name of a contributor. - :type variable: str + :ivar code: The error code. Possible values include: "InvalidCustomInterval", "BadArgument", + "InvalidGranularity", "InvalidPeriod", "InvalidModelArgument", "InvalidSeries", + "InvalidJsonFormat", "RequiredGranularity", "RequiredSeries", "InvalidImputeMode", + "InvalidImputeFixedValue". + :vartype code: str or ~azure.ai.anomalydetector.models.AnomalyDetectorErrorCodes + :ivar message: A message explaining the error reported by the service. + :vartype message: str """ - _validation = { - 'contribution_score': {'maximum': 2, 'minimum': 0}, - } - _attribute_map = { - 'contribution_score': {'key': 'contributionScore', 'type': 'float'}, - 'variable': {'key': 'variable', 'type': 'str'}, + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, } def __init__( self, *, - contribution_score: Optional[float] = None, - variable: Optional[str] = None, + code: Optional[Union[str, "AnomalyDetectorErrorCodes"]] = None, + message: Optional[str] = None, **kwargs ): - super(AnomalyContributor, self).__init__(**kwargs) - self.contribution_score = contribution_score - self.variable = variable + """ + :keyword code: The error code. Possible values include: "InvalidCustomInterval", "BadArgument", + "InvalidGranularity", "InvalidPeriod", "InvalidModelArgument", "InvalidSeries", + "InvalidJsonFormat", "RequiredGranularity", "RequiredSeries", "InvalidImputeMode", + "InvalidImputeFixedValue". + :paramtype code: str or ~azure.ai.anomalydetector.models.AnomalyDetectorErrorCodes + :keyword message: A message explaining the error reported by the service. + :paramtype message: str + """ + super(AnomalyDetectorError, self).__init__(**kwargs) + self.code = code + self.message = message -class AnomalyDetectorError(msrest.serialization.Model): - """Error information returned by the API. +class AnomalyInterpretation(msrest.serialization.Model): + """AnomalyInterpretation. - :param code: The error code. Possible values include: "InvalidCustomInterval", "BadArgument", - "InvalidGranularity", "InvalidPeriod", "InvalidModelArgument", "InvalidSeries", - "InvalidJsonFormat", "RequiredGranularity", "RequiredSeries". - :type code: str or ~azure.ai.anomalydetector.models.AnomalyDetectorErrorCodes - :param message: A message explaining the error reported by the service. - :type message: str + :ivar variable: + :vartype variable: str + :ivar contribution_score: + :vartype contribution_score: float + :ivar correlation_changes: + :vartype correlation_changes: ~azure.ai.anomalydetector.models.CorrelationChanges """ _attribute_map = { - 'code': {'key': 'code', 'type': 'str'}, - 'message': {'key': 'message', 'type': 'str'}, + 'variable': {'key': 'variable', 'type': 'str'}, + 'contribution_score': {'key': 'contributionScore', 'type': 'float'}, + 'correlation_changes': {'key': 'correlationChanges', 'type': 'CorrelationChanges'}, } def __init__( self, *, - code: Optional[Union[str, "AnomalyDetectorErrorCodes"]] = None, - message: Optional[str] = None, + variable: Optional[str] = None, + contribution_score: Optional[float] = None, + correlation_changes: Optional["CorrelationChanges"] = None, **kwargs ): - super(AnomalyDetectorError, self).__init__(**kwargs) - self.code = code - self.message = message + """ + :keyword variable: + :paramtype variable: str + :keyword contribution_score: + :paramtype contribution_score: float + :keyword correlation_changes: + :paramtype correlation_changes: ~azure.ai.anomalydetector.models.CorrelationChanges + """ + super(AnomalyInterpretation, self).__init__(**kwargs) + self.variable = variable + self.contribution_score = contribution_score + self.correlation_changes = correlation_changes class AnomalyState(msrest.serialization.Model): @@ -115,12 +144,12 @@ class AnomalyState(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param timestamp: Required. timestamp. - :type timestamp: ~datetime.datetime - :param value: - :type value: ~azure.ai.anomalydetector.models.AnomalyValue - :param errors: Error message when inference this timestamp. - :type errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar timestamp: Required. timestamp. + :vartype timestamp: ~datetime.datetime + :ivar value: + :vartype value: ~azure.ai.anomalydetector.models.AnomalyValue + :ivar errors: Error message for the current timestamp. + :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] """ _validation = { @@ -141,6 +170,14 @@ def __init__( errors: Optional[List["ErrorResponse"]] = None, **kwargs ): + """ + :keyword timestamp: Required. timestamp. + :paramtype timestamp: ~datetime.datetime + :keyword value: + :paramtype value: ~azure.ai.anomalydetector.models.AnomalyValue + :keyword errors: Error message for the current timestamp. + :paramtype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + """ super(AnomalyState, self).__init__(**kwargs) self.timestamp = timestamp self.value = value @@ -152,31 +189,28 @@ class AnomalyValue(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param contributors: If current timestamp is an anomaly, contributors will show potential root - cause for thus anomaly. Contributors can help us understand why current timestamp has been - detected as an anomaly. - :type contributors: list[~azure.ai.anomalydetector.models.AnomalyContributor] - :param is_anomaly: Required. To indicate whether current timestamp is anomaly or not. - :type is_anomaly: bool - :param severity: Required. anomaly score of the current timestamp, the more significant an - anomaly is, the higher the score will be. - :type severity: float - :param score: anomaly score of the current timestamp, the more significant an anomaly is, the - higher the score will be, score measures global significance. - :type score: float + :ivar is_anomaly: Required. True if an anomaly is detected at the current timestamp. + :vartype is_anomaly: bool + :ivar severity: Required. Indicates the significance of the anomaly. The higher the severity, + the more significant the anomaly. + :vartype severity: float + :ivar score: Required. Raw score from the model. + :vartype score: float + :ivar interpretation: + :vartype interpretation: list[~azure.ai.anomalydetector.models.AnomalyInterpretation] """ _validation = { 'is_anomaly': {'required': True}, 'severity': {'required': True, 'maximum': 1, 'minimum': 0}, - 'score': {'maximum': 2, 'minimum': 0}, + 'score': {'required': True, 'maximum': 2, 'minimum': 0}, } _attribute_map = { - 'contributors': {'key': 'contributors', 'type': '[AnomalyContributor]'}, 'is_anomaly': {'key': 'isAnomaly', 'type': 'bool'}, 'severity': {'key': 'severity', 'type': 'float'}, 'score': {'key': 'score', 'type': 'float'}, + 'interpretation': {'key': 'interpretation', 'type': '[AnomalyInterpretation]'}, } def __init__( @@ -184,43 +218,54 @@ def __init__( *, is_anomaly: bool, severity: float, - contributors: Optional[List["AnomalyContributor"]] = None, - score: Optional[float] = None, + score: float, + interpretation: Optional[List["AnomalyInterpretation"]] = None, **kwargs ): + """ + :keyword is_anomaly: Required. True if an anomaly is detected at the current timestamp. + :paramtype is_anomaly: bool + :keyword severity: Required. Indicates the significance of the anomaly. The higher the + severity, the more significant the anomaly. + :paramtype severity: float + :keyword score: Required. Raw score from the model. + :paramtype score: float + :keyword interpretation: + :paramtype interpretation: list[~azure.ai.anomalydetector.models.AnomalyInterpretation] + """ super(AnomalyValue, self).__init__(**kwargs) - self.contributors = contributors self.is_anomaly = is_anomaly self.severity = severity self.score = score + self.interpretation = interpretation class ChangePointDetectRequest(msrest.serialization.Model): - """ChangePointDetectRequest. + """The request of change point detection. All required parameters must be populated in order to send to Azure. - :param series: Required. Time series data points. Points should be sorted by timestamp in + :ivar series: Required. Time series data points. Points should be sorted by timestamp in ascending order to match the change point detection result. - :type series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] - :param granularity: Required. Can only be one of yearly, monthly, weekly, daily, hourly, + :vartype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :ivar granularity: Required. Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid. Possible values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", "none". - :type granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity - :param custom_interval: Custom Interval is used to set non-standard time interval, for example, + :vartype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :ivar custom_interval: Custom Interval is used to set non-standard time interval, for example, if the series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}. - :type custom_interval: int - :param period: Optional argument, periodic value of a time series. If the value is null or does + :vartype custom_interval: int + :ivar period: Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - :type period: int - :param stable_trend_window: Optional argument, advanced model parameter, a default + :vartype period: int + :ivar stable_trend_window: Optional argument, advanced model parameter, a default stableTrendWindow will be used in detection. - :type stable_trend_window: int - :param threshold: Optional argument, advanced model parameter, between 0.0-1.0, the lower the + :vartype stable_trend_window: int + :ivar threshold: Optional argument, advanced model parameter, between 0.0-1.0, the lower the value is, the larger the trend error will be which means less change point will be accepted. - :type threshold: float + :vartype threshold: float """ _validation = { @@ -248,6 +293,29 @@ def __init__( threshold: Optional[float] = None, **kwargs ): + """ + :keyword series: Required. Time series data points. Points should be sorted by timestamp in + ascending order to match the change point detection result. + :paramtype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :keyword granularity: Required. Can only be one of yearly, monthly, weekly, daily, hourly, + minutely or secondly. Granularity is used for verify whether input series is valid. Possible + values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", + "microsecond", "none". + :paramtype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :keyword custom_interval: Custom Interval is used to set non-standard time interval, for + example, if the series is 5 minutes, request can be set as {"granularity":"minutely", + "customInterval":5}. + :paramtype custom_interval: int + :keyword period: Optional argument, periodic value of a time series. If the value is null or + does not present, the API will determine the period automatically. + :paramtype period: int + :keyword stable_trend_window: Optional argument, advanced model parameter, a default + stableTrendWindow will be used in detection. + :paramtype stable_trend_window: int + :keyword threshold: Optional argument, advanced model parameter, between 0.0-1.0, the lower the + value is, the larger the trend error will be which means less change point will be accepted. + :paramtype threshold: float + """ super(ChangePointDetectRequest, self).__init__(**kwargs) self.series = series self.granularity = granularity @@ -258,19 +326,19 @@ def __init__( class ChangePointDetectResponse(msrest.serialization.Model): - """ChangePointDetectResponse. + """The response of change point detection. Variables are only populated by the server, and will be ignored when sending a request. :ivar period: Frequency extracted from the series, zero means no recurrent pattern has been found. :vartype period: int - :param is_change_point: isChangePoint contains change point properties for each input point. + :ivar is_change_point: isChangePoint contains change point properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. - :type is_change_point: list[bool] - :param confidence_scores: the change point confidence of each point. - :type confidence_scores: list[float] + :vartype is_change_point: list[bool] + :ivar confidence_scores: the change point confidence of each point. + :vartype confidence_scores: list[float] """ _validation = { @@ -290,30 +358,68 @@ def __init__( confidence_scores: Optional[List[float]] = None, **kwargs ): + """ + :keyword is_change_point: isChangePoint contains change point properties for each input point. + True means an anomaly either negative or positive has been detected. The index of the array is + consistent with the input series. + :paramtype is_change_point: list[bool] + :keyword confidence_scores: the change point confidence of each point. + :paramtype confidence_scores: list[float] + """ super(ChangePointDetectResponse, self).__init__(**kwargs) self.period = None self.is_change_point = is_change_point self.confidence_scores = confidence_scores +class CorrelationChanges(msrest.serialization.Model): + """CorrelationChanges. + + :ivar changed_variables: correlated variables. + :vartype changed_variables: list[str] + :ivar changed_values: changes in correlation. + :vartype changed_values: list[float] + """ + + _attribute_map = { + 'changed_variables': {'key': 'changedVariables', 'type': '[str]'}, + 'changed_values': {'key': 'changedValues', 'type': '[float]'}, + } + + def __init__( + self, + *, + changed_variables: Optional[List[str]] = None, + changed_values: Optional[List[float]] = None, + **kwargs + ): + """ + :keyword changed_variables: correlated variables. + :paramtype changed_variables: list[str] + :keyword changed_values: changes in correlation. + :paramtype changed_values: list[float] + """ + super(CorrelationChanges, self).__init__(**kwargs) + self.changed_variables = changed_variables + self.changed_values = changed_values + + class DetectionRequest(msrest.serialization.Model): - """Request to submit a detection. + """Detection request. All required parameters must be populated in order to send to Azure. - :param source: Required. source file link of the input variables, each variable will be a csv - with two columns, the first column will be timestamp, the second column will be value.Besides - these variable csv files, a extra meta.json can be included in th zip file if you would like to - rename a variable.Be default, the file name of the variable will be used as the variable name. - The variables used in detection should be consistent with variables in the model used for - detection. - :type source: str - :param start_time: Required. A require field, start time of data be used for detection, should - be date-time. - :type start_time: ~datetime.datetime - :param end_time: Required. A require field, end time of data be used for detection, should be - date-time. - :type end_time: ~datetime.datetime + :ivar source: Required. Source link to the input variables. Each variable should be a csv with + two columns, ``timestamp`` and ``value``. The file name of the variable will be used as its + name. The variables used in detection should be exactly the same with those used in the + training phase. + :vartype source: str + :ivar start_time: Required. A required field, indicating the start time of data for detection. + Should be date-time. + :vartype start_time: ~datetime.datetime + :ivar end_time: Required. A required field, indicating the end time of data for detection. + Should be date-time. + :vartype end_time: ~datetime.datetime """ _validation = { @@ -336,6 +442,19 @@ def __init__( end_time: datetime.datetime, **kwargs ): + """ + :keyword source: Required. Source link to the input variables. Each variable should be a csv + with two columns, ``timestamp`` and ``value``. The file name of the variable will be used as + its name. The variables used in detection should be exactly the same with those used in the + training phase. + :paramtype source: str + :keyword start_time: Required. A required field, indicating the start time of data for + detection. Should be date-time. + :paramtype start_time: ~datetime.datetime + :keyword end_time: Required. A required field, indicating the end time of data for detection. + Should be date-time. + :paramtype end_time: ~datetime.datetime + """ super(DetectionRequest, self).__init__(**kwargs) self.source = source self.start_time = start_time @@ -343,16 +462,16 @@ def __init__( class DetectionResult(msrest.serialization.Model): - """Anomaly Response of one detection corresponds to a resultId. + """Response of the given resultId. All required parameters must be populated in order to send to Azure. - :param result_id: Required. - :type result_id: str - :param summary: Required. Multivariate anomaly detection status. - :type summary: ~azure.ai.anomalydetector.models.DetectionResultSummary - :param results: Required. anomaly status of each timestamp. - :type results: list[~azure.ai.anomalydetector.models.AnomalyState] + :ivar result_id: Required. + :vartype result_id: str + :ivar summary: Required. + :vartype summary: ~azure.ai.anomalydetector.models.DetectionResultSummary + :ivar results: Required. Detection result for each timestamp. + :vartype results: list[~azure.ai.anomalydetector.models.AnomalyState] """ _validation = { @@ -375,6 +494,14 @@ def __init__( results: List["AnomalyState"], **kwargs ): + """ + :keyword result_id: Required. + :paramtype result_id: str + :keyword summary: Required. + :paramtype summary: ~azure.ai.anomalydetector.models.DetectionResultSummary + :keyword results: Required. Detection result for each timestamp. + :paramtype results: list[~azure.ai.anomalydetector.models.AnomalyState] + """ super(DetectionResult, self).__init__(**kwargs) self.result_id = result_id self.summary = summary @@ -386,15 +513,15 @@ class DetectionResultSummary(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param status: Required. Multivariate anomaly detection status. Possible values include: - "CREATED", "RUNNING", "READY", "FAILED". - :type status: str or ~azure.ai.anomalydetector.models.DetectionStatus - :param errors: Error message when creating or training model fails. - :type errors: list[~azure.ai.anomalydetector.models.ErrorResponse] - :param variable_states: - :type variable_states: list[~azure.ai.anomalydetector.models.VariableState] - :param setup_info: Required. Request when creating the model. - :type setup_info: ~azure.ai.anomalydetector.models.DetectionRequest + :ivar status: Required. Status of detection results. One of CREATED, RUNNING, READY, and + FAILED. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". + :vartype status: str or ~azure.ai.anomalydetector.models.DetectionStatus + :ivar errors: Error message when detection is failed. + :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar variable_states: + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :ivar setup_info: Required. Detection request. + :vartype setup_info: ~azure.ai.anomalydetector.models.DetectionRequest """ _validation = { @@ -418,6 +545,17 @@ def __init__( variable_states: Optional[List["VariableState"]] = None, **kwargs ): + """ + :keyword status: Required. Status of detection results. One of CREATED, RUNNING, READY, and + FAILED. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". + :paramtype status: str or ~azure.ai.anomalydetector.models.DetectionStatus + :keyword errors: Error message when detection is failed. + :paramtype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :keyword variable_states: + :paramtype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :keyword setup_info: Required. Detection request. + :paramtype setup_info: ~azure.ai.anomalydetector.models.DetectionRequest + """ super(DetectionResultSummary, self).__init__(**kwargs) self.status = status self.errors = errors @@ -426,34 +564,41 @@ def __init__( class DetectRequest(msrest.serialization.Model): - """DetectRequest. + """The request of entire or last anomaly detection. All required parameters must be populated in order to send to Azure. - :param series: Required. Time series data points. Points should be sorted by timestamp in + :ivar series: Required. Time series data points. Points should be sorted by timestamp in ascending order to match the anomaly detection result. If the data is not sorted correctly or there is duplicated timestamp, the API will not work. In such case, an error message will be returned. - :type series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] - :param granularity: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, + :vartype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :ivar granularity: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, minutely, secondly, microsecond or none. If granularity is not present, it will be none by default. If granularity is none, the timestamp property in time series point can be absent. Possible values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", "secondly", "microsecond", "none". - :type granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity - :param custom_interval: Custom Interval is used to set non-standard time interval, for example, + :vartype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :ivar custom_interval: Custom Interval is used to set non-standard time interval, for example, if the series is 5 minutes, request can be set as {"granularity":"minutely", "customInterval":5}. - :type custom_interval: int - :param period: Optional argument, periodic value of a time series. If the value is null or does + :vartype custom_interval: int + :ivar period: Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - :type period: int - :param max_anomaly_ratio: Optional argument, advanced model parameter, max anomaly ratio in a + :vartype period: int + :ivar max_anomaly_ratio: Optional argument, advanced model parameter, max anomaly ratio in a time series. - :type max_anomaly_ratio: float - :param sensitivity: Optional argument, advanced model parameter, between 0-99, the lower the + :vartype max_anomaly_ratio: float + :ivar sensitivity: Optional argument, advanced model parameter, between 0-99, the lower the value is, the larger the margin value will be which means less anomalies will be accepted. - :type sensitivity: int + :vartype sensitivity: int + :ivar impute_mode: Used to specify how to deal with missing values in the input series, it's + used when granularity is not "none". Possible values include: "auto", "previous", "linear", + "fixed", "zero", "notFill". + :vartype impute_mode: str or ~azure.ai.anomalydetector.models.ImputeMode + :ivar impute_fixed_value: Used to specify the value to fill, it's used when granularity is not + "none" and imputeMode is "fixed". + :vartype impute_fixed_value: float """ _validation = { @@ -467,6 +612,8 @@ class DetectRequest(msrest.serialization.Model): 'period': {'key': 'period', 'type': 'int'}, 'max_anomaly_ratio': {'key': 'maxAnomalyRatio', 'type': 'float'}, 'sensitivity': {'key': 'sensitivity', 'type': 'int'}, + 'impute_mode': {'key': 'imputeMode', 'type': 'str'}, + 'impute_fixed_value': {'key': 'imputeFixedValue', 'type': 'float'}, } def __init__( @@ -478,8 +625,43 @@ def __init__( period: Optional[int] = None, max_anomaly_ratio: Optional[float] = None, sensitivity: Optional[int] = None, + impute_mode: Optional[Union[str, "ImputeMode"]] = None, + impute_fixed_value: Optional[float] = None, **kwargs ): + """ + :keyword series: Required. Time series data points. Points should be sorted by timestamp in + ascending order to match the anomaly detection result. If the data is not sorted correctly or + there is duplicated timestamp, the API will not work. In such case, an error message will be + returned. + :paramtype series: list[~azure.ai.anomalydetector.models.TimeSeriesPoint] + :keyword granularity: Optional argument, can be one of yearly, monthly, weekly, daily, hourly, + minutely, secondly, microsecond or none. If granularity is not present, it will be none by + default. If granularity is none, the timestamp property in time series point can be absent. + Possible values include: "yearly", "monthly", "weekly", "daily", "hourly", "minutely", + "secondly", "microsecond", "none". + :paramtype granularity: str or ~azure.ai.anomalydetector.models.TimeGranularity + :keyword custom_interval: Custom Interval is used to set non-standard time interval, for + example, if the series is 5 minutes, request can be set as {"granularity":"minutely", + "customInterval":5}. + :paramtype custom_interval: int + :keyword period: Optional argument, periodic value of a time series. If the value is null or + does not present, the API will determine the period automatically. + :paramtype period: int + :keyword max_anomaly_ratio: Optional argument, advanced model parameter, max anomaly ratio in a + time series. + :paramtype max_anomaly_ratio: float + :keyword sensitivity: Optional argument, advanced model parameter, between 0-99, the lower the + value is, the larger the margin value will be which means less anomalies will be accepted. + :paramtype sensitivity: int + :keyword impute_mode: Used to specify how to deal with missing values in the input series, it's + used when granularity is not "none". Possible values include: "auto", "previous", "linear", + "fixed", "zero", "notFill". + :paramtype impute_mode: str or ~azure.ai.anomalydetector.models.ImputeMode + :keyword impute_fixed_value: Used to specify the value to fill, it's used when granularity is + not "none" and imputeMode is "fixed". + :paramtype impute_fixed_value: float + """ super(DetectRequest, self).__init__(**kwargs) self.series = series self.granularity = granularity @@ -487,15 +669,17 @@ def __init__( self.period = period self.max_anomaly_ratio = max_anomaly_ratio self.sensitivity = sensitivity + self.impute_mode = impute_mode + self.impute_fixed_value = impute_fixed_value class DiagnosticsInfo(msrest.serialization.Model): """DiagnosticsInfo. - :param model_state: - :type model_state: ~azure.ai.anomalydetector.models.ModelState - :param variable_states: - :type variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :ivar model_state: + :vartype model_state: ~azure.ai.anomalydetector.models.ModelState + :ivar variable_states: + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] """ _attribute_map = { @@ -510,47 +694,56 @@ def __init__( variable_states: Optional[List["VariableState"]] = None, **kwargs ): + """ + :keyword model_state: + :paramtype model_state: ~azure.ai.anomalydetector.models.ModelState + :keyword variable_states: + :paramtype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + """ super(DiagnosticsInfo, self).__init__(**kwargs) self.model_state = model_state self.variable_states = variable_states class EntireDetectResponse(msrest.serialization.Model): - """EntireDetectResponse. + """The response of entire anomaly detection. All required parameters must be populated in order to send to Azure. - :param period: Required. Frequency extracted from the series, zero means no recurrent pattern + :ivar period: Required. Frequency extracted from the series, zero means no recurrent pattern has been found. - :type period: int - :param expected_values: Required. ExpectedValues contain expected value for each input point. + :vartype period: int + :ivar expected_values: Required. ExpectedValues contain expected value for each input point. The index of the array is consistent with the input series. - :type expected_values: list[float] - :param upper_margins: Required. UpperMargins contain upper margin of each input point. + :vartype expected_values: list[float] + :ivar upper_margins: Required. UpperMargins contain upper margin of each input point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. Anomalies in response can be filtered by upperBoundary and lowerBoundary. By adjusting marginScale value, less significant anomalies can be filtered in client side. The index of the array is consistent with the input series. - :type upper_margins: list[float] - :param lower_margins: Required. LowerMargins contain lower margin of each input point. + :vartype upper_margins: list[float] + :ivar lower_margins: Required. LowerMargins contain lower margin of each input point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. Points between the boundary can be marked as normal ones in client side. The index of the array is consistent with the input series. - :type lower_margins: list[float] - :param is_anomaly: Required. IsAnomaly contains anomaly properties for each input point. True + :vartype lower_margins: list[float] + :ivar is_anomaly: Required. IsAnomaly contains anomaly properties for each input point. True means an anomaly either negative or positive has been detected. The index of the array is consistent with the input series. - :type is_anomaly: list[bool] - :param is_negative_anomaly: Required. IsNegativeAnomaly contains anomaly status in negative + :vartype is_anomaly: list[bool] + :ivar is_negative_anomaly: Required. IsNegativeAnomaly contains anomaly status in negative direction for each input point. True means a negative anomaly has been detected. A negative anomaly means the point is detected as an anomaly and its real value is smaller than the expected one. The index of the array is consistent with the input series. - :type is_negative_anomaly: list[bool] - :param is_positive_anomaly: Required. IsPositiveAnomaly contain anomaly status in positive + :vartype is_negative_anomaly: list[bool] + :ivar is_positive_anomaly: Required. IsPositiveAnomaly contain anomaly status in positive direction for each input point. True means a positive anomaly has been detected. A positive anomaly means the point is detected as an anomaly and its real value is larger than the expected one. The index of the array is consistent with the input series. - :type is_positive_anomaly: list[bool] + :vartype is_positive_anomaly: list[bool] + :ivar severity: The severity score for each input point. The larger the value is, the more + sever the anomaly is. For normal points, the "severity" is always 0. + :vartype severity: list[float] """ _validation = { @@ -571,6 +764,7 @@ class EntireDetectResponse(msrest.serialization.Model): 'is_anomaly': {'key': 'isAnomaly', 'type': '[bool]'}, 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': '[bool]'}, 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': '[bool]'}, + 'severity': {'key': 'severity', 'type': '[float]'}, } def __init__( @@ -583,8 +777,45 @@ def __init__( is_anomaly: List[bool], is_negative_anomaly: List[bool], is_positive_anomaly: List[bool], + severity: Optional[List[float]] = None, **kwargs ): + """ + :keyword period: Required. Frequency extracted from the series, zero means no recurrent pattern + has been found. + :paramtype period: int + :keyword expected_values: Required. ExpectedValues contain expected value for each input point. + The index of the array is consistent with the input series. + :paramtype expected_values: list[float] + :keyword upper_margins: Required. UpperMargins contain upper margin of each input point. + UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - + marginScale)*upperMargin. Anomalies in response can be filtered by upperBoundary and + lowerBoundary. By adjusting marginScale value, less significant anomalies can be filtered in + client side. The index of the array is consistent with the input series. + :paramtype upper_margins: list[float] + :keyword lower_margins: Required. LowerMargins contain lower margin of each input point. + LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - + marginScale)*lowerMargin. Points between the boundary can be marked as normal ones in client + side. The index of the array is consistent with the input series. + :paramtype lower_margins: list[float] + :keyword is_anomaly: Required. IsAnomaly contains anomaly properties for each input point. True + means an anomaly either negative or positive has been detected. The index of the array is + consistent with the input series. + :paramtype is_anomaly: list[bool] + :keyword is_negative_anomaly: Required. IsNegativeAnomaly contains anomaly status in negative + direction for each input point. True means a negative anomaly has been detected. A negative + anomaly means the point is detected as an anomaly and its real value is smaller than the + expected one. The index of the array is consistent with the input series. + :paramtype is_negative_anomaly: list[bool] + :keyword is_positive_anomaly: Required. IsPositiveAnomaly contain anomaly status in positive + direction for each input point. True means a positive anomaly has been detected. A positive + anomaly means the point is detected as an anomaly and its real value is larger than the + expected one. The index of the array is consistent with the input series. + :paramtype is_positive_anomaly: list[bool] + :keyword severity: The severity score for each input point. The larger the value is, the more + sever the anomaly is. For normal points, the "severity" is always 0. + :paramtype severity: list[float] + """ super(EntireDetectResponse, self).__init__(**kwargs) self.period = period self.expected_values = expected_values @@ -593,6 +824,7 @@ def __init__( self.is_anomaly = is_anomaly self.is_negative_anomaly = is_negative_anomaly self.is_positive_anomaly = is_positive_anomaly + self.severity = severity class ErrorResponse(msrest.serialization.Model): @@ -600,10 +832,10 @@ class ErrorResponse(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param code: Required. The error Code. - :type code: str - :param message: Required. A message explaining the error reported by the service. - :type message: str + :ivar code: Required. The error code. + :vartype code: str + :ivar message: Required. The message explaining the error reported by the service. + :vartype message: str """ _validation = { @@ -623,41 +855,121 @@ def __init__( message: str, **kwargs ): + """ + :keyword code: Required. The error code. + :paramtype code: str + :keyword message: Required. The message explaining the error reported by the service. + :paramtype message: str + """ super(ErrorResponse, self).__init__(**kwargs) self.code = code self.message = message +class LastDetectionRequest(msrest.serialization.Model): + """LastDetectionRequest. + + All required parameters must be populated in order to send to Azure. + + :ivar variables: Required. variables. + :vartype variables: list[~azure.ai.anomalydetector.models.VariableValues] + :ivar detecting_points: Required. number of timestamps on which the model detects. + :vartype detecting_points: int + """ + + _validation = { + 'variables': {'required': True}, + 'detecting_points': {'required': True}, + } + + _attribute_map = { + 'variables': {'key': 'variables', 'type': '[VariableValues]'}, + 'detecting_points': {'key': 'detectingPoints', 'type': 'int'}, + } + + def __init__( + self, + *, + variables: List["VariableValues"], + detecting_points: int, + **kwargs + ): + """ + :keyword variables: Required. variables. + :paramtype variables: list[~azure.ai.anomalydetector.models.VariableValues] + :keyword detecting_points: Required. number of timestamps on which the model detects. + :paramtype detecting_points: int + """ + super(LastDetectionRequest, self).__init__(**kwargs) + self.variables = variables + self.detecting_points = detecting_points + + +class LastDetectionResult(msrest.serialization.Model): + """LastDetectionResult. + + :ivar variable_states: + :vartype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :ivar results: + :vartype results: list[~azure.ai.anomalydetector.models.AnomalyState] + """ + + _attribute_map = { + 'variable_states': {'key': 'variableStates', 'type': '[VariableState]'}, + 'results': {'key': 'results', 'type': '[AnomalyState]'}, + } + + def __init__( + self, + *, + variable_states: Optional[List["VariableState"]] = None, + results: Optional[List["AnomalyState"]] = None, + **kwargs + ): + """ + :keyword variable_states: + :paramtype variable_states: list[~azure.ai.anomalydetector.models.VariableState] + :keyword results: + :paramtype results: list[~azure.ai.anomalydetector.models.AnomalyState] + """ + super(LastDetectionResult, self).__init__(**kwargs) + self.variable_states = variable_states + self.results = results + + class LastDetectResponse(msrest.serialization.Model): - """LastDetectResponse. + """The response of last anomaly detection. All required parameters must be populated in order to send to Azure. - :param period: Required. Frequency extracted from the series, zero means no recurrent pattern + :ivar period: Required. Frequency extracted from the series, zero means no recurrent pattern has been found. - :type period: int - :param suggested_window: Required. Suggested input series points needed for detecting the - latest point. - :type suggested_window: int - :param expected_value: Required. Expected value of the latest point. - :type expected_value: float - :param upper_margin: Required. Upper margin of the latest point. UpperMargin is used to + :vartype period: int + :ivar suggested_window: Required. Suggested input series points needed for detecting the latest + point. + :vartype suggested_window: int + :ivar expected_value: Required. Expected value of the latest point. + :vartype expected_value: float + :ivar upper_margin: Required. Upper margin of the latest point. UpperMargin is used to calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. If the value of latest point is between upperBoundary and lowerBoundary, it should be treated as normal value. By adjusting marginScale value, anomaly status of latest point can be changed. - :type upper_margin: float - :param lower_margin: Required. Lower margin of the latest point. LowerMargin is used to + :vartype upper_margin: float + :ivar lower_margin: Required. Lower margin of the latest point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. - :type lower_margin: float - :param is_anomaly: Required. Anomaly status of the latest point, true means the latest point is + :vartype lower_margin: float + :ivar is_anomaly: Required. Anomaly status of the latest point, true means the latest point is an anomaly either in negative direction or positive direction. - :type is_anomaly: bool - :param is_negative_anomaly: Required. Anomaly status in negative direction of the latest point. + :vartype is_anomaly: bool + :ivar is_negative_anomaly: Required. Anomaly status in negative direction of the latest point. True means the latest point is an anomaly and its real value is smaller than the expected one. - :type is_negative_anomaly: bool - :param is_positive_anomaly: Required. Anomaly status in positive direction of the latest point. + :vartype is_negative_anomaly: bool + :ivar is_positive_anomaly: Required. Anomaly status in positive direction of the latest point. True means the latest point is an anomaly and its real value is larger than the expected one. - :type is_positive_anomaly: bool + :vartype is_positive_anomaly: bool + :ivar severity: The severity score for the last input point. The larger the value is, the more + sever the anomaly is. For normal points, the "severity" is always 0. + :vartype severity: float """ _validation = { @@ -680,6 +992,7 @@ class LastDetectResponse(msrest.serialization.Model): 'is_anomaly': {'key': 'isAnomaly', 'type': 'bool'}, 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': 'bool'}, 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': 'bool'}, + 'severity': {'key': 'severity', 'type': 'float'}, } def __init__( @@ -693,8 +1006,41 @@ def __init__( is_anomaly: bool, is_negative_anomaly: bool, is_positive_anomaly: bool, + severity: Optional[float] = None, **kwargs ): + """ + :keyword period: Required. Frequency extracted from the series, zero means no recurrent pattern + has been found. + :paramtype period: int + :keyword suggested_window: Required. Suggested input series points needed for detecting the + latest point. + :paramtype suggested_window: int + :keyword expected_value: Required. Expected value of the latest point. + :paramtype expected_value: float + :keyword upper_margin: Required. Upper margin of the latest point. UpperMargin is used to + calculate upperBoundary, which equals to expectedValue + (100 - marginScale)*upperMargin. If + the value of latest point is between upperBoundary and lowerBoundary, it should be treated as + normal value. By adjusting marginScale value, anomaly status of latest point can be changed. + :paramtype upper_margin: float + :keyword lower_margin: Required. Lower margin of the latest point. LowerMargin is used to + calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. + :paramtype lower_margin: float + :keyword is_anomaly: Required. Anomaly status of the latest point, true means the latest point + is an anomaly either in negative direction or positive direction. + :paramtype is_anomaly: bool + :keyword is_negative_anomaly: Required. Anomaly status in negative direction of the latest + point. True means the latest point is an anomaly and its real value is smaller than the + expected one. + :paramtype is_negative_anomaly: bool + :keyword is_positive_anomaly: Required. Anomaly status in positive direction of the latest + point. True means the latest point is an anomaly and its real value is larger than the expected + one. + :paramtype is_positive_anomaly: bool + :keyword severity: The severity score for the last input point. The larger the value is, the + more sever the anomaly is. For normal points, the "severity" is always 0. + :paramtype severity: float + """ super(LastDetectResponse, self).__init__(**kwargs) self.period = period self.suggested_window = suggested_window @@ -704,21 +1050,23 @@ def __init__( self.is_anomaly = is_anomaly self.is_negative_anomaly = is_negative_anomaly self.is_positive_anomaly = is_positive_anomaly + self.severity = severity class Model(msrest.serialization.Model): - """Response of get model. + """Response of getting a model. All required parameters must be populated in order to send to Azure. - :param model_id: Required. Model identifier. - :type model_id: str - :param created_time: Required. Date and time (UTC) when the model was created. - :type created_time: ~datetime.datetime - :param last_updated_time: Required. Date and time (UTC) when the model was last updated. - :type last_updated_time: ~datetime.datetime - :param model_info: Training Status of the model. - :type model_info: ~azure.ai.anomalydetector.models.ModelInfo + :ivar model_id: Required. Model identifier. + :vartype model_id: str + :ivar created_time: Required. Date and time (UTC) when the model was created. + :vartype created_time: ~datetime.datetime + :ivar last_updated_time: Required. Date and time (UTC) when the model was last updated. + :vartype last_updated_time: ~datetime.datetime + :ivar model_info: Train result of a model including status, errors and diagnose info for model + and variables. + :vartype model_info: ~azure.ai.anomalydetector.models.ModelInfo """ _validation = { @@ -743,6 +1091,17 @@ def __init__( model_info: Optional["ModelInfo"] = None, **kwargs ): + """ + :keyword model_id: Required. Model identifier. + :paramtype model_id: str + :keyword created_time: Required. Date and time (UTC) when the model was created. + :paramtype created_time: ~datetime.datetime + :keyword last_updated_time: Required. Date and time (UTC) when the model was last updated. + :paramtype last_updated_time: ~datetime.datetime + :keyword model_info: Train result of a model including status, errors and diagnose info for + model and variables. + :paramtype model_info: ~azure.ai.anomalydetector.models.ModelInfo + """ super(Model, self).__init__(**kwargs) self.model_id = model_id self.created_time = created_time @@ -757,32 +1116,29 @@ class ModelInfo(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param sliding_window: An optional field, indicates how many history points will be used to - determine the anomaly score of one subsequent point. - :type sliding_window: int - :param align_policy: An optional field, since those multivariate need to be aligned in the same - timestamp before starting the detection. - :type align_policy: ~azure.ai.anomalydetector.models.AlignPolicy - :param source: Required. source file link of the input variables, each variable will be a csv - with two columns, the first column will be timestamp, the second column will be value.Besides - these variable csv files, an extra meta.json can be included in th zip file if you would like - to rename a variable.Be default, the file name of the variable will be used as the variable - name. - :type source: str - :param start_time: Required. require field, start time of data be used for generating - multivariate anomaly detection model, should be data-time. - :type start_time: ~datetime.datetime - :param end_time: Required. require field, end time of data be used for generating multivariate - anomaly detection model, should be data-time. - :type end_time: ~datetime.datetime - :param display_name: optional field, name of the model. - :type display_name: str + :ivar sliding_window: An optional field, indicating how many previous points will be used to + compute the anomaly score of the subsequent point. + :vartype sliding_window: int + :ivar align_policy: + :vartype align_policy: ~azure.ai.anomalydetector.models.AlignPolicy + :ivar source: Required. Source link to the input variables. Each variable should be a csv file + with two columns, ``timestamp`` and ``value``. By default, the file name of the variable will + be used as its variable name. + :vartype source: str + :ivar start_time: Required. A required field, indicating the start time of training data. + Should be date-time. + :vartype start_time: ~datetime.datetime + :ivar end_time: Required. A required field, indicating the end time of training data. Should be + date-time. + :vartype end_time: ~datetime.datetime + :ivar display_name: An optional field. The name of the model whose maximum length is 24. + :vartype display_name: str :ivar status: Model training status. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". :vartype status: str or ~azure.ai.anomalydetector.models.ModelStatus - :ivar errors: Error message when fails to create a model. + :ivar errors: Error messages when failed to create a model. :vartype errors: list[~azure.ai.anomalydetector.models.ErrorResponse] - :ivar diagnostics_info: Used for deep analysis model and variables. + :ivar diagnostics_info: :vartype diagnostics_info: ~azure.ai.anomalydetector.models.DiagnosticsInfo """ @@ -819,6 +1175,25 @@ def __init__( display_name: Optional[str] = None, **kwargs ): + """ + :keyword sliding_window: An optional field, indicating how many previous points will be used to + compute the anomaly score of the subsequent point. + :paramtype sliding_window: int + :keyword align_policy: + :paramtype align_policy: ~azure.ai.anomalydetector.models.AlignPolicy + :keyword source: Required. Source link to the input variables. Each variable should be a csv + file with two columns, ``timestamp`` and ``value``. By default, the file name of the variable + will be used as its variable name. + :paramtype source: str + :keyword start_time: Required. A required field, indicating the start time of training data. + Should be date-time. + :paramtype start_time: ~datetime.datetime + :keyword end_time: Required. A required field, indicating the end time of training data. Should + be date-time. + :paramtype end_time: ~datetime.datetime + :keyword display_name: An optional field. The name of the model whose maximum length is 24. + :paramtype display_name: str + """ super(ModelInfo, self).__init__(**kwargs) self.sliding_window = sliding_window self.align_policy = align_policy @@ -832,18 +1207,18 @@ def __init__( class ModelList(msrest.serialization.Model): - """Response to the list models operation. + """Response of listing models. All required parameters must be populated in order to send to Azure. - :param models: Required. List of models. - :type models: list[~azure.ai.anomalydetector.models.ModelSnapshot] - :param current_count: Required. Current count of trained multivariate models. - :type current_count: int - :param max_count: Required. Max number of models that can be trained for this subscription. - :type max_count: int - :param next_link: next link to fetch more models. - :type next_link: str + :ivar models: Required. List of models. + :vartype models: list[~azure.ai.anomalydetector.models.ModelSnapshot] + :ivar current_count: Required. Current count of trained multivariate models. + :vartype current_count: int + :ivar max_count: Required. Max number of models that can be trained for this subscription. + :vartype max_count: int + :ivar next_link: The link to fetch more models. + :vartype next_link: str """ _validation = { @@ -868,6 +1243,16 @@ def __init__( next_link: Optional[str] = None, **kwargs ): + """ + :keyword models: Required. List of models. + :paramtype models: list[~azure.ai.anomalydetector.models.ModelSnapshot] + :keyword current_count: Required. Current count of trained multivariate models. + :paramtype current_count: int + :keyword max_count: Required. Max number of models that can be trained for this subscription. + :paramtype max_count: int + :keyword next_link: The link to fetch more models. + :paramtype next_link: str + """ super(ModelList, self).__init__(**kwargs) self.models = models self.current_count = current_count @@ -882,19 +1267,19 @@ class ModelSnapshot(msrest.serialization.Model): All required parameters must be populated in order to send to Azure. - :param model_id: Required. Model identifier. - :type model_id: str - :param created_time: Required. Date and time (UTC) when the model was created. - :type created_time: ~datetime.datetime - :param last_updated_time: Required. Date and time (UTC) when the model was last updated. - :type last_updated_time: ~datetime.datetime + :ivar model_id: Required. Model identifier. + :vartype model_id: str + :ivar created_time: Required. Date and time (UTC) when the model was created. + :vartype created_time: ~datetime.datetime + :ivar last_updated_time: Required. Date and time (UTC) when the model was last updated. + :vartype last_updated_time: ~datetime.datetime :ivar status: Required. Model training status. Possible values include: "CREATED", "RUNNING", "READY", "FAILED". :vartype status: str or ~azure.ai.anomalydetector.models.ModelStatus - :param display_name: - :type display_name: str - :param variables_count: Required. Count of variables. - :type variables_count: int + :ivar display_name: + :vartype display_name: str + :ivar variables_count: Required. Total number of variables. + :vartype variables_count: int """ _validation = { @@ -924,6 +1309,18 @@ def __init__( display_name: Optional[str] = None, **kwargs ): + """ + :keyword model_id: Required. Model identifier. + :paramtype model_id: str + :keyword created_time: Required. Date and time (UTC) when the model was created. + :paramtype created_time: ~datetime.datetime + :keyword last_updated_time: Required. Date and time (UTC) when the model was last updated. + :paramtype last_updated_time: ~datetime.datetime + :keyword display_name: + :paramtype display_name: str + :keyword variables_count: Required. Total number of variables. + :paramtype variables_count: int + """ super(ModelSnapshot, self).__init__(**kwargs) self.model_id = model_id self.created_time = created_time @@ -936,14 +1333,14 @@ def __init__( class ModelState(msrest.serialization.Model): """ModelState. - :param epoch_ids: Epoch id. - :type epoch_ids: list[int] - :param train_losses: - :type train_losses: list[float] - :param validation_losses: - :type validation_losses: list[float] - :param latencies_in_seconds: - :type latencies_in_seconds: list[float] + :ivar epoch_ids: Epoch id. + :vartype epoch_ids: list[int] + :ivar train_losses: + :vartype train_losses: list[float] + :ivar validation_losses: + :vartype validation_losses: list[float] + :ivar latencies_in_seconds: + :vartype latencies_in_seconds: list[float] """ _attribute_map = { @@ -962,6 +1359,16 @@ def __init__( latencies_in_seconds: Optional[List[float]] = None, **kwargs ): + """ + :keyword epoch_ids: Epoch id. + :paramtype epoch_ids: list[int] + :keyword train_losses: + :paramtype train_losses: list[float] + :keyword validation_losses: + :paramtype validation_losses: list[float] + :keyword latencies_in_seconds: + :paramtype latencies_in_seconds: list[float] + """ super(ModelState, self).__init__(**kwargs) self.epoch_ids = epoch_ids self.train_losses = train_losses @@ -970,14 +1377,14 @@ def __init__( class TimeSeriesPoint(msrest.serialization.Model): - """TimeSeriesPoint. + """The definition of input timeseries points. All required parameters must be populated in order to send to Azure. - :param timestamp: Optional argument, timestamp of a data point (ISO8601 format). - :type timestamp: ~datetime.datetime - :param value: Required. The measurement of that point, should be float. - :type value: float + :ivar timestamp: Optional argument, timestamp of a data point (ISO8601 format). + :vartype timestamp: ~datetime.datetime + :ivar value: Required. The measurement of that point, should be float. + :vartype value: float """ _validation = { @@ -996,6 +1403,12 @@ def __init__( timestamp: Optional[datetime.datetime] = None, **kwargs ): + """ + :keyword timestamp: Optional argument, timestamp of a data point (ISO8601 format). + :paramtype timestamp: ~datetime.datetime + :keyword value: Required. The measurement of that point, should be float. + :paramtype value: float + """ super(TimeSeriesPoint, self).__init__(**kwargs) self.timestamp = timestamp self.value = value @@ -1004,18 +1417,16 @@ def __init__( class VariableState(msrest.serialization.Model): """VariableState. - :param variable: Variable name. - :type variable: str - :param filled_na_ratio: Merged NA ratio of a variable. - :type filled_na_ratio: float - :param effective_count: Effective time-series points count. - :type effective_count: int - :param start_time: Start time of a variable. - :type start_time: ~datetime.datetime - :param end_time: End time of a variable. - :type end_time: ~datetime.datetime - :param errors: Error message when parse variable. - :type errors: list[~azure.ai.anomalydetector.models.ErrorResponse] + :ivar variable: Variable name. + :vartype variable: str + :ivar filled_na_ratio: Proportion of NaN values filled of the variable. + :vartype filled_na_ratio: float + :ivar effective_count: Number of effective points counted. + :vartype effective_count: int + :ivar start_time: Start time of the variable. + :vartype start_time: ~datetime.datetime + :ivar end_time: End time of the variable. + :vartype end_time: ~datetime.datetime """ _validation = { @@ -1028,7 +1439,6 @@ class VariableState(msrest.serialization.Model): 'effective_count': {'key': 'effectiveCount', 'type': 'int'}, 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, - 'errors': {'key': 'errors', 'type': '[ErrorResponse]'}, } def __init__( @@ -1039,13 +1449,70 @@ def __init__( effective_count: Optional[int] = None, start_time: Optional[datetime.datetime] = None, end_time: Optional[datetime.datetime] = None, - errors: Optional[List["ErrorResponse"]] = None, **kwargs ): + """ + :keyword variable: Variable name. + :paramtype variable: str + :keyword filled_na_ratio: Proportion of NaN values filled of the variable. + :paramtype filled_na_ratio: float + :keyword effective_count: Number of effective points counted. + :paramtype effective_count: int + :keyword start_time: Start time of the variable. + :paramtype start_time: ~datetime.datetime + :keyword end_time: End time of the variable. + :paramtype end_time: ~datetime.datetime + """ super(VariableState, self).__init__(**kwargs) self.variable = variable self.filled_na_ratio = filled_na_ratio self.effective_count = effective_count self.start_time = start_time self.end_time = end_time - self.errors = errors + + +class VariableValues(msrest.serialization.Model): + """VariableValues. + + All required parameters must be populated in order to send to Azure. + + :ivar name: Required. variable name. + :vartype name: str + :ivar timestamps: Required. timestamps. + :vartype timestamps: list[str] + :ivar values: Required. values. + :vartype values: list[float] + """ + + _validation = { + 'name': {'required': True}, + 'timestamps': {'required': True}, + 'values': {'required': True}, + } + + _attribute_map = { + 'name': {'key': 'name', 'type': 'str'}, + 'timestamps': {'key': 'timestamps', 'type': '[str]'}, + 'values': {'key': 'values', 'type': '[float]'}, + } + + def __init__( + self, + *, + name: str, + timestamps: List[str], + values: List[float], + **kwargs + ): + """ + :keyword name: Required. variable name. + :paramtype name: str + :keyword timestamps: Required. timestamps. + :paramtype timestamps: list[str] + :keyword values: Required. values. + :paramtype values: list[float] + """ + super(VariableValues, self).__init__(**kwargs) + self.name = name + self.timestamps = timestamps + self.values = values diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/_anomaly_detector_client_operations.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/_anomaly_detector_client_operations.py index c8109491fd7a..2fb3d17ee8dc 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/_anomaly_detector_client_operations.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/_anomaly_detector_client_operations.py @@ -5,25 +5,325 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +import functools from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.paging import ItemPaged from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpRequest, HttpResponse +from azure.core.pipeline.transport import HttpResponse +from azure.core.rest import HttpRequest +from azure.core.tracing.decorator import distributed_trace +from msrest import Serializer from .. import models as _models +from .._vendor import _convert_request, _format_url_section if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, IO, Iterable, Optional, TypeVar - T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False +# fmt: off + +def build_detect_entire_series_request( + **kwargs # type: Any +): + # type: (...) -> HttpRequest + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/timeseries/entire/detect') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_detect_last_point_request( + **kwargs # type: Any +): + # type: (...) -> HttpRequest + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/timeseries/last/detect') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_detect_change_point_request( + **kwargs # type: Any +): + # type: (...) -> HttpRequest + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/timeseries/changepoint/detect') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_train_multivariate_model_request( + **kwargs # type: Any +): + # type: (...) -> HttpRequest + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/models') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_list_multivariate_model_request( + **kwargs # type: Any +): + # type: (...) -> HttpRequest + skip = kwargs.pop('skip', 0) # type: Optional[int] + top = kwargs.pop('top', 5) # type: Optional[int] + + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/models') + + # Construct parameters + query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + if skip is not None: + query_parameters['$skip'] = _SERIALIZER.query("skip", skip, 'int') + if top is not None: + query_parameters['$top'] = _SERIALIZER.query("top", top, 'int') + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + params=query_parameters, + headers=header_parameters, + **kwargs + ) + + +def build_get_multivariate_model_request( + model_id, # type: str + **kwargs # type: Any +): + # type: (...) -> HttpRequest + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/models/{modelId}') + path_format_arguments = { + "modelId": _SERIALIZER.url("model_id", model_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_delete_multivariate_model_request( + model_id, # type: str + **kwargs # type: Any +): + # type: (...) -> HttpRequest + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/models/{modelId}') + path_format_arguments = { + "modelId": _SERIALIZER.url("model_id", model_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="DELETE", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_detect_anomaly_request( + model_id, # type: str + **kwargs # type: Any +): + # type: (...) -> HttpRequest + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/models/{modelId}/detect') + path_format_arguments = { + "modelId": _SERIALIZER.url("model_id", model_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_get_detection_result_request( + result_id, # type: str + **kwargs # type: Any +): + # type: (...) -> HttpRequest + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/results/{resultId}') + path_format_arguments = { + "resultId": _SERIALIZER.url("result_id", result_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_export_model_request( + model_id, # type: str + **kwargs # type: Any +): + # type: (...) -> HttpRequest + accept = "application/zip, application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/models/{modelId}/export') + path_format_arguments = { + "modelId": _SERIALIZER.url("model_id", model_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="GET", + url=url, + headers=header_parameters, + **kwargs + ) + + +def build_last_detect_anomaly_request( + model_id, # type: str + **kwargs # type: Any +): + # type: (...) -> HttpRequest + content_type = kwargs.pop('content_type', None) # type: Optional[str] + + accept = "application/json" + # Construct URL + url = kwargs.pop("template_url", '/multivariate/models/{modelId}/last/detect') + path_format_arguments = { + "modelId": _SERIALIZER.url("model_id", model_id, 'str'), + } + + url = _format_url_section(url, **path_format_arguments) + + # Construct headers + header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + if content_type is not None: + header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + + return HttpRequest( + method="POST", + url=url, + headers=header_parameters, + **kwargs + ) + +# fmt: on class AnomalyDetectorClientOperationsMixin(object): + @distributed_trace def detect_entire_series( self, body, # type: "_models.DetectRequest" @@ -39,6 +339,9 @@ def detect_entire_series( :param body: Time series points and period if needed. Advanced model parameters can also be set in the request. :type body: ~azure.ai.anomalydetector.models.DetectRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: EntireDetectResponse, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.EntireDetectResponse @@ -49,34 +352,30 @@ def detect_entire_series( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_entire_series.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'DetectRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_entire_series_request( + content_type=content_type, + json=_json, + template_url=self.detect_entire_series.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(body, 'DetectRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, response) + error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('EntireDetectResponse', pipeline_response) @@ -85,8 +384,11 @@ def detect_entire_series( return cls(pipeline_response, deserialized, {}) return deserialized + detect_entire_series.metadata = {'url': '/timeseries/entire/detect'} # type: ignore + + @distributed_trace def detect_last_point( self, body, # type: "_models.DetectRequest" @@ -102,6 +404,9 @@ def detect_last_point( :param body: Time series points and period if needed. Advanced model parameters can also be set in the request. :type body: ~azure.ai.anomalydetector.models.DetectRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: LastDetectResponse, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.LastDetectResponse @@ -112,34 +417,30 @@ def detect_last_point( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_last_point.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'DetectRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_last_point_request( + content_type=content_type, + json=_json, + template_url=self.detect_last_point.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(body, 'DetectRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, response) + error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('LastDetectResponse', pipeline_response) @@ -148,8 +449,11 @@ def detect_last_point( return cls(pipeline_response, deserialized, {}) return deserialized + detect_last_point.metadata = {'url': '/timeseries/last/detect'} # type: ignore + + @distributed_trace def detect_change_point( self, body, # type: "_models.ChangePointDetectRequest" @@ -163,6 +467,9 @@ def detect_change_point( :param body: Time series points and granularity is needed. Advanced model parameters can also be set in the request if needed. :type body: ~azure.ai.anomalydetector.models.ChangePointDetectRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: ChangePointDetectResponse, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.ChangePointDetectResponse @@ -173,34 +480,30 @@ def detect_change_point( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_change_point.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'ChangePointDetectRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_change_point_request( + content_type=content_type, + json=_json, + template_url=self.detect_change_point.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(body, 'ChangePointDetectRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, response) + error = self._deserialize.failsafe_deserialize(_models.AnomalyDetectorError, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('ChangePointDetectResponse', pipeline_response) @@ -209,11 +512,14 @@ def detect_change_point( return cls(pipeline_response, deserialized, {}) return deserialized + detect_change_point.metadata = {'url': '/timeseries/changepoint/detect'} # type: ignore + + @distributed_trace def train_multivariate_model( self, - model_request, # type: "_models.ModelInfo" + body, # type: "_models.ModelInfo" **kwargs # type: Any ): # type: (...) -> None @@ -225,8 +531,11 @@ def train_multivariate_model( Each time-series will be in a single CSV file in which the first column is timestamp and the second column is value. - :param model_request: Training request. - :type model_request: ~azure.ai.anomalydetector.models.ModelInfo + :param body: Training request. + :type body: ~azure.ai.anomalydetector.models.ModelInfo + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None @@ -237,44 +546,136 @@ def train_multivariate_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.train_multivariate_model.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'ModelInfo') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_train_multivariate_model_request( + content_type=content_type, + json=_json, + template_url=self.train_multivariate_model.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(model_request, 'ModelInfo') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Location']=self._deserialize('str', response.headers.get('Location')) + if cls: return cls(pipeline_response, None, response_headers) train_multivariate_model.metadata = {'url': '/multivariate/models'} # type: ignore + + @distributed_trace + def list_multivariate_model( + self, + skip=0, # type: Optional[int] + top=5, # type: Optional[int] + **kwargs # type: Any + ): + # type: (...) -> Iterable["_models.ModelList"] + """List Multivariate Models. + + List models of a subscription. + + :param skip: $skip indicates how many models will be skipped. + :type skip: int + :param top: $top indicates how many models will be fetched. + :type top: int + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword callable cls: A custom type or function that will be passed the direct response + :return: An iterator like instance of either ModelList or the result of cls(response) + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.anomalydetector.models.ModelList] + :raises: ~azure.core.exceptions.HttpResponseError + """ + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + cls = kwargs.pop('cls', None) # type: ClsType["_models.ModelList"] + error_map = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError + } + error_map.update(kwargs.pop('error_map', {})) + def prepare_request(next_link=None): + if not next_link: + + request = build_list_multivariate_model_request( + skip=skip, + top=top, + template_url=self.list_multivariate_model.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) + + else: + + request = build_list_multivariate_model_request( + skip=skip, + top=top, + template_url=next_link, + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) + + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.method = "GET" + return request + + def extract_data(pipeline_response): + deserialized = self._deserialize("ModelList", pipeline_response) + list_of_elem = deserialized.models + if cls: + list_of_elem = cls(list_of_elem) + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + request = prepare_request(next_link) + + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + + return ItemPaged( + get_next, extract_data + ) + list_multivariate_model.metadata = {'url': '/multivariate/models'} # type: ignore + + @distributed_trace def get_multivariate_model( self, model_id, # type: str @@ -288,6 +689,9 @@ def get_multivariate_model( :param model_id: Model identifier. :type model_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Model, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.Model @@ -298,30 +702,27 @@ def get_multivariate_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - # Construct URL - url = self.get_multivariate_model.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_get_multivariate_model_request( + model_id=model_id, + template_url=self.get_multivariate_model.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request.url = self._client.format_url(request.url, **path_format_arguments) - request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('Model', pipeline_response) @@ -330,8 +731,11 @@ def get_multivariate_model( return cls(pipeline_response, deserialized, {}) return deserialized + get_multivariate_model.metadata = {'url': '/multivariate/models/{modelId}'} # type: ignore + + @distributed_trace def delete_multivariate_model( self, model_id, # type: str @@ -344,6 +748,9 @@ def delete_multivariate_model( :param model_id: Model identifier. :type model_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None @@ -354,30 +761,27 @@ def delete_multivariate_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - # Construct URL - url = self.delete_multivariate_model.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_delete_multivariate_model_request( + model_id=model_id, + template_url=self.delete_multivariate_model.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request.url = self._client.format_url(request.url, **path_format_arguments) - request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) if cls: @@ -385,10 +789,12 @@ def delete_multivariate_model( delete_multivariate_model.metadata = {'url': '/multivariate/models/{modelId}'} # type: ignore + + @distributed_trace def detect_anomaly( self, model_id, # type: str - detection_request, # type: "_models.DetectionRequest" + body, # type: "_models.DetectionRequest" **kwargs # type: Any ): # type: (...) -> None @@ -403,8 +809,11 @@ def detect_anomaly( :param model_id: Model identifier. :type model_id: str - :param detection_request: Detect anomaly request. - :type detection_request: ~azure.ai.anomalydetector.models.DetectionRequest + :param body: Detect anomaly request. + :type body: ~azure.ai.anomalydetector.models.DetectionRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None @@ -415,45 +824,44 @@ def detect_anomaly( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - content_type = kwargs.pop("content_type", "application/json") - accept = "application/json" - # Construct URL - url = self.detect_anomaly.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), - } - url = self._client.format_url(url, **path_format_arguments) + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + _json = self._serialize.body(body, 'DetectionRequest') - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + request = build_detect_anomaly_request( + model_id=model_id, + content_type=content_type, + json=_json, + template_url=self.detect_anomaly.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - body_content_kwargs = {} # type: Dict[str, Any] - body_content = self._serialize.body(detection_request, 'DetectionRequest') - body_content_kwargs['content'] = body_content - request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Location']=self._deserialize('str', response.headers.get('Location')) + if cls: return cls(pipeline_response, None, response_headers) detect_anomaly.metadata = {'url': '/multivariate/models/{modelId}/detect'} # type: ignore + + @distributed_trace def get_detection_result( self, result_id, # type: str @@ -467,6 +875,9 @@ def get_detection_result( :param result_id: Result identifier. :type result_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DetectionResult, or the result of cls(response) :rtype: ~azure.ai.anomalydetector.models.DetectionResult @@ -477,30 +888,27 @@ def get_detection_result( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - # Construct URL - url = self.get_detection_result.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_get_detection_result_request( + result_id=result_id, + template_url=self.get_detection_result.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'resultId': self._serialize.url("result_id", result_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + request.url = self._client.format_url(request.url, **path_format_arguments) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) raise HttpResponseError(response=response, model=error) deserialized = self._deserialize('DetectionResult', pipeline_response) @@ -509,8 +917,11 @@ def get_detection_result( return cls(pipeline_response, deserialized, {}) return deserialized + get_detection_result.metadata = {'url': '/multivariate/results/{resultId}'} # type: ignore + + @distributed_trace def export_model( self, model_id, # type: str @@ -523,6 +934,9 @@ def export_model( :param model_id: Model identifier. :type model_id: str + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response :return: IO, or the result of cls(response) :rtype: IO @@ -533,119 +947,101 @@ def export_model( 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/zip" - # Construct URL - url = self.export_model.metadata['url'] # type: ignore + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + + + request = build_export_model_request( + model_id=model_id, + template_url=self.export_model.metadata['url'], + ) + request = _convert_request(request) path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - 'modelId': self._serialize.url("model_id", model_id, 'str'), + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), } - url = self._client.format_url(url, **path_format_arguments) - - # Construct parameters - query_parameters = {} # type: Dict[str, Any] + request.url = self._client.format_url(request.url, **path_format_arguments) - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') - - request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=True, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) - response_headers = {} - response_headers['content-type']=self._deserialize('str', response.headers.get('content-type')) deserialized = response.stream_download(self._client._pipeline) if cls: - return cls(pipeline_response, deserialized, response_headers) + return cls(pipeline_response, deserialized, {}) return deserialized + export_model.metadata = {'url': '/multivariate/models/{modelId}/export'} # type: ignore - def list_multivariate_model( + + @distributed_trace + def last_detect_anomaly( self, - skip=0, # type: Optional[int] - top=5, # type: Optional[int] + model_id, # type: str + body, # type: "_models.LastDetectionRequest" **kwargs # type: Any ): - # type: (...) -> Iterable["_models.ModelList"] - """List Multivariate Models. + # type: (...) -> "_models.LastDetectionResult" + """Detect anomalies in the last a few points of the request body. - List models of a subscription. + Synchronized API for anomaly detection. - :param skip: $skip indicates how many models will be skipped. - :type skip: int - :param top: $top indicates how many models will be fetched. - :type top: int + :param model_id: Model identifier. + :type model_id: str + :param body: Request for last detection. + :type body: ~azure.ai.anomalydetector.models.LastDetectionRequest + :keyword api_version: Anomaly Detector API version (for example, v1.0). The default value is + "v1.1-preview.1". Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str :keyword callable cls: A custom type or function that will be passed the direct response - :return: An iterator like instance of either ModelList or the result of cls(response) - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.anomalydetector.models.ModelList] + :return: LastDetectionResult, or the result of cls(response) + :rtype: ~azure.ai.anomalydetector.models.LastDetectionResult :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType["_models.ModelList"] + cls = kwargs.pop('cls', None) # type: ClsType["_models.LastDetectionResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) - accept = "application/json" - def prepare_request(next_link=None): - # Construct headers - header_parameters = {} # type: Dict[str, Any] - header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') + api_version = kwargs.pop('api_version', "v1.1-preview.1") # type: str + content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - if not next_link: - # Construct URL - url = self.list_multivariate_model.metadata['url'] # type: ignore - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - # Construct parameters - query_parameters = {} # type: Dict[str, Any] - if skip is not None: - query_parameters['$skip'] = self._serialize.query("skip", skip, 'int') - if top is not None: - query_parameters['$top'] = self._serialize.query("top", top, 'int') - - request = self._client.get(url, query_parameters, header_parameters) - else: - url = next_link - query_parameters = {} # type: Dict[str, Any] - path_format_arguments = { - 'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), - } - url = self._client.format_url(url, **path_format_arguments) - request = self._client.get(url, query_parameters, header_parameters) - return request + _json = self._serialize.body(body, 'LastDetectionRequest') - def extract_data(pipeline_response): - deserialized = self._deserialize('ModelList', pipeline_response) - list_of_elem = deserialized.models - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.next_link or None, iter(list_of_elem) + request = build_last_detect_anomaly_request( + model_id=model_id, + content_type=content_type, + json=_json, + template_url=self.last_detect_anomaly.metadata['url'], + ) + request = _convert_request(request) + path_format_arguments = { + "Endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + "ApiVersion": self._serialize.url("api_version", api_version, 'str', skip_quote=True), + } + request.url = self._client.format_url(request.url, **path_format_arguments) - def get_next(next_link=None): - request = prepare_request(next_link) + pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + response = pipeline_response.http_response - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) - response = pipeline_response.http_response + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response) + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response) - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response, model=error) + deserialized = self._deserialize('LastDetectionResult', pipeline_response) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + + last_detect_anomaly.metadata = {'url': '/multivariate/models/{modelId}/last/detect'} # type: ignore - return ItemPaged( - get_next, extract_data - ) - list_multivariate_model.metadata = {'url': '/multivariate/models'} # type: ignore From 9e64cd6f2ea63d1efa2a2c9584c56c1314627e98 Mon Sep 17 00:00:00 2001 From: Travis Prescott Date: Wed, 15 Dec 2021 15:28:05 -0800 Subject: [PATCH 2/4] Bump version to 3.0.0b4. --- sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md | 4 ++++ .../azure/ai/anomalydetector/_version.py | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md index 44bc2617046a..84e822d5b730 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md +++ b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 3.0.0b4 (Unreleased) + +# TODO: Service team fill out + ## 3.0.0b3 (2021-04-16) **Features** diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py index 1de4e6f8264d..2682d7c4c12d 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "3.0.0b3" +VERSION = "3.0.0b4" From bb3c0b7e4b5765a6ef4e62d13810e447e81e17cb Mon Sep 17 00:00:00 2001 From: Chu Wang Date: Wed, 5 Jan 2022 06:20:50 +0800 Subject: [PATCH 3/4] add mvad/uvad python sdk sample for v1.1-preview.1 (#22241) * add mvad sample for v1.1-preview.1 * modify * fix exception error * modify Readme.md * modify changelog * modify format for change log file Co-authored-by: Chu__Wang --- .../azure-ai-anomalydetector/CHANGELOG.md | 10 ++++- .../samples/README.md | 1 + .../samples/sample_detect_change_point.py | 5 +-- .../sample_detect_entire_series_anomaly.py | 4 +- .../sample_detect_last_point_anomaly.py | 4 +- .../samples/sample_multivariate_detect.py | 42 +++++++++++++++++-- 6 files changed, 52 insertions(+), 14 deletions(-) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md index 84e822d5b730..81e4f1bddc8f 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md +++ b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md @@ -1,8 +1,14 @@ # Release History -## 3.0.0b4 (Unreleased) +## 3.0.0b4 (2021-12-20) -# TODO: Service team fill out + **Features** + - Introduced the new API: `AnomalyDetectorClientOperationsMixin.last_detect_anomaly`. + - Added 2 new optional properties: `impute_mode` & `impute_fixed_value` to `DetectRequest` object. + - Added 1 new optional property: `severity` to the `EntireDetectResponse` & `LastDetectResponse` objects. + - Removed the optional property `errors` from the `VariableState` object. + - Refactored the optional property `contributors` to `interpretation` from the `AnomalyValue` object. + - Modified the `FillNAMethod` object into an extensible enum. ## 3.0.0b3 (2021-04-16) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/samples/README.md b/sdk/anomalydetector/azure-ai-anomalydetector/samples/README.md index 298c608768f2..8b3436dc1152 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/samples/README.md +++ b/sdk/anomalydetector/azure-ai-anomalydetector/samples/README.md @@ -20,6 +20,7 @@ These sample programs show common scenarios for the Anomaly Detector client's of |[sample_detect_entire_series_anomaly.py][sample_detect_entire_series_anomaly] |Detecting anomalies in the entire time series.| |[sample_detect_last_point_anomaly.py][sample_detect_last_point_anomaly] |Detecting the anomaly status of the latest data point.| |[sample_detect_change_point.py][sample_detect_change_point] |Detecting change points in the entire time series.| +|[sample_multivariate_detect.py][sample_multivariate_detect] |Detecting anomalies in the multivariate time series.| ## Prerequisites * Python 2.7 or 3.5 or higher is required to use this package. diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_change_point.py b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_change_point.py index f2f0eb64e6d3..4dcf49b8e3c4 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_change_point.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_change_point.py @@ -64,10 +64,9 @@ def detect_change_point(self): try: response = client.detect_change_point(request) - except AnomalyDetectorError as e: - print('Error code: {}'.format(e.error.code), 'Error message: {}'.format(e.error.message)) + except Exception as e: - print(e) + print('Error code: {}'.format(e.error.code), 'Error message: {}'.format(e.error.message)) if any(response.is_change_point): print('An change point was detected at index:') diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_entire_series_anomaly.py b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_entire_series_anomaly.py index 941e381d9cd0..0b1dede0b854 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_entire_series_anomaly.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_entire_series_anomaly.py @@ -64,10 +64,8 @@ def detect_entire_series(self): try: response = client.detect_entire_series(request) - except AnomalyDetectorError as e: - print('Error code: {}'.format(e.error.code), 'Error message: {}'.format(e.error.message)) except Exception as e: - print(e) + print('Error code: {}'.format(e.error.code), 'Error message: {}'.format(e.error.message)) if any(response.is_anomaly): print('An anomaly was detected at index:') diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_last_point_anomaly.py b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_last_point_anomaly.py index d8557583396c..3d1788d317be 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_last_point_anomaly.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_detect_last_point_anomaly.py @@ -64,10 +64,8 @@ def detect_last_point(self): try: response = client.detect_last_point(request) - except AnomalyDetectorError as e: - print('Error code: {}'.format(e.error.code), 'Error message: {}'.format(e.error.message)) except Exception as e: - print(e) + print('Error code: {}'.format(e.error.code), 'Error message: {}'.format(e.error.message)) if response.is_anomaly: print('The latest point is detected as anomaly.') diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py index 67779706d6cd..aa260e73477b 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py +++ b/sdk/anomalydetector/azure-ai-anomalydetector/samples/sample_multivariate_detect.py @@ -24,12 +24,11 @@ from datetime import datetime, timezone from azure.ai.anomalydetector import AnomalyDetectorClient -from azure.ai.anomalydetector.models import DetectionRequest, ModelInfo +from azure.ai.anomalydetector.models import DetectionRequest, ModelInfo, LastDetectionRequest from azure.ai.anomalydetector.models import ModelStatus, DetectionStatus from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import HttpResponseError - class MultivariateSample: def __init__(self, subscription_key, anomaly_detector_endpoint, data_source=None): @@ -142,6 +141,14 @@ def delete_model(self, model_id): print("{:d} available models after deletion.".format(len(model_list_after_delete))) + def last_detect(self, model_id, variables, detecting_points): + + # Detect anomaly by sync api + last_detection_req = LastDetectionRequest(variables=variables, detecting_points=detecting_points) + r = self.ad_client.last_detect_anomaly(model_id, last_detection_req) + print("Get last detection result") + return r + if __name__ == '__main__': SUBSCRIPTION_KEY = os.environ["ANOMALY_DETECTOR_KEY"] ANOMALY_DETECTOR_ENDPOINT = os.environ["ANOMALY_DETECTOR_ENDPOINT"] @@ -159,7 +166,7 @@ def delete_model(self, model_id): datetime(2021, 1, 2, 12, 0, 0, tzinfo=timezone.utc)) assert model_id is not None - # Reference + # Inference result = sample.detect(model_id, datetime(2021, 1, 2, 12, 0, 0, tzinfo=timezone.utc), datetime(2021, 1, 3, 0, 0, 0, tzinfo=timezone.utc)) assert result is not None @@ -173,3 +180,32 @@ def delete_model(self, model_id): # Delete model sample.delete_model(model_id) + + # ******************************************************************************************************************* + # use your own inference data sending to last detection api, you should define your own variables and detectingPoints + # ***************************************************************************************************************** + # define "" + variables = [ + { + "name": "variables_name1", + "timestamps": ['2021-01-01T00:00:00Z', '2021-01-01T00:01:00Z', ...], + "values": [0, 0, ...] + }, + { + "name": "variables_name2", + "timestamps": ['2021-01-01T00:00:00Z', '2021-01-01T00:01:00Z', ...], + "values": [0, 0, ...] + } + ] + # define " + detectingPoints = 10 + + # Last detection + last_detect_result = sample.last_detect(model_id, variables, detectingPoints) + + assert last_detect_result is not None + + print("Variable States:\t", last_detect_result.variable_states) + print("Variable States length:\t", len(last_detect_result.variable_states)) + print("Results:\t", last_detect_result.results) + print("Results length:\t", len(last_detect_result.results)) From d7606cc35e63d07f4e870e6e6a62a68033114006 Mon Sep 17 00:00:00 2001 From: Laurent Mazuel Date: Thu, 13 Jan 2022 13:00:27 -0800 Subject: [PATCH 4/4] Update CHANGELOG.md --- sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md index 81e4f1bddc8f..a6b18214dd36 100644 --- a/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md +++ b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 3.0.0b4 (2021-12-20) +## 3.0.0b4 (2022-01-18) **Features** - Introduced the new API: `AnomalyDetectorClientOperationsMixin.last_detect_anomaly`.