diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md new file mode 100644 index 000000000000..5ef43195f053 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/CHANGELOG.md @@ -0,0 +1,5 @@ +# Release History + +## 3.0.0b1 (2020-08-17) + + - Initial Release diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/MANIFEST.in b/sdk/anomalydetector/azure-ai-anomalydetector/MANIFEST.in new file mode 100644 index 000000000000..bde85ca9d6c8 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/MANIFEST.in @@ -0,0 +1,5 @@ +recursive-include tests *.py *.yaml +include *.md +include azure/__init__.py +include azure/ai/__init__.py + diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/README.md b/sdk/anomalydetector/azure-ai-anomalydetector/README.md new file mode 100644 index 000000000000..277d153b8256 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/README.md @@ -0,0 +1,22 @@ +# Microsoft Azure SDK for Python + +This is the Microsoft Azure Cognitive Services Anomaly Detector Client Library. +This package has been tested with Python 2.7, 3.5, 3.6, 3.7 and 3.8. + +For a more complete set of Azure libraries, see the +[azure sdk python release](https://aka.ms/azsdk/python/all). + +# Usage + +For code examples, see [Cognitive Services Anomaly Detector](https://docs.microsoft.com/python/api/overview/azure/cognitive-services) +on docs.microsoft.com. + + +# Provide Feedback + +If you encounter any bugs or have suggestions, please file an issue in the +[Issues](https://github.com/Azure/azure-sdk-for-python/issues) +section of the project. + + +![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-python%2Fazure-cognitiveservices-anomalydetector%2FREADME.png) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/__init__.py new file mode 100644 index 000000000000..0260537a02bb --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) \ No newline at end of file diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/__init__.py new file mode 100644 index 000000000000..0260537a02bb --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/__init__.py @@ -0,0 +1 @@ +__path__ = __import__('pkgutil').extend_path(__path__, __name__) \ No newline at end of file diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/__init__.py new file mode 100644 index 000000000000..a55b787999fc --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/__init__.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 ._anomaly_detector_client import AnomalyDetectorClient +from ._version import VERSION + +__version__ = VERSION +__all__ = ['AnomalyDetectorClient'] + +try: + from ._patch import patch_sdk # type: ignore + patch_sdk() +except ImportError: + pass 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 new file mode 100644 index 000000000000..08818e25a366 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_anomaly_detector_client.py @@ -0,0 +1,61 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 typing import TYPE_CHECKING + +from azure.core import PipelineClient +from msrest import Deserializer, Serializer + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import AzureKeyCredential + +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). + :type endpoint: str + """ + + def __init__( + self, + credential, # type: AzureKeyCredential + endpoint, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + base_url = '{Endpoint}/anomalydetector/v1.0' + self._config = AnomalyDetectorClientConfiguration(credential, 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._deserialize = Deserializer(client_models) + + + def close(self): + # type: () -> None + self._client.close() + + def __enter__(self): + # type: () -> AnomalyDetectorClient + self._client.__enter__() + return self + + def __exit__(self, *exc_details): + # type: (Any) -> None + self._client.__exit__(*exc_details) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py new file mode 100644 index 000000000000..1db866bdb626 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_configuration.py @@ -0,0 +1,68 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 typing import TYPE_CHECKING + +from azure.core.configuration import Configuration +from azure.core.pipeline import policies + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any + + from azure.core.credentials import AzureKeyCredential + + +class AnomalyDetectorClientConfiguration(Configuration): + """Configuration for AnomalyDetectorClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :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). + :type endpoint: str + """ + + def __init__( + self, + credential, # type: AzureKeyCredential + endpoint, # type: str + **kwargs # type: Any + ): + # type: (...) -> None + 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 + kwargs.setdefault('sdk_moniker', 'ai-anomalydetector/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs # type: Any + ): + # type: (...) -> None + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + 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) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_metadata.json b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_metadata.json new file mode 100644 index 000000000000..3092456454e2 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_metadata.json @@ -0,0 +1,95 @@ +{ + "chosen_version": "1.0", + "total_api_version_list": ["1.0"], + "client": { + "name": "AnomalyDetectorClient", + "filename": "_anomaly_detector_client", + "description": "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.", + "base_url": null, + "custom_base_url": "\u0027{Endpoint}/anomalydetector/v1.0\u0027", + "azure_arm": false, + "has_lro_operations": false + }, + "global_parameters": { + "sync_method": { + "credential": { + "method_signature": "credential, # type: AzureKeyCredential", + "description": "Credential needed for the client to connect to Azure.", + "docstring_type": "~azure.core.credentials.AzureKeyCredential", + "required": true + }, + "endpoint": { + "method_signature": "endpoint, # type: str", + "description": "Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com).", + "docstring_type": "str", + "required": true + } + }, + "async_method": { + "credential": { + "method_signature": "credential, # type: AzureKeyCredential", + "description": "Credential needed for the client to connect to Azure.", + "docstring_type": "~azure.core.credentials.AzureKeyCredential", + "required": true + }, + "endpoint": { + "method_signature": "endpoint, # type: str", + "description": "Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus2.api.cognitive.microsoft.com).", + "docstring_type": "str", + "required": true + } + }, + "constant": { + }, + "call": "credential, endpoint" + }, + "config": { + "credential": true, + "credential_scopes": null, + "credential_default_policy_type": "AzureKeyCredentialPolicy", + "credential_default_policy_type_has_async_version": false, + "credential_key_header_name": "Ocp-Apim-Subscription-Key" + }, + "operation_groups": { + }, + "operation_mixins": { + "entire_detect" : { + "sync": { + "signature": "def entire_detect(\n self,\n body, # type: \"models.Request\"\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Detect anomalies for the entire series in batch.\n\nThis operation generates a model using an entire series, each point is detected with the same\nmodel. With this method, points before and after a certain point are used to determine whether\nit is an anomaly. The entire detection can give user an overall status of the time series.\n\n:param body: Time series points and period if needed. Advanced model parameters can also be set\n in the request.\n:type body: ~azure.ai.anomalydetector.models.Request\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: EntireDetectResponse, or the result of cls(response)\n:rtype: ~azure.ai.anomalydetector.models.EntireDetectResponse\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def entire_detect(\n self,\n body: \"models.Request\",\n **kwargs\n) -\u003e \"models.EntireDetectResponse\":\n", + "doc": "\"\"\"Detect anomalies for the entire series in batch.\n\nThis operation generates a model using an entire series, each point is detected with the same\nmodel. With this method, points before and after a certain point are used to determine whether\nit is an anomaly. The entire detection can give user an overall status of the time series.\n\n:param body: Time series points and period if needed. Advanced model parameters can also be set\n in the request.\n:type body: ~azure.ai.anomalydetector.models.Request\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: EntireDetectResponse, or the result of cls(response)\n:rtype: ~azure.ai.anomalydetector.models.EntireDetectResponse\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "body" + }, + "last_detect" : { + "sync": { + "signature": "def last_detect(\n self,\n body, # type: \"models.Request\"\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Detect anomaly status of the latest point in time series.\n\nThis operation generates a model using points before the latest one. With this method, only\nhistorical points are used to determine whether the target point is an anomaly. The latest\npoint detecting operation matches the scenario of real-time monitoring of business metrics.\n\n:param body: Time series points and period if needed. Advanced model parameters can also be set\n in the request.\n:type body: ~azure.ai.anomalydetector.models.Request\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: LastDetectResponse, or the result of cls(response)\n:rtype: ~azure.ai.anomalydetector.models.LastDetectResponse\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def last_detect(\n self,\n body: \"models.Request\",\n **kwargs\n) -\u003e \"models.LastDetectResponse\":\n", + "doc": "\"\"\"Detect anomaly status of the latest point in time series.\n\nThis operation generates a model using points before the latest one. With this method, only\nhistorical points are used to determine whether the target point is an anomaly. The latest\npoint detecting operation matches the scenario of real-time monitoring of business metrics.\n\n:param body: Time series points and period if needed. Advanced model parameters can also be set\n in the request.\n:type body: ~azure.ai.anomalydetector.models.Request\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: LastDetectResponse, or the result of cls(response)\n:rtype: ~azure.ai.anomalydetector.models.LastDetectResponse\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "body" + }, + "change_point_detect" : { + "sync": { + "signature": "def change_point_detect(\n self,\n body, # type: \"models.ChangePointDetectRequest\"\n **kwargs # type: Any\n):\n", + "doc": "\"\"\"Detect change point for the entire series.\n\nEvaluate change point score of every series point.\n\n:param body: Time series points and granularity is needed. Advanced model parameters can also\n be set in the request if needed.\n:type body: ~azure.ai.anomalydetector.models.ChangePointDetectRequest\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: ChangePointDetectResponse, or the result of cls(response)\n:rtype: ~azure.ai.anomalydetector.models.ChangePointDetectResponse\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "async": { + "coroutine": true, + "signature": "async def change_point_detect(\n self,\n body: \"models.ChangePointDetectRequest\",\n **kwargs\n) -\u003e \"models.ChangePointDetectResponse\":\n", + "doc": "\"\"\"Detect change point for the entire series.\n\nEvaluate change point score of every series point.\n\n:param body: Time series points and granularity is needed. Advanced model parameters can also\n be set in the request if needed.\n:type body: ~azure.ai.anomalydetector.models.ChangePointDetectRequest\n:keyword callable cls: A custom type or function that will be passed the direct response\n:return: ChangePointDetectResponse, or the result of cls(response)\n:rtype: ~azure.ai.anomalydetector.models.ChangePointDetectResponse\n:raises: ~azure.core.exceptions.HttpResponseError\n\"\"\"" + }, + "call": "body" + } + }, + "sync_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"HttpRequest\", \"HttpResponse\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"Optional\", \"TypeVar\"]}}}", + "async_imports": "{\"regular\": {\"azurecore\": {\"azure.core.exceptions\": [\"HttpResponseError\", \"ResourceExistsError\", \"ResourceNotFoundError\", \"map_error\"], \"azure.core.pipeline\": [\"PipelineResponse\"], \"azure.core.pipeline.transport\": [\"AsyncHttpResponse\", \"HttpRequest\"]}, \"stdlib\": {\"warnings\": [null]}}, \"conditional\": {\"stdlib\": {\"typing\": [\"Any\", \"Callable\", \"Dict\", \"Generic\", \"Optional\", \"TypeVar\"]}}}" +} \ No newline at end of file diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py new file mode 100644 index 000000000000..5819b888fe6e --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +VERSION = "3.0.0b1" 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 new file mode 100644 index 000000000000..9dac254ddfbd --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/__init__.py @@ -0,0 +1,10 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 ._anomaly_detector_client_async import AnomalyDetectorClient +__all__ = ['AnomalyDetectorClient'] diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_anomaly_detector_client_async.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_anomaly_detector_client_async.py new file mode 100644 index 000000000000..be6f209c6abf --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_anomaly_detector_client_async.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 typing import Any + +from azure.core import AsyncPipelineClient +from azure.core.credentials import AzureKeyCredential +from msrest import Deserializer, Serializer + +from ._configuration_async import AnomalyDetectorClientConfiguration +from .operations_async 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). + :type endpoint: str + """ + + def __init__( + self, + credential: AzureKeyCredential, + endpoint: str, + **kwargs: Any + ) -> None: + base_url = '{Endpoint}/anomalydetector/v1.0' + self._config = AnomalyDetectorClientConfiguration(credential, 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._deserialize = Deserializer(client_models) + + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> "AnomalyDetectorClient": + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration_async.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration_async.py new file mode 100644 index 000000000000..1554cc3e4cc6 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/_configuration_async.py @@ -0,0 +1,61 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 typing import Any + +from azure.core.configuration import Configuration +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies + +from .._version import VERSION + + +class AnomalyDetectorClientConfiguration(Configuration): + """Configuration for AnomalyDetectorClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :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). + :type endpoint: str + """ + + def __init__( + self, + credential: AzureKeyCredential, + endpoint: str, + **kwargs: Any + ) -> None: + 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 + kwargs.setdefault('sdk_moniker', 'ai-anomalydetector/{}'.format(VERSION)) + self._configure(**kwargs) + + def _configure( + self, + **kwargs: Any + ) -> None: + self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) + 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) diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations_async/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations_async/__init__.py new file mode 100644 index 000000000000..228b2fe26d48 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations_async/__init__.py @@ -0,0 +1,13 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 ._anomaly_detector_client_operations_async import AnomalyDetectorClientOperationsMixin + +__all__ = [ + 'AnomalyDetectorClientOperationsMixin', +] diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations_async/_anomaly_detector_client_operations_async.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations_async/_anomaly_detector_client_operations_async.py new file mode 100644 index 000000000000..d50db418eac5 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/aio/operations_async/_anomaly_detector_client_operations_async.py @@ -0,0 +1,198 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 typing import Any, Callable, Dict, Generic, Optional, TypeVar +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest + +from ... import models + +T = TypeVar('T') +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] + +class AnomalyDetectorClientOperationsMixin: + + async def entire_detect( + self, + body: "models.Request", + **kwargs + ) -> "models.EntireDetectResponse": + """Detect anomalies for the entire series in batch. + + This operation generates a model using an entire series, each point is detected with the same + model. With this method, points before and after a certain point are used to determine whether + it is an anomaly. The entire detection can give user an overall status of the time 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.Request + :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 + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.EntireDetectResponse"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.entire_detect.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] + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(body, 'Request') + 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(models.APIError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('EntireDetectResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + entire_detect.metadata = {'url': '/timeseries/entire/detect'} # type: ignore + + async def last_detect( + self, + body: "models.Request", + **kwargs + ) -> "models.LastDetectResponse": + """Detect anomaly status of the latest point in time series. + + This operation generates a model using points before the latest one. With this method, only + historical points are used to determine whether the target point is an anomaly. The latest + point detecting operation matches the scenario of real-time monitoring of business metrics. + + :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.Request + :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 + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.LastDetectResponse"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.last_detect.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] + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(body, 'Request') + 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(models.APIError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('LastDetectResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + last_detect.metadata = {'url': '/timeseries/last/detect'} # type: ignore + + async def change_point_detect( + self, + body: "models.ChangePointDetectRequest", + **kwargs + ) -> "models.ChangePointDetectResponse": + """Detect change point for the entire series. + + Evaluate change point score of every series 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 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 + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.ChangePointDetectResponse"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.change_point_detect.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] + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + 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(models.APIError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('ChangePointDetectResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + change_point_detect.metadata = {'url': '/timeseries/changePoint/detect'} # 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 new file mode 100644 index 000000000000..5e200ece70fe --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/__init__.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +try: + from ._models_py3 import APIError + from ._models_py3 import ChangePointDetectRequest + from ._models_py3 import ChangePointDetectResponse + from ._models_py3 import EntireDetectResponse + from ._models_py3 import LastDetectResponse + from ._models_py3 import Point + from ._models_py3 import Request +except (SyntaxError, ImportError): + from ._models import APIError # type: ignore + from ._models import ChangePointDetectRequest # type: ignore + from ._models import ChangePointDetectResponse # type: ignore + from ._models import EntireDetectResponse # type: ignore + from ._models import LastDetectResponse # type: ignore + from ._models import Point # type: ignore + from ._models import Request # type: ignore + +from ._anomaly_detector_client_enums import ( + AnomalyDetectorErrorCodes, + Granularity, +) + +__all__ = [ + 'APIError', + 'ChangePointDetectRequest', + 'ChangePointDetectResponse', + 'EntireDetectResponse', + 'LastDetectResponse', + 'Point', + 'Request', + 'AnomalyDetectorErrorCodes', + 'Granularity', +] 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 new file mode 100644 index 000000000000..5b10529c5ee3 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_anomaly_detector_client_enums.py @@ -0,0 +1,54 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 enum import Enum, EnumMeta +from six import with_metaclass + +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 AnomalyDetectorErrorCodes(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """The error code. + """ + + INVALID_CUSTOM_INTERVAL = "InvalidCustomInterval" + BAD_ARGUMENT = "BadArgument" + INVALID_GRANULARITY = "InvalidGranularity" + INVALID_PERIOD = "InvalidPeriod" + INVALID_MODEL_ARGUMENT = "InvalidModelArgument" + INVALID_SERIES = "InvalidSeries" + INVALID_JSON_FORMAT = "InvalidJsonFormat" + REQUIRED_GRANULARITY = "RequiredGranularity" + REQUIRED_SERIES = "RequiredSeries" + +class Granularity(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): + """Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is + used for verify whether input series is valid. + """ + + YEARLY = "yearly" + MONTHLY = "monthly" + WEEKLY = "weekly" + DAILY = "daily" + HOURLY = "hourly" + MINUTELY = "minutely" + SECONDLY = "secondly" 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 new file mode 100644 index 000000000000..9d78d6220e31 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models.py @@ -0,0 +1,354 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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.exceptions import HttpResponseError +import msrest.serialization + + +class APIError(msrest.serialization.Model): + """Error information returned by the API. + + :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 + """ + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + **kwargs + ): + super(APIError, self).__init__(**kwargs) + self.code = kwargs.get('code', None) + self.message = kwargs.get('message', None) + + +class ChangePointDetectRequest(msrest.serialization.Model): + """ChangePointDetectRequest. + + 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 + ascending order to match the change point detection result. + :type series: list[~azure.ai.anomalydetector.models.Point] + :param 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". + :type granularity: str or ~azure.ai.anomalydetector.models.Granularity + :param 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 + not present, the API will determine the period automatically. + :type period: int + :param 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 + value is, the larger the trend error will be which means less change point will be accepted. + :type threshold: float + """ + + _validation = { + 'series': {'required': True}, + 'granularity': {'required': True}, + } + + _attribute_map = { + 'series': {'key': 'series', 'type': '[Point]'}, + 'granularity': {'key': 'granularity', 'type': 'str'}, + 'custom_interval': {'key': 'customInterval', 'type': 'int'}, + 'period': {'key': 'period', 'type': 'int'}, + 'stable_trend_window': {'key': 'stableTrendWindow', 'type': 'int'}, + 'threshold': {'key': 'threshold', 'type': 'float'}, + } + + def __init__( + self, + **kwargs + ): + super(ChangePointDetectRequest, self).__init__(**kwargs) + self.series = kwargs['series'] + self.granularity = kwargs['granularity'] + self.custom_interval = kwargs.get('custom_interval', None) + self.period = kwargs.get('period', None) + self.stable_trend_window = kwargs.get('stable_trend_window', None) + self.threshold = kwargs.get('threshold', None) + + +class ChangePointDetectResponse(msrest.serialization.Model): + """ChangePointDetectResponse. + + 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 + has been found. + :type period: int + :param is_change_point: Required. 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: Required. the change point confidence of each point. + :type confidence_scores: list[float] + """ + + _validation = { + 'period': {'required': True}, + 'is_change_point': {'required': True}, + 'confidence_scores': {'required': True}, + } + + _attribute_map = { + 'period': {'key': 'period', 'type': 'int'}, + 'is_change_point': {'key': 'isChangePoint', 'type': '[bool]'}, + 'confidence_scores': {'key': 'confidenceScores', 'type': '[float]'}, + } + + def __init__( + self, + **kwargs + ): + super(ChangePointDetectResponse, self).__init__(**kwargs) + self.period = kwargs['period'] + self.is_change_point = kwargs['is_change_point'] + self.confidence_scores = kwargs['confidence_scores'] + + +class EntireDetectResponse(msrest.serialization.Model): + """EntireDetectResponse. + + 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 + has been found. + :type period: int + :param 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. + 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. + 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 + 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 + 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 + 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] + """ + + _validation = { + 'period': {'required': True}, + 'expected_values': {'required': True}, + 'upper_margins': {'required': True}, + 'lower_margins': {'required': True}, + 'is_anomaly': {'required': True}, + 'is_negative_anomaly': {'required': True}, + 'is_positive_anomaly': {'required': True}, + } + + _attribute_map = { + 'period': {'key': 'period', 'type': 'int'}, + 'expected_values': {'key': 'expectedValues', 'type': '[float]'}, + 'upper_margins': {'key': 'upperMargins', 'type': '[float]'}, + 'lower_margins': {'key': 'lowerMargins', 'type': '[float]'}, + 'is_anomaly': {'key': 'isAnomaly', 'type': '[bool]'}, + 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': '[bool]'}, + 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': '[bool]'}, + } + + def __init__( + self, + **kwargs + ): + super(EntireDetectResponse, self).__init__(**kwargs) + self.period = kwargs['period'] + self.expected_values = kwargs['expected_values'] + self.upper_margins = kwargs['upper_margins'] + self.lower_margins = kwargs['lower_margins'] + self.is_anomaly = kwargs['is_anomaly'] + self.is_negative_anomaly = kwargs['is_negative_anomaly'] + self.is_positive_anomaly = kwargs['is_positive_anomaly'] + + +class LastDetectResponse(msrest.serialization.Model): + """LastDetectResponse. + + 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 + 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 + 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 + 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 + 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. + 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. + True means the latest point is an anomaly and its real value is larger than the expected one. + :type is_positive_anomaly: bool + """ + + _validation = { + 'period': {'required': True}, + 'suggested_window': {'required': True}, + 'expected_value': {'required': True}, + 'upper_margin': {'required': True}, + 'lower_margin': {'required': True}, + 'is_anomaly': {'required': True}, + 'is_negative_anomaly': {'required': True}, + 'is_positive_anomaly': {'required': True}, + } + + _attribute_map = { + 'period': {'key': 'period', 'type': 'int'}, + 'suggested_window': {'key': 'suggestedWindow', 'type': 'int'}, + 'expected_value': {'key': 'expectedValue', 'type': 'float'}, + 'upper_margin': {'key': 'upperMargin', 'type': 'float'}, + 'lower_margin': {'key': 'lowerMargin', 'type': 'float'}, + 'is_anomaly': {'key': 'isAnomaly', 'type': 'bool'}, + 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': 'bool'}, + 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': 'bool'}, + } + + def __init__( + self, + **kwargs + ): + super(LastDetectResponse, self).__init__(**kwargs) + self.period = kwargs['period'] + self.suggested_window = kwargs['suggested_window'] + self.expected_value = kwargs['expected_value'] + self.upper_margin = kwargs['upper_margin'] + self.lower_margin = kwargs['lower_margin'] + self.is_anomaly = kwargs['is_anomaly'] + self.is_negative_anomaly = kwargs['is_negative_anomaly'] + self.is_positive_anomaly = kwargs['is_positive_anomaly'] + + +class Point(msrest.serialization.Model): + """Point. + + All required parameters must be populated in order to send to Azure. + + :param timestamp: Required. 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 + """ + + _validation = { + 'timestamp': {'required': True}, + 'value': {'required': True}, + } + + _attribute_map = { + 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, + 'value': {'key': 'value', 'type': 'float'}, + } + + def __init__( + self, + **kwargs + ): + super(Point, self).__init__(**kwargs) + self.timestamp = kwargs['timestamp'] + self.value = kwargs['value'] + + +class Request(msrest.serialization.Model): + """Request. + + 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 + 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.Point] + :param 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". + :type granularity: str or ~azure.ai.anomalydetector.models.Granularity + :param 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 + 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 + time series. + :type max_anomaly_ratio: float + :param 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 + """ + + _validation = { + 'series': {'required': True}, + 'granularity': {'required': True}, + } + + _attribute_map = { + 'series': {'key': 'series', 'type': '[Point]'}, + 'granularity': {'key': 'granularity', 'type': 'str'}, + 'custom_interval': {'key': 'customInterval', 'type': 'int'}, + 'period': {'key': 'period', 'type': 'int'}, + 'max_anomaly_ratio': {'key': 'maxAnomalyRatio', 'type': 'float'}, + 'sensitivity': {'key': 'sensitivity', 'type': 'int'}, + } + + def __init__( + self, + **kwargs + ): + super(Request, self).__init__(**kwargs) + self.series = kwargs['series'] + self.granularity = kwargs['granularity'] + self.custom_interval = kwargs.get('custom_interval', None) + self.period = kwargs.get('period', None) + self.max_anomaly_ratio = kwargs.get('max_anomaly_ratio', None) + self.sensitivity = kwargs.get('sensitivity', None) 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 new file mode 100644 index 000000000000..9ec3fcb94623 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/models/_models_py3.py @@ -0,0 +1,400 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- + +import datetime +from typing import List, Optional, Union + +from azure.core.exceptions import HttpResponseError +import msrest.serialization + +from ._anomaly_detector_client_enums import * + + +class APIError(msrest.serialization.Model): + """Error information returned by the API. + + :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 + """ + + _attribute_map = { + 'code': {'key': 'code', 'type': 'str'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__( + self, + *, + code: Optional[Union[str, "AnomalyDetectorErrorCodes"]] = None, + message: Optional[str] = None, + **kwargs + ): + super(APIError, self).__init__(**kwargs) + self.code = code + self.message = message + + +class ChangePointDetectRequest(msrest.serialization.Model): + """ChangePointDetectRequest. + + 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 + ascending order to match the change point detection result. + :type series: list[~azure.ai.anomalydetector.models.Point] + :param 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". + :type granularity: str or ~azure.ai.anomalydetector.models.Granularity + :param 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 + not present, the API will determine the period automatically. + :type period: int + :param 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 + value is, the larger the trend error will be which means less change point will be accepted. + :type threshold: float + """ + + _validation = { + 'series': {'required': True}, + 'granularity': {'required': True}, + } + + _attribute_map = { + 'series': {'key': 'series', 'type': '[Point]'}, + 'granularity': {'key': 'granularity', 'type': 'str'}, + 'custom_interval': {'key': 'customInterval', 'type': 'int'}, + 'period': {'key': 'period', 'type': 'int'}, + 'stable_trend_window': {'key': 'stableTrendWindow', 'type': 'int'}, + 'threshold': {'key': 'threshold', 'type': 'float'}, + } + + def __init__( + self, + *, + series: List["Point"], + granularity: Union[str, "Granularity"], + custom_interval: Optional[int] = None, + period: Optional[int] = None, + stable_trend_window: Optional[int] = None, + threshold: Optional[float] = None, + **kwargs + ): + super(ChangePointDetectRequest, self).__init__(**kwargs) + self.series = series + self.granularity = granularity + self.custom_interval = custom_interval + self.period = period + self.stable_trend_window = stable_trend_window + self.threshold = threshold + + +class ChangePointDetectResponse(msrest.serialization.Model): + """ChangePointDetectResponse. + + 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 + has been found. + :type period: int + :param is_change_point: Required. 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: Required. the change point confidence of each point. + :type confidence_scores: list[float] + """ + + _validation = { + 'period': {'required': True}, + 'is_change_point': {'required': True}, + 'confidence_scores': {'required': True}, + } + + _attribute_map = { + 'period': {'key': 'period', 'type': 'int'}, + 'is_change_point': {'key': 'isChangePoint', 'type': '[bool]'}, + 'confidence_scores': {'key': 'confidenceScores', 'type': '[float]'}, + } + + def __init__( + self, + *, + period: int, + is_change_point: List[bool], + confidence_scores: List[float], + **kwargs + ): + super(ChangePointDetectResponse, self).__init__(**kwargs) + self.period = period + self.is_change_point = is_change_point + self.confidence_scores = confidence_scores + + +class EntireDetectResponse(msrest.serialization.Model): + """EntireDetectResponse. + + 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 + has been found. + :type period: int + :param 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. + 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. + 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 + 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 + 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 + 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] + """ + + _validation = { + 'period': {'required': True}, + 'expected_values': {'required': True}, + 'upper_margins': {'required': True}, + 'lower_margins': {'required': True}, + 'is_anomaly': {'required': True}, + 'is_negative_anomaly': {'required': True}, + 'is_positive_anomaly': {'required': True}, + } + + _attribute_map = { + 'period': {'key': 'period', 'type': 'int'}, + 'expected_values': {'key': 'expectedValues', 'type': '[float]'}, + 'upper_margins': {'key': 'upperMargins', 'type': '[float]'}, + 'lower_margins': {'key': 'lowerMargins', 'type': '[float]'}, + 'is_anomaly': {'key': 'isAnomaly', 'type': '[bool]'}, + 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': '[bool]'}, + 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': '[bool]'}, + } + + def __init__( + self, + *, + period: int, + expected_values: List[float], + upper_margins: List[float], + lower_margins: List[float], + is_anomaly: List[bool], + is_negative_anomaly: List[bool], + is_positive_anomaly: List[bool], + **kwargs + ): + super(EntireDetectResponse, self).__init__(**kwargs) + self.period = period + self.expected_values = expected_values + self.upper_margins = upper_margins + self.lower_margins = lower_margins + self.is_anomaly = is_anomaly + self.is_negative_anomaly = is_negative_anomaly + self.is_positive_anomaly = is_positive_anomaly + + +class LastDetectResponse(msrest.serialization.Model): + """LastDetectResponse. + + 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 + 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 + 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 + 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 + 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. + 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. + True means the latest point is an anomaly and its real value is larger than the expected one. + :type is_positive_anomaly: bool + """ + + _validation = { + 'period': {'required': True}, + 'suggested_window': {'required': True}, + 'expected_value': {'required': True}, + 'upper_margin': {'required': True}, + 'lower_margin': {'required': True}, + 'is_anomaly': {'required': True}, + 'is_negative_anomaly': {'required': True}, + 'is_positive_anomaly': {'required': True}, + } + + _attribute_map = { + 'period': {'key': 'period', 'type': 'int'}, + 'suggested_window': {'key': 'suggestedWindow', 'type': 'int'}, + 'expected_value': {'key': 'expectedValue', 'type': 'float'}, + 'upper_margin': {'key': 'upperMargin', 'type': 'float'}, + 'lower_margin': {'key': 'lowerMargin', 'type': 'float'}, + 'is_anomaly': {'key': 'isAnomaly', 'type': 'bool'}, + 'is_negative_anomaly': {'key': 'isNegativeAnomaly', 'type': 'bool'}, + 'is_positive_anomaly': {'key': 'isPositiveAnomaly', 'type': 'bool'}, + } + + def __init__( + self, + *, + period: int, + suggested_window: int, + expected_value: float, + upper_margin: float, + lower_margin: float, + is_anomaly: bool, + is_negative_anomaly: bool, + is_positive_anomaly: bool, + **kwargs + ): + super(LastDetectResponse, self).__init__(**kwargs) + self.period = period + self.suggested_window = suggested_window + self.expected_value = expected_value + self.upper_margin = upper_margin + self.lower_margin = lower_margin + self.is_anomaly = is_anomaly + self.is_negative_anomaly = is_negative_anomaly + self.is_positive_anomaly = is_positive_anomaly + + +class Point(msrest.serialization.Model): + """Point. + + All required parameters must be populated in order to send to Azure. + + :param timestamp: Required. 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 + """ + + _validation = { + 'timestamp': {'required': True}, + 'value': {'required': True}, + } + + _attribute_map = { + 'timestamp': {'key': 'timestamp', 'type': 'iso-8601'}, + 'value': {'key': 'value', 'type': 'float'}, + } + + def __init__( + self, + *, + timestamp: datetime.datetime, + value: float, + **kwargs + ): + super(Point, self).__init__(**kwargs) + self.timestamp = timestamp + self.value = value + + +class Request(msrest.serialization.Model): + """Request. + + 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 + 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.Point] + :param 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". + :type granularity: str or ~azure.ai.anomalydetector.models.Granularity + :param 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 + 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 + time series. + :type max_anomaly_ratio: float + :param 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 + """ + + _validation = { + 'series': {'required': True}, + 'granularity': {'required': True}, + } + + _attribute_map = { + 'series': {'key': 'series', 'type': '[Point]'}, + 'granularity': {'key': 'granularity', 'type': 'str'}, + 'custom_interval': {'key': 'customInterval', 'type': 'int'}, + 'period': {'key': 'period', 'type': 'int'}, + 'max_anomaly_ratio': {'key': 'maxAnomalyRatio', 'type': 'float'}, + 'sensitivity': {'key': 'sensitivity', 'type': 'int'}, + } + + def __init__( + self, + *, + series: List["Point"], + granularity: Union[str, "Granularity"], + custom_interval: Optional[int] = None, + period: Optional[int] = None, + max_anomaly_ratio: Optional[float] = None, + sensitivity: Optional[int] = None, + **kwargs + ): + super(Request, self).__init__(**kwargs) + self.series = series + self.granularity = granularity + self.custom_interval = custom_interval + self.period = period + self.max_anomaly_ratio = max_anomaly_ratio + self.sensitivity = sensitivity diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/__init__.py b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/__init__.py new file mode 100644 index 000000000000..00fccdc398f9 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/__init__.py @@ -0,0 +1,13 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 ._anomaly_detector_client_operations import AnomalyDetectorClientOperationsMixin + +__all__ = [ + 'AnomalyDetectorClientOperationsMixin', +] 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 new file mode 100644 index 000000000000..c5e1bd5b483f --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/operations/_anomaly_detector_client_operations.py @@ -0,0 +1,205 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# 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 typing import TYPE_CHECKING +import warnings + +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest, HttpResponse + +from .. import models + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from typing import Any, Callable, Dict, Generic, Optional, TypeVar + + T = TypeVar('T') + ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +class AnomalyDetectorClientOperationsMixin(object): + + def entire_detect( + self, + body, # type: "models.Request" + **kwargs # type: Any + ): + # type: (...) -> "models.EntireDetectResponse" + """Detect anomalies for the entire series in batch. + + This operation generates a model using an entire series, each point is detected with the same + model. With this method, points before and after a certain point are used to determine whether + it is an anomaly. The entire detection can give user an overall status of the time 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.Request + :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 + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.EntireDetectResponse"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.entire_detect.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] + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(body, 'Request') + 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(models.APIError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('EntireDetectResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + entire_detect.metadata = {'url': '/timeseries/entire/detect'} # type: ignore + + def last_detect( + self, + body, # type: "models.Request" + **kwargs # type: Any + ): + # type: (...) -> "models.LastDetectResponse" + """Detect anomaly status of the latest point in time series. + + This operation generates a model using points before the latest one. With this method, only + historical points are used to determine whether the target point is an anomaly. The latest + point detecting operation matches the scenario of real-time monitoring of business metrics. + + :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.Request + :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 + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.LastDetectResponse"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.last_detect.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] + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + body_content_kwargs = {} # type: Dict[str, Any] + body_content = self._serialize.body(body, 'Request') + 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(models.APIError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('LastDetectResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + last_detect.metadata = {'url': '/timeseries/last/detect'} # type: ignore + + def change_point_detect( + self, + body, # type: "models.ChangePointDetectRequest" + **kwargs # type: Any + ): + # type: (...) -> "models.ChangePointDetectResponse" + """Detect change point for the entire series. + + Evaluate change point score of every series 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 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 + :raises: ~azure.core.exceptions.HttpResponseError + """ + cls = kwargs.pop('cls', None) # type: ClsType["models.ChangePointDetectResponse"] + error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop('error_map', {})) + content_type = kwargs.pop("content_type", "application/json") + + # Construct URL + url = self.change_point_detect.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] + + # Construct headers + header_parameters = {} # type: Dict[str, Any] + header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') + header_parameters['Accept'] = 'application/json' + + 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(models.APIError, response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize('ChangePointDetectResponse', pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) + + return deserialized + change_point_detect.metadata = {'url': '/timeseries/changePoint/detect'} # type: ignore diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/py.typed b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/azure/ai/anomalydetector/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/sdk_packaging.toml b/sdk/anomalydetector/azure-ai-anomalydetector/sdk_packaging.toml new file mode 100644 index 000000000000..76d3e53f4bed --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/sdk_packaging.toml @@ -0,0 +1,9 @@ +[packaging] +package_name = "azure-ai-anomalydetector" +package_nspkg = "azure-ai-nspkg" +package_pprint_name = "Cognitive Services Anomaly Detector" +package_doc_id = "cognitive-services" +is_stable = false +is_arm = false +need_msrestazure = false +auto_update = false diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/setup.cfg b/sdk/anomalydetector/azure-ai-anomalydetector/setup.cfg new file mode 100644 index 000000000000..3c6e79cf31da --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/setup.cfg @@ -0,0 +1,2 @@ +[bdist_wheel] +universal=1 diff --git a/sdk/anomalydetector/azure-ai-anomalydetector/setup.py b/sdk/anomalydetector/azure-ai-anomalydetector/setup.py new file mode 100644 index 000000000000..5a18ae349192 --- /dev/null +++ b/sdk/anomalydetector/azure-ai-anomalydetector/setup.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python + +#------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +#-------------------------------------------------------------------------- + +import re +import os.path +from io import open +from setuptools import find_packages, setup + +# Change the PACKAGE_NAME only to change folder and different name +PACKAGE_NAME = "azure-ai-anomalydetector" +PACKAGE_PPRINT_NAME = "Cognitive Services Anomaly Detector" + +# a-b-c => a/b/c +package_folder_path = PACKAGE_NAME.replace('-', '/') +# a-b-c => a.b.c +namespace_name = PACKAGE_NAME.replace('-', '.') + + +# Version extraction inspired from 'requests' +with open(os.path.join(package_folder_path, 'version.py') + if os.path.exists(os.path.join(package_folder_path, 'version.py')) + else os.path.join(package_folder_path, '_version.py'), 'r') as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', + fd.read(), re.MULTILINE).group(1) + +if not version: + raise RuntimeError('Cannot find version information') + +with open('README.md', encoding='utf-8') as f: + readme = f.read() +with open('CHANGELOG.md', encoding='utf-8') as f: + changelog = f.read() + +setup( + name=PACKAGE_NAME, + version=version, + description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME), + long_description=readme + '\n\n' + changelog, + long_description_content_type='text/markdown', + license='MIT License', + author='Microsoft Corporation', + author_email='azpysdkhelp@microsoft.com', + url='https://github.com/Azure/azure-sdk-for-python', + classifiers=[ + 'Development Status :: 4 - Beta', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'License :: OSI Approved :: MIT License', + ], + zip_safe=False, + packages=find_packages(exclude=[ + 'tests', + # Exclude packages that will be covered by PEP420 or nspkg + 'azure', + 'azure.ai', + ]), + install_requires=[ + 'msrest>=0.5.0', + 'azure-common~=1.1', + 'azure-core>=1.6.0,<2.0.0', + ], + extras_require={ + ":python_version<'3.0'": ['azure-ai-nspkg'], + } +) diff --git a/sdk/anomalydetector/ci.yml b/sdk/anomalydetector/ci.yml new file mode 100644 index 000000000000..3dd5fbfa2221 --- /dev/null +++ b/sdk/anomalydetector/ci.yml @@ -0,0 +1,35 @@ +# DO NOT EDIT THIS FILE +# This file is generated automatically and any changes will be lost. + +trigger: + branches: + include: + - master + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/anomalydetector/ + - sdk/core/ + +pr: + branches: + include: + - master + - feature/* + - hotfix/* + - release/* + - restapi* + paths: + include: + - sdk/anomalydetector/ + - sdk/core/ + +extends: + template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: anomalydetector + Artifacts: + - name: azure_ai_anomalydetector + safeName: azureaianomalydetector