diff --git a/sdk/anomalydetector/ai-anomaly-detector/package.json b/sdk/anomalydetector/ai-anomaly-detector/package.json index c48abde462fc..8f4896753121 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/package.json +++ b/sdk/anomalydetector/ai-anomaly-detector/package.json @@ -13,7 +13,7 @@ "audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit", "build:browser": "tsc -p . && cross-env ONLY_BROWSER=true rollup -c 2>&1", "build:node": "tsc -p . && cross-env ONLY_NODE=true rollup -c 2>&1", - "build:samples": "dev-tool samples prep && cd dist-samples && tsc -p .", + "build:samples": "echo Obsolete.", "build:test": "tsc -p . && rollup -c rollup.test.config.js 2>&1", "build": "tsc -p . && rollup -c 2>&1 && api-extractor run --local", "check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"", @@ -64,6 +64,7 @@ "dependencies": { "@azure/core-http": "^1.2.0", "@azure/core-auth": "^1.3.0", + "@azure/core-paging": "^1.1.1", "@azure/logger": "^1.0.0", "tslib": "^2.0.0", "@azure/core-tracing": "1.0.0-preview.11" @@ -114,7 +115,15 @@ "typedoc": "0.15.2" }, "//sampleConfiguration": { - "skipFolder": true + "productName": "Azure Anomaly Detector", + "productSlugs": [ + "azure", + "azure-cognitive-services", + "azure-anomaly-detector" + ], + "requiredResources": { + "Azure Anomaly Detector instance": "https://docs.microsoft.com/azure/cognitive-services/anomaly-detector/quickstarts/client-libraries?tabs=windows&pivots=programming-language-javascript" + } }, "//metadata": { "constantPaths": [ diff --git a/sdk/anomalydetector/ai-anomaly-detector/review/ai-anomaly-detector.api.md b/sdk/anomalydetector/ai-anomaly-detector/review/ai-anomaly-detector.api.md index c1724584cdbe..eba1763543b9 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/review/ai-anomaly-detector.api.md +++ b/sdk/anomalydetector/ai-anomaly-detector/review/ai-anomaly-detector.api.md @@ -6,7 +6,7 @@ import * as coreHttp from '@azure/core-http'; import { KeyCredential } from '@azure/core-auth'; -import { OperationOptions } from '@azure/core-http'; +import { PagedAsyncIterableIterator } from '@azure/core-paging'; import { PipelineOptions } from '@azure/core-http'; import { TokenCredential } from '@azure/core-auth'; @@ -26,36 +26,121 @@ export interface AnomalyContributor { variable?: string; } +// @public (undocumented) +export class AnomalyDetector extends AnomalyDetectorContext { + constructor(endpoint: string, options?: AnomalyDetectorOptionalParams); + deleteMultivariateModel(modelId: string, options?: coreHttp.OperationOptions): Promise; + detectAnomaly(modelId: string, detectionRequest: DetectionRequest, options?: coreHttp.OperationOptions): Promise; + detectChangePoint(body: DetectChangePointRequest, options?: coreHttp.OperationOptions): Promise; + detectEntireSeries(body: DetectRequest, options?: coreHttp.OperationOptions): Promise; + detectLastPoint(body: DetectRequest, options?: coreHttp.OperationOptions): Promise; + exportModel(modelId: string, options?: coreHttp.OperationOptions): Promise; + getDetectionResult(resultId: string, options?: coreHttp.OperationOptions): Promise; + getMultivariateModel(modelId: string, options?: coreHttp.OperationOptions): Promise; + listMultivariateModel(options?: AnomalyDetectorListMultivariateModelOptionalParams): PagedAsyncIterableIterator; + trainMultivariateModel(modelRequest: AnomalyDetectorClientModelInfo, options?: coreHttp.OperationOptions): Promise; +} + // @public -export class AnomalyDetectorClient { - constructor(endpointUrl: string, credential: TokenCredential | KeyCredential, options?: AnomalyDetectorClientOptions); - deleteMultivariateModel(modelId: string, options?: DeleteMultivariateModelOptions): Promise; - detectAnomaly(modelId: string, detectionRequest: DetectionRequest, options?: DetectAnomalyOptions): Promise; - detectChangePoint(body: DetectChangePointRequest, options?: DetectChangePointOptions): Promise; - detectEntireSeries(body: DetectRequest, options?: DetectEntireSeriesOptions): Promise; - detectLastPoint(body: DetectRequest, options?: DetectLastPointOptions): Promise; - exportModel(modelId: string, options?: ExportModelOptions): Promise; - getDetectionResult(resultId: string, options?: GetDetectionResultOptions): Promise; - getMultivariateModel(modelId: string, options?: GetMultivariateModelOptions): Promise; - listMultivariateModel(options?: ListMultivariateModelOptionalParams): Promise; - listMultivariateModelNext(nextLink: string, options?: ListMultivariateModelNextOptionalParams): Promise; - trainMultivariateModel(modelRequest: AnomalyDetectorClientModelInfo, options?: TrainMultivariateModelOptions): Promise; +export class AnomalyDetectorClient extends AnomalyDetector { + constructor(endpointUrl: string, credential: TokenCredential | KeyCredential, options?: PipelineOptions); +} + +// @public (undocumented) +export interface AnomalyDetectorClientErrorResponse { + code: string; + message: string; } // @public -export interface AnomalyDetectorClientDetectAnomalyHeaders { +export interface AnomalyDetectorClientModel { + createdTime: Date; + lastUpdatedTime: Date; + modelId: string; + modelInfo?: AnomalyDetectorClientModelInfo; +} + +// @public +export interface AnomalyDetectorClientModelInfo { + alignPolicy?: AlignPolicy; + readonly diagnosticsInfo?: DiagnosticsInfo; + displayName?: string; + endTime: Date; + readonly errors?: AnomalyDetectorClientErrorResponse[]; + slidingWindow?: number; + source: string; + startTime: Date; + readonly status?: AnomalyDetectorClientModelStatus; +} + +// @public +export interface AnomalyDetectorClientModelList { + currentCount: number; + maxCount: number; + models: AnomalyDetectorClientModelSnapshot[]; + nextLink?: string; +} + +// @public (undocumented) +export interface AnomalyDetectorClientModelSnapshot { + createdTime: Date; + // (undocumented) + displayName?: string; + lastUpdatedTime: Date; + modelId: string; + readonly status: AnomalyDetectorClientModelStatus; + variablesCount: number; +} + +// @public (undocumented) +export interface AnomalyDetectorClientModelState { + epochIds?: number[]; + // (undocumented) + latenciesInSeconds?: number[]; + // (undocumented) + trainLosses?: number[]; + // (undocumented) + validationLosses?: number[]; +} + +// @public +export type AnomalyDetectorClientModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; + +// @public +export interface AnomalyDetectorClientOptions extends PipelineOptions { +} + +// @public (undocumented) +export interface AnomalyDetectorClientVariableState { + effectiveCount?: number; + endTime?: Date; + errors?: AnomalyDetectorClientErrorResponse[]; + filledNARatio?: number; + startTime?: Date; + variable?: string; +} + +// @public (undocumented) +export class AnomalyDetectorContext extends coreHttp.ServiceClient { + constructor(endpoint: string, options?: AnomalyDetectorOptionalParams); + // (undocumented) + endpoint: string; +} + +// @public +export interface AnomalyDetectorDetectAnomalyHeaders { location?: string; } // @public -export type AnomalyDetectorClientDetectAnomalyResponse = AnomalyDetectorClientDetectAnomalyHeaders & { +export type AnomalyDetectorDetectAnomalyResponse = AnomalyDetectorDetectAnomalyHeaders & { _response: coreHttp.HttpResponse & { - parsedHeaders: AnomalyDetectorClientDetectAnomalyHeaders; + parsedHeaders: AnomalyDetectorDetectAnomalyHeaders; }; }; // @public -export type AnomalyDetectorClientDetectChangePointResponse = DetectChangePointResponse & { +export type AnomalyDetectorDetectChangePointResponse = DetectChangePointResponse & { _response: coreHttp.HttpResponse & { bodyAsText: string; parsedBody: DetectChangePointResponse; @@ -63,7 +148,7 @@ export type AnomalyDetectorClientDetectChangePointResponse = DetectChangePointRe }; // @public -export type AnomalyDetectorClientDetectEntireResponse = DetectEntireResponse & { +export type AnomalyDetectorDetectEntireSeriesResponse = DetectEntireResponse & { _response: coreHttp.HttpResponse & { bodyAsText: string; parsedBody: DetectEntireResponse; @@ -71,35 +156,29 @@ export type AnomalyDetectorClientDetectEntireResponse = DetectEntireResponse & { }; // @public -export type AnomalyDetectorClientDetectLastPointResponse = DetectLastPointResponse & { +export type AnomalyDetectorDetectLastPointResponse = DetectLastPointResponse & { _response: coreHttp.HttpResponse & { bodyAsText: string; parsedBody: DetectLastPointResponse; }; }; -// @public (undocumented) -export interface AnomalyDetectorClientErrorResponse { - code: string; - message: string; -} - // @public -export interface AnomalyDetectorClientExportModelHeaders { +export interface AnomalyDetectorExportModelHeaders { contentType?: string; } // @public -export type AnomalyDetectorClientExportModelResponse = AnomalyDetectorClientExportModelHeaders & { +export type AnomalyDetectorExportModelResponse = AnomalyDetectorExportModelHeaders & { blobBody?: Promise; readableStreamBody?: NodeJS.ReadableStream; _response: coreHttp.HttpResponse & { - parsedHeaders: AnomalyDetectorClientExportModelHeaders; + parsedHeaders: AnomalyDetectorExportModelHeaders; }; }; // @public -export type AnomalyDetectorClientGetDetectionResultResponse = DetectionResult & { +export type AnomalyDetectorGetDetectionResultResponse = DetectionResult & { _response: coreHttp.HttpResponse & { bodyAsText: string; parsedBody: DetectionResult; @@ -107,7 +186,7 @@ export type AnomalyDetectorClientGetDetectionResultResponse = DetectionResult & }; // @public -export type AnomalyDetectorClientGetMultivariateModelResponse = AnomalyDetectorClientModel & { +export type AnomalyDetectorGetMultivariateModelResponse = AnomalyDetectorClientModel & { _response: coreHttp.HttpResponse & { bodyAsText: string; parsedBody: AnomalyDetectorClientModel; @@ -115,15 +194,13 @@ export type AnomalyDetectorClientGetMultivariateModelResponse = AnomalyDetectorC }; // @public -export type AnomalyDetectorClientListMultivariateModelNextResponse = AnomalyDetectorClientModelList & { - _response: coreHttp.HttpResponse & { - bodyAsText: string; - parsedBody: AnomalyDetectorClientModelList; - }; -}; +export interface AnomalyDetectorListMultivariateModelNextOptionalParams extends coreHttp.OperationOptions { + skip?: number; + top?: number; +} // @public -export type AnomalyDetectorClientListMultivariateModelResponse = AnomalyDetectorClientModelList & { +export type AnomalyDetectorListMultivariateModelNextResponse = AnomalyDetectorClientModelList & { _response: coreHttp.HttpResponse & { bodyAsText: string; parsedBody: AnomalyDetectorClientModelList; @@ -131,85 +208,36 @@ export type AnomalyDetectorClientListMultivariateModelResponse = AnomalyDetector }; // @public -export interface AnomalyDetectorClientModel { - createdTime: Date; - lastUpdatedTime: Date; - modelId: string; - modelInfo?: AnomalyDetectorClientModelInfo; -} - -// @public -export interface AnomalyDetectorClientModelInfo { - alignPolicy?: AlignPolicy; - readonly diagnosticsInfo?: DiagnosticsInfo; - displayName?: string; - endTime: Date; - readonly errors?: AnomalyDetectorClientErrorResponse[]; - slidingWindow?: number; - source: string; - startTime: Date; - readonly status?: AnomalyDetectorClientModelStatus; -} - -// @public -export interface AnomalyDetectorClientModelList { - currentCount: number; - maxCount: number; - models: AnomalyDetectorClientModelSnapshot[]; - nextLink?: string; -} - -// @public (undocumented) -export interface AnomalyDetectorClientModelSnapshot { - createdTime: Date; - // (undocumented) - displayName?: string; - lastUpdatedTime: Date; - modelId: string; - readonly status: AnomalyDetectorClientModelStatus; - variablesCount: number; -} - -// @public (undocumented) -export interface AnomalyDetectorClientModelState { - epochIds?: number[]; - // (undocumented) - latenciesInSeconds?: number[]; - // (undocumented) - trainLosses?: number[]; - // (undocumented) - validationLosses?: number[]; +export interface AnomalyDetectorListMultivariateModelOptionalParams extends coreHttp.OperationOptions { + skip?: number; + top?: number; } // @public -export type AnomalyDetectorClientModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; +export type AnomalyDetectorListMultivariateModelResponse = AnomalyDetectorClientModelList & { + _response: coreHttp.HttpResponse & { + bodyAsText: string; + parsedBody: AnomalyDetectorClientModelList; + }; +}; // @public -export interface AnomalyDetectorClientOptions extends PipelineOptions { +export interface AnomalyDetectorOptionalParams extends coreHttp.ServiceClientOptions { + endpoint?: string; } // @public -export interface AnomalyDetectorClientTrainMultivariateModelHeaders { +export interface AnomalyDetectorTrainMultivariateModelHeaders { location?: string; } // @public -export type AnomalyDetectorClientTrainMultivariateModelResponse = AnomalyDetectorClientTrainMultivariateModelHeaders & { +export type AnomalyDetectorTrainMultivariateModelResponse = AnomalyDetectorTrainMultivariateModelHeaders & { _response: coreHttp.HttpResponse & { - parsedHeaders: AnomalyDetectorClientTrainMultivariateModelHeaders; + parsedHeaders: AnomalyDetectorTrainMultivariateModelHeaders; }; }; -// @public (undocumented) -export interface AnomalyDetectorClientVariableState { - effectiveCount?: number; - endTime?: Date; - errors?: AnomalyDetectorClientErrorResponse[]; - filledNARatio?: number; - startTime?: Date; - variable?: string; -} - // @public (undocumented) export interface AnomalyState { errors?: AnomalyDetectorClientErrorResponse[]; @@ -226,15 +254,6 @@ export interface AnomalyValue { severity: number; } -// @public (undocumented) -export type DeleteMultivariateModelOptions = OperationOptions; - -// @public (undocumented) -export type DetectAnomalyOptions = OperationOptions; - -// @public (undocumented) -export type DetectChangePointOptions = OperationOptions; - // @public (undocumented) export interface DetectChangePointRequest { customInterval?: number; @@ -263,9 +282,6 @@ export interface DetectEntireResponse { upperMargins: number[]; } -// @public (undocumented) -export type DetectEntireSeriesOptions = OperationOptions; - // @public export interface DetectionRequest { endTime: Date; @@ -293,9 +309,6 @@ export interface DetectionResultSummary { // @public export type DetectionStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; -// @public (undocumented) -export type DetectLastPointOptions = OperationOptions; - // @public (undocumented) export interface DetectLastPointResponse { expectedValue: number; @@ -311,7 +324,7 @@ export interface DetectLastPointResponse { // @public (undocumented) export interface DetectRequest { customInterval?: number; - granularity: TimeGranularity; + granularity?: TimeGranularity; maxAnomalyRatio?: number; period?: number; sensitivity?: number; @@ -326,32 +339,11 @@ export interface DiagnosticsInfo { variableStates?: AnomalyDetectorClientVariableState[]; } -// @public (undocumented) -export type ExportModelOptions = OperationOptions; - // @public export type FillNAMethod = "Previous" | "Subsequent" | "Linear" | "Zero" | "Pad" | "NotFill"; // @public (undocumented) -export type GetDetectionResultOptions = OperationOptions; - -// @public (undocumented) -export type GetMultivariateModelOptions = OperationOptions; - -// @public -export interface ListMultivariateModelNextOptionalParams extends coreHttp.OperationOptions { - skip?: number; - top?: number; -} - -// @public -export interface ListMultivariateModelOptionalParams extends coreHttp.OperationOptions { - skip?: number; - top?: number; -} - -// @public (undocumented) -export enum TimeGranularity { +export enum KnownTimeGranularity { daily = "daily", hourly = "hourly", monthly = "monthly", @@ -363,15 +355,15 @@ export enum TimeGranularity { yearly = "yearly" } +// @public +export type TimeGranularity = "yearly" | "monthly" | "weekly" | "daily" | "hourly" | "minutely" | "secondly" | "microsecond" | "none"; + // @public (undocumented) export interface TimeSeriesPoint { timestamp?: Date; value: number; } -// @public (undocumented) -export type TrainMultivariateModelOptions = OperationOptions; - // (No @packageDocumentation comment for this package) diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/example-data/request-data.csv b/sdk/anomalydetector/ai-anomaly-detector/samples-dev/example-data/request-data.csv similarity index 100% rename from sdk/anomalydetector/ai-anomaly-detector/samples/example-data/request-data.csv rename to sdk/anomalydetector/ai-anomaly-detector/samples-dev/example-data/request-data.csv diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_change_point.ts b/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_change_point.ts new file mode 100644 index 000000000000..6d49981f5d17 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_change_point.ts @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Demonstrates how to detect change points on entire series. + * + * @summary detects change points. + * @azsdk-weight 40 + */ + +import { + AnomalyDetectorClient, + DetectChangePointRequest, + DetectChangePointResponse, + TimeSeriesPoint, + KnownTimeGranularity +} from "@azure/ai-anomaly-detector"; +import { AzureKeyCredential } from "@azure/core-auth"; + +import * as fs from "fs"; +import parse from "csv-parse/lib/sync"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +// You will need to set this environment variables or edit the following values +const apiKey = process.env["API_KEY"] || ""; +const endpoint = process.env["ENDPOINT"] || ""; +const timeSeriesDataPath = "../example-data/request-data.csv"; + +function read_series_from_file(path: string): Array { + let result = Array(); + let input = fs.readFileSync(path).toString(); + let parsed = parse(input, { skip_empty_lines: true }); + parsed.forEach(function(e: Array) { + result.push({ timestamp: new Date(e[0]), value: Number(e[1]) }); + }); + return result; +} + +export async function main() { + // create client + const client = new AnomalyDetectorClient(endpoint, new AzureKeyCredential(apiKey)); + + // construct request + const request: DetectChangePointRequest = { + series: read_series_from_file(timeSeriesDataPath), + granularity: KnownTimeGranularity.daily + }; + + // get change point detect results + const result: DetectChangePointResponse = await client.detectChangePoint(request); + + if ( + result.isChangePoint!.some(function(changePoint) { + return changePoint === true; + }) + ) { + console.log("Change points were detected from the series at index:"); + result.isChangePoint!.forEach(function(changePoint, index) { + if (changePoint === true) console.log(index); + }); + } else { + console.log("There is no change point detected from the series."); + } + // output: + // Change points were detected from the series at index: + // 20 + // 27 +} + +main().catch((err) => { + console.error("The sample encountered an error:", err); +}); diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_entire_series_anomaly.ts b/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_entire_series_anomaly.ts new file mode 100644 index 000000000000..0144f594a51f --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_entire_series_anomaly.ts @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Demonstrates how to detect anomaly points on entire series. + * + * @summary detects anomaly points on entire series. + * @azsdk-weight 40 + */ + +import { + AnomalyDetectorClient, + DetectRequest, + DetectEntireResponse, + TimeSeriesPoint, + KnownTimeGranularity +} from "@azure/ai-anomaly-detector"; +import { AzureKeyCredential } from "@azure/core-auth"; + +import * as fs from "fs"; +import parse from "csv-parse/lib/sync"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +// You will need to set this environment variables or edit the following values +const apiKey = process.env["API_KEY"] || ""; +const endpoint = process.env["ENDPOINT"] || ""; +const timeSeriesDataPath = "../example-data/request-data.csv"; + +function read_series_from_file(path: string): Array { + let result = Array(); + let input = fs.readFileSync(path).toString(); + let parsed = parse(input, { skip_empty_lines: true }); + parsed.forEach(function(e: Array) { + result.push({ timestamp: new Date(e[0]), value: Number(e[1]) }); + }); + return result; +} + +export async function main() { + // create client + const client = new AnomalyDetectorClient(endpoint, new AzureKeyCredential(apiKey)); + + // construct request + const request: DetectRequest = { + series: read_series_from_file(timeSeriesDataPath), + granularity: KnownTimeGranularity.daily + }; + + // get entire detect result + const result: DetectEntireResponse = await client.detectEntireSeries(request); + + if ( + result.isAnomaly.some(function(anomaly) { + return anomaly === true; + }) + ) { + console.log("Anomalies were detected from the series at index:"); + result.isAnomaly.forEach(function(anomaly, index) { + if (anomaly === true) { + console.log(index); + } + }); + } else { + console.log("There is no anomaly detected from the series."); + } + // output: + // Anomalies were detected from the series at index: + // 3 + // 18 + // 21 + // 22 + // 23 + // 24 + // 25 + // 28 + // 29 + // 30 + // 31 + // 32 + // 35 + // 44 +} + +main().catch((err) => { + console.error("The sample encountered an error:", err); +}); diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_last_point_anomaly.ts b/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_last_point_anomaly.ts new file mode 100644 index 000000000000..612e97397c23 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples-dev/sample_detect_last_point_anomaly.ts @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Demonstrates how to detect anomaly for the last point on the series. + * + * @summary detects anomaly for the last point on the series. + * @azsdk-weight 40 + */ + +import { + AnomalyDetectorClient, + DetectRequest, + DetectLastPointResponse, + TimeSeriesPoint, + KnownTimeGranularity +} from "@azure/ai-anomaly-detector"; +import { AzureKeyCredential } from "@azure/core-auth"; + +import * as fs from "fs"; +import parse from "csv-parse/lib/sync"; + +// Load the .env file if it exists +import * as dotenv from "dotenv"; +dotenv.config(); + +// You will need to set this environment variables or edit the following values +const apiKey = process.env["API_KEY"] || ""; +const endpoint = process.env["ENDPOINT"] || ""; +const timeSeriesDataPath = "../example-data/request-data.csv"; + +function read_series_from_file(path: string): Array { + let result = Array(); + let input = fs.readFileSync(path).toString(); + let parsed = parse(input, { skip_empty_lines: true }); + parsed.forEach(function(e: Array) { + result.push({ timestamp: new Date(e[0]), value: Number(e[1]) }); + }); + return result; +} + +export async function main() { + // create client + const client = new AnomalyDetectorClient(endpoint, new AzureKeyCredential(apiKey)); + + // construct request + const request: DetectRequest = { + series: read_series_from_file(timeSeriesDataPath), + granularity: KnownTimeGranularity.daily + }; + + // get last detect result + const result: DetectLastPointResponse = await client.detectLastPoint(request); + + if (result.isAnomaly) { + console.log("The latest point is detected as anomaly."); + } else { + console.log("The latest point is not detected as anomaly."); + } + // output + // The latest point is not detected as anomaly. +} + +main().catch((err) => { + console.error("The sample encountered an error:", err); +}); diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/README.md b/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/README.md deleted file mode 100644 index 0adcf9d48700..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/README.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -page_type: sample -languages: - - javascript -products: - - azure - - azure-cognitive-services -urlFragment: ai-anomaly-detector-javascript ---- - -# Azure Anomaly Detector client library samples for JavaScript - -These sample programs show how to use the JavaScript client libraries for Azure Cognitive Services Anomaly Detector in some common scenarios. - -| **File Name** | **Description** | -| ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| [sample_detect_entire_series_anomaly.js][detectentireseriesanomaly] | Detect anomaly for each point of the series | -| [sample_detect_last_point_anomaly.js][detectlastpointanomaly] | Detect anomaly for the last point of the series | -| [sample_detect_change_point.js][detectchangepoint] | Detect change point for each point of the series | - -## Prerequisites - -The samples are compatible with Node.js >= 8.0.0. - -You need [an Azure subscription][freesub] and [an Azure Cognitive Services Instance][azcogsvc] to run these sample programs. Samples retrieve credentials to access the Cognitive Services endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Not all environment variables are required. Read the relevant sample sources and the `sample.env` file to determine which ones are required. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -3. Run whichever samples you like: - -```bash -node sample_detect_entire_series_anomaly.js -``` - -[detectentireseriesanomaly]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_entire_series_anomaly.js -[detectlastpointanomaly]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_last_point_anomaly.js -[detectchangepoint]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_change_point.js -[azcogsvc]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/README.md diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample.env b/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample.env deleted file mode 100644 index bec0f536a952..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample.env +++ /dev/null @@ -1,13 +0,0 @@ -# Used in most samples. Retrieve these values from a Cognitive Services instance -# in the Azure Portal. -ENDPOINT="" -API_KEY="" - -# Used to authenticate using Azure AD as a service principal for role-based authentication -# in the tokenAuth sample. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/tsconfig.json b/sdk/anomalydetector/ai-anomaly-detector/samples/tsconfig.json deleted file mode 100644 index 8de828320b71..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { - "module": "commonjs", - "outDir": "typescript/dist", - "lib": [ - "DOM", - "ES6" - ] - }, - "include": [ - "typescript/src/**.ts" - ], - "exclude": [ - "typescript/*.json", - "**/node_modules/", - "../node_modules", - "../typings" - ] -} diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/README.md b/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/README.md deleted file mode 100644 index 00b65865d6a3..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/README.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -page_type: sample -languages: - - typescript -products: - - azure - - azure-cognitive-services -urlFragment: ai-anomaly-detector-typescript ---- - -# Azure Anomaly Detector client library samples for TypeScript - -These sample programs show how to use the TypeScript client libraries for Azure Cognitive Services Anomaly Detector in some common scenarios. - -| **File Name** | **Description** | -| ------------------------------------------------------------------- | ------------------------------------------------ | -| [src/sample_detect_entire_series_anomaly.ts][detectentireseriesanomaly] | Detect anomaly for each point of the series | -| [src/sample_detect_last_point_anomaly.ts][detectlastpointanomaly] | Detect anomaly for the last point of the series | -| [src/sample_detect_change_point.ts][detectchangepoint] | Detect change point for each point of the series | - -## Prerequisites - -The samples are compatible with Node.js >= 8.0.0. - -Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using - -```bash -npm install -g typescript -``` - -You need [an Azure subscription][freesub] and [an Azure Cognitive Services Instance][azcogsvc] to run these sample programs. Samples retrieve credentials to access the Cognitive Services endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. - -Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. - -## Setup - -To run the samples using the published version of the package: - -1. Install the dependencies using `npm`: - -```bash -npm install -``` - -2. Compile the samples - -```bash -npm run build -``` - -3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Not all environment variables are required. Read the relevant sample sources and the `sample.env` file to determine which ones are required. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. - -4. Run whichever samples you like (note that some samples may require additional setup, see the table above): - -```bash -node dist/sample_detect_entire_series_anomaly.js -``` - -[detectentireseriesanomaly]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_entire_series_anomaly.ts -[detectlastpointanomaly]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_last_point_anomaly.ts -[detectchangepoint]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_change_point.ts -[azcogsvc]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account -[freesub]: https://azure.microsoft.com/free/ -[package]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/README.md -[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/sample.env b/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/sample.env deleted file mode 100644 index 472c7b5448be..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/sample.env +++ /dev/null @@ -1,13 +0,0 @@ -# Used in most samples. Retrieve these values from a Cognitive Services instance -# in the Azure Portal. -ENDPOINT="Your Endpoint URL" -API_KEY="" - -# Used to authenticate using Azure AD as a service principal for role-based authentication -# in the tokenAuth sample. -# -# See the documentation for `EnvironmentCredential` at the following link: -# https://docs.microsoft.com/javascript/api/@azure/identity/environmentcredential -AZURE_TENANT_ID= -AZURE_CLIENT_ID= -AZURE_CLIENT_SECRET= diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/tsconfig.json b/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/tsconfig.json deleted file mode 100644 index f2358c809731..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/tsconfig.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "compilerOptions": { - /* Basic Options */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - // "lib": [], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - // "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - // "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "incremental": true, /* Enable incremental compilation */ - // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - } -} diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/README.md b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/README.md new file mode 100644 index 000000000000..ac722fe7e214 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/README.md @@ -0,0 +1,68 @@ +--- +page_type: sample +languages: + - javascript +products: + - azure + - azure-cognitive-services + - azure-anomaly-detector +urlFragment: ai-anomaly-detector-javascript +--- + +# Azure Data Tables client library samples for JavaScript + +These sample programs show how to use the JavaScript client libraries for Azure Data Tables in some common scenarios. + +| **File Name** | **Description** | +| ----------------------------------------------------------------------------- | ------------------------------------------------- | +| [sample_detect_change_point.js][sample_detect_change_point] | detects change points. | +| [sample_detect_entire_series_anomaly.js][sample_detect_entire_series_anomaly] | detects anomaly points on entire series. | +| [sample_detect_last_point_anomaly.js][sample_detect_last_point_anomaly] | detects anomaly for the last point on the series. | + +## Prerequisites + +The sample programs are compatible with Node.js >=12.0.0. + +You need [an Azure subscription][freesub] and the following Azure resources to run these sample programs: + +- [Azure Anomaly Detector instance][createinstance_azureanomalydetectorinstance] + +Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +3. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node sample_detect_change_point.js +``` + +Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): + +```bash +npx cross-env API_KEY="" ENDPOINT="" node sample_detect_change_point.js +``` + +## Next Steps + +Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. + +[sample_detect_change_point]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_change_point.js +[sample_detect_entire_series_anomaly]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_entire_series_anomaly.js +[sample_detect_last_point_anomaly]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_last_point_anomaly.js +[apiref]: https://docs.microsoft.com/javascript/api/@azure/ai-anomaly-detector +[freesub]: https://azure.microsoft.com/free/ +[createinstance_azureanomalydetectorinstance]: https://docs.microsoft.com/azure/cognitive-services/anomaly-detector/quickstarts/client-libraries?tabs=windows&pivots=programming-language-javascript +[package]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/README.md diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/example-data/request-data.csv b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/example-data/request-data.csv new file mode 100644 index 000000000000..7f242c3712c1 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/example-data/request-data.csv @@ -0,0 +1,47 @@ +2018-03-01T00:00:00Z,32858923 +2018-03-02T00:00:00Z,29615278 +2018-03-03T00:00:00Z,22839355 +2018-03-04T00:00:00Z,25948736 +2018-03-05T00:00:00Z,34139159 +2018-03-06T00:00:00Z,33843985 +2018-03-07T00:00:00Z,33637661 +2018-03-08T00:00:00Z,32627350 +2018-03-09T00:00:00Z,29881076 +2018-03-10T00:00:00Z,22681575 +2018-03-11T00:00:00Z,24629393 +2018-03-12T00:00:00Z,34010679 +2018-03-13T00:00:00Z,33893888 +2018-03-14T00:00:00Z,33760076 +2018-03-15T00:00:00Z,33093515 +2018-03-16T00:00:00Z,29945555 +2018-03-17T00:00:00Z,22676212 +2018-03-18T00:00:00Z,25262514 +2018-03-19T00:00:00Z,33631649 +2018-03-20T00:00:00Z,34468310 +2018-03-21T00:00:00Z,34212281 +2018-03-22T00:00:00Z,38144434 +2018-03-23T00:00:00Z,34662949 +2018-03-24T00:00:00Z,24623684 +2018-03-25T00:00:00Z,26530491 +2018-03-26T00:00:00Z,35445003 +2018-03-27T00:00:00Z,34250789 +2018-03-28T00:00:00Z,33423012 +2018-03-29T00:00:00Z,30744783 +2018-03-30T00:00:00Z,25825128 +2018-03-31T00:00:00Z,21244209 +2018-04-01T00:00:00Z,22576956 +2018-04-02T00:00:00Z,31957221 +2018-04-03T00:00:00Z,33841228 +2018-04-04T00:00:00Z,33554483 +2018-04-05T00:00:00Z,32383350 +2018-04-06T00:00:00Z,29494850 +2018-04-07T00:00:00Z,22815534 +2018-04-08T00:00:00Z,25557267 +2018-04-09T00:00:00Z,34858252 +2018-04-10T00:00:00Z,34750597 +2018-04-11T00:00:00Z,34717956 +2018-04-12T00:00:00Z,34132534 +2018-04-13T00:00:00Z,30762236 +2018-04-14T00:00:00Z,22504059 +2018-04-15T00:00:00Z,26149060 +2018-04-16T00:00:00Z,35250105 \ No newline at end of file diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/package.json b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/package.json similarity index 58% rename from sdk/anomalydetector/ai-anomaly-detector/samples/javascript/package.json rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/package.json index 98362983258d..38e404046214 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/package.json +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/package.json @@ -1,20 +1,20 @@ { "name": "azure-ai-anomaly-detector-samples-js", "private": true, - "version": "0.1.0", - "description": "Azure ai-anomaly-detector client library samples for JavaScript", + "version": "1.0.0", + "description": "Azure Data Tables client library samples for JavaScript", "engine": { - "node": ">=8.0.0" + "node": ">=12.0.0" }, "repository": { "type": "git", "url": "git+https://github.com/Azure/azure-sdk-for-js.git", - "directory": "sdk/anomalydetector/ai-anomaly-detector/" + "directory": "sdk/anomalydetector/ai-anomaly-detector" }, "keywords": [ - "Azure", - "Node.js", - "JavaScript" + "azure", + "cloud", + "typescript" ], "author": "Microsoft Corporation", "license": "MIT", @@ -22,10 +22,10 @@ "url": "https://github.com/Azure/azure-sdk-for-js/issues" }, "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector", - "sideEffects": false, "dependencies": { - "@azure/ai-anomaly-detector": "latest", - "csv-parse": "^4.4.0", - "dotenv": "^8.2.0" + "@azure/ai-anomaly-detector": "next", + "dotenv": "latest", + "@azure/core-auth": "^1.3.0", + "csv-parse": "^4.4.0" } } diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample.env b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample.env new file mode 100644 index 000000000000..643a802c1060 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample.env @@ -0,0 +1,8 @@ +# Used in most samples. Retrieve these values from a Cognitive Services instance +# in the Azure Portal. +ANOMALY_DETECTOR_ENDPOINT="https://.cognitiveservices.azure.com/" +ANOMALY_DETECTOR_API_KEY="' + +# Our tests assume that TEST_MODE is "playback" by default. You can +# change it to "record" to generate new recordings, or "live" to bypass the recorder entirely. +# TEST_MODE=playback diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_change_point.js b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_change_point.js similarity index 81% rename from sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_change_point.js rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_change_point.js index f3621abcaad8..eec22e0d5585 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_change_point.js +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_change_point.js @@ -3,10 +3,13 @@ /** * Demonstrates how to detect change points on entire series. + * + * @summary detects change points. */ -const { AnomalyDetectorClient } = require("@azure/ai-anomaly-detector"); +const { AnomalyDetectorClient, KnownTimeGranularity } = require("@azure/ai-anomaly-detector"); const { AzureKeyCredential } = require("@azure/core-auth"); + const fs = require("fs"); const parse = require("csv-parse/lib/sync"); @@ -14,10 +17,10 @@ const parse = require("csv-parse/lib/sync"); const dotenv = require("dotenv"); dotenv.config(); -// You will need to set this environment variables in .env file or edit the following values +// You will need to set this environment variables or edit the following values const apiKey = process.env["API_KEY"] || ""; const endpoint = process.env["ENDPOINT"] || ""; -const timeSeriesDataPath = "../example-data/request-data.csv"; +const timeSeriesDataPath = "./example-data/request-data.csv"; function read_series_from_file(path) { let result = Array(); @@ -36,7 +39,7 @@ async function main() { // construct request const request = { series: read_series_from_file(timeSeriesDataPath), - granularity: "daily" + granularity: KnownTimeGranularity.daily }; // get change point detect results @@ -49,9 +52,7 @@ async function main() { ) { console.log("Change points were detected from the series at index:"); result.isChangePoint.forEach(function(changePoint, index) { - if (changePoint === true) { - console.log(index); - } + if (changePoint === true) console.log(index); }); } else { console.log("There is no change point detected from the series."); diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_entire_series_anomaly.js b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_entire_series_anomaly.js similarity index 83% rename from sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_entire_series_anomaly.js rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_entire_series_anomaly.js index bfe10c365ec8..35f9af8860cd 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_entire_series_anomaly.js +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_entire_series_anomaly.js @@ -3,10 +3,13 @@ /** * Demonstrates how to detect anomaly points on entire series. + * + * @summary detects anomaly points on entire series. */ -const { AnomalyDetectorClient } = require("@azure/ai-anomaly-detector"); +const { AnomalyDetectorClient, KnownTimeGranularity } = require("@azure/ai-anomaly-detector"); const { AzureKeyCredential } = require("@azure/core-auth"); + const fs = require("fs"); const parse = require("csv-parse/lib/sync"); @@ -14,10 +17,10 @@ const parse = require("csv-parse/lib/sync"); const dotenv = require("dotenv"); dotenv.config(); -// You will need to set this environment variables in .env file or edit the following values +// You will need to set this environment variables or edit the following values const apiKey = process.env["API_KEY"] || ""; const endpoint = process.env["ENDPOINT"] || ""; -const timeSeriesDataPath = "../example-data/request-data.csv"; +const timeSeriesDataPath = "./example-data/request-data.csv"; function read_series_from_file(path) { let result = Array(); @@ -36,7 +39,7 @@ async function main() { // construct request const request = { series: read_series_from_file(timeSeriesDataPath), - granularity: "daily" + granularity: KnownTimeGranularity.daily }; // get entire detect result diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_last_point_anomaly.js b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_last_point_anomaly.js similarity index 76% rename from sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_last_point_anomaly.js rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_last_point_anomaly.js index ec3467505e9c..ef8d0259e133 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/javascript/sample_detect_last_point_anomaly.js +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/javascript/sample_detect_last_point_anomaly.js @@ -3,10 +3,13 @@ /** * Demonstrates how to detect anomaly for the last point on the series. + * + * @summary detects anomaly for the last point on the series. */ -const { AnomalyDetectorClient } = require("@azure/ai-anomaly-detector"); +const { AnomalyDetectorClient, KnownTimeGranularity } = require("@azure/ai-anomaly-detector"); const { AzureKeyCredential } = require("@azure/core-auth"); + const fs = require("fs"); const parse = require("csv-parse/lib/sync"); @@ -14,10 +17,10 @@ const parse = require("csv-parse/lib/sync"); const dotenv = require("dotenv"); dotenv.config(); -// You will need to set this environment variables in .env file or edit the following values +// You will need to set this environment variables or edit the following values const apiKey = process.env["API_KEY"] || ""; const endpoint = process.env["ENDPOINT"] || ""; -const timeSeriesDataPath = "../example-data/request-data.csv"; +const timeSeriesDataPath = "./example-data/request-data.csv"; function read_series_from_file(path) { let result = Array(); @@ -36,18 +39,18 @@ async function main() { // construct request const request = { series: read_series_from_file(timeSeriesDataPath), - granularity: "daily" + granularity: KnownTimeGranularity.daily }; // get last detect result - const result = client.detectLastPoint(request); + const result = await client.detectLastPoint(request); if (result.isAnomaly) { console.log("The latest point is detected as anomaly."); } else { console.log("The latest point is not detected as anomaly."); } - // output: + // output // The latest point is not detected as anomaly. } diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/README.md b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/README.md new file mode 100644 index 000000000000..3dfec82e4b13 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/README.md @@ -0,0 +1,81 @@ +--- +page_type: sample +languages: + - typescript +products: + - azure + - azure-cognitive-services + - azure-anomaly-detector +urlFragment: ai-anomaly-detector-typescript +--- + +# Azure Data Tables client library samples for TypeScript + +These sample programs show how to use the TypeScript client libraries for Azure Data Tables in some common scenarios. + +| **File Name** | **Description** | +| ----------------------------------------------------------------------------- | ------------------------------------------------- | +| [sample_detect_change_point.ts][sample_detect_change_point] | detects change points. | +| [sample_detect_entire_series_anomaly.ts][sample_detect_entire_series_anomaly] | detects anomaly points on entire series. | +| [sample_detect_last_point_anomaly.ts][sample_detect_last_point_anomaly] | detects anomaly for the last point on the series. | + +## Prerequisites + +The sample programs are compatible with Node.js >=12.0.0. + +Before running the samples in Node, they must be compiled to JavaScript using the TypeScript compiler. For more information on TypeScript, see the [TypeScript documentation][typescript]. Install the TypeScript compiler using: + +```bash +npm install -g typescript +``` + +You need [an Azure subscription][freesub] and the following Azure resources to run these sample programs: + +- [Azure Anomaly Detector instance][createinstance_azureanomalydetectorinstance] + +Samples retrieve credentials to access the service endpoint from environment variables. Alternatively, edit the source code to include the appropriate credentials. See each individual sample for details on which environment variables/credentials it requires to function. + +Adapting the samples to run in the browser may require some additional consideration. For details, please see the [package README][package]. + +## Setup + +To run the samples using the published version of the package: + +1. Install the dependencies using `npm`: + +```bash +npm install +``` + +2. Compile the samples: + +```bash +npm run build +``` + +3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically. + +4. Run whichever samples you like (note that some samples may require additional setup, see the table above): + +```bash +node dist/sample_detect_change_point.ts +``` + +Alternatively, run a single sample with the correct environment variables set (setting up the `.env` file is not required if you do this), for example (cross-platform): + +```bash +npx cross-env API_KEY="" ENDPOINT="" node dist/sample_detect_change_point.js +``` + +## Next Steps + +Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients. + +[sample_detect_change_point]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_change_point.ts +[sample_detect_entire_series_anomaly]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_entire_series_anomaly.ts +[sample_detect_last_point_anomaly]: https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_last_point_anomaly.ts +[apiref]: https://docs.microsoft.com/javascript/api/@azure/ai-anomaly-detector +[freesub]: https://azure.microsoft.com/free/ +[createinstance_azureanomalydetectorinstance]: https://docs.microsoft.com/azure/cognitive-services/anomaly-detector/quickstarts/client-libraries?tabs=windows&pivots=programming-language-javascript +[package]: https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector/README.md +[typescript]: https://www.typescriptlang.org/docs/home.html diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/example-data/request-data.csv b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/example-data/request-data.csv new file mode 100644 index 000000000000..7f242c3712c1 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/example-data/request-data.csv @@ -0,0 +1,47 @@ +2018-03-01T00:00:00Z,32858923 +2018-03-02T00:00:00Z,29615278 +2018-03-03T00:00:00Z,22839355 +2018-03-04T00:00:00Z,25948736 +2018-03-05T00:00:00Z,34139159 +2018-03-06T00:00:00Z,33843985 +2018-03-07T00:00:00Z,33637661 +2018-03-08T00:00:00Z,32627350 +2018-03-09T00:00:00Z,29881076 +2018-03-10T00:00:00Z,22681575 +2018-03-11T00:00:00Z,24629393 +2018-03-12T00:00:00Z,34010679 +2018-03-13T00:00:00Z,33893888 +2018-03-14T00:00:00Z,33760076 +2018-03-15T00:00:00Z,33093515 +2018-03-16T00:00:00Z,29945555 +2018-03-17T00:00:00Z,22676212 +2018-03-18T00:00:00Z,25262514 +2018-03-19T00:00:00Z,33631649 +2018-03-20T00:00:00Z,34468310 +2018-03-21T00:00:00Z,34212281 +2018-03-22T00:00:00Z,38144434 +2018-03-23T00:00:00Z,34662949 +2018-03-24T00:00:00Z,24623684 +2018-03-25T00:00:00Z,26530491 +2018-03-26T00:00:00Z,35445003 +2018-03-27T00:00:00Z,34250789 +2018-03-28T00:00:00Z,33423012 +2018-03-29T00:00:00Z,30744783 +2018-03-30T00:00:00Z,25825128 +2018-03-31T00:00:00Z,21244209 +2018-04-01T00:00:00Z,22576956 +2018-04-02T00:00:00Z,31957221 +2018-04-03T00:00:00Z,33841228 +2018-04-04T00:00:00Z,33554483 +2018-04-05T00:00:00Z,32383350 +2018-04-06T00:00:00Z,29494850 +2018-04-07T00:00:00Z,22815534 +2018-04-08T00:00:00Z,25557267 +2018-04-09T00:00:00Z,34858252 +2018-04-10T00:00:00Z,34750597 +2018-04-11T00:00:00Z,34717956 +2018-04-12T00:00:00Z,34132534 +2018-04-13T00:00:00Z,30762236 +2018-04-14T00:00:00Z,22504059 +2018-04-15T00:00:00Z,26149060 +2018-04-16T00:00:00Z,35250105 \ No newline at end of file diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/package.json b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/package.json similarity index 63% rename from sdk/anomalydetector/ai-anomaly-detector/samples/typescript/package.json rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/package.json index 5eeb02eba3f0..fc7e1dfeabb8 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/package.json +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/package.json @@ -1,10 +1,10 @@ { "name": "azure-ai-anomaly-detector-samples-ts", "private": true, - "version": "0.1.0", - "description": "Azure ai-anomaly-detector client library samples for TypeScript", + "version": "1.0.0", + "description": "Azure Data Tables client library samples for TypeScript", "engine": { - "node": ">=8.0.0" + "node": ">=12.0.0" }, "scripts": { "build": "tsc", @@ -16,9 +16,9 @@ "directory": "sdk/anomalydetector/ai-anomaly-detector" }, "keywords": [ - "Azure", - "Node.js", - "TypeScript" + "azure", + "cloud", + "typescript" ], "author": "Microsoft Corporation", "license": "MIT", @@ -26,15 +26,14 @@ "url": "https://github.com/Azure/azure-sdk-for-js/issues" }, "homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector", - "sideEffects": false, "dependencies": { - "@azure/ai-anomaly-detector": "latest", - "csv-parse": "^4.4.0", - "dotenv": "^8.2.0" + "@azure/ai-anomaly-detector": "next", + "dotenv": "latest", + "@azure/core-auth": "^1.3.0", + "csv-parse": "^4.4.0" }, "devDependencies": { - "@types/node": "^8.0.0", - "rimraf": "^3.0.0", - "typescript": "~3.6.4" + "typescript": "~4.2.0", + "rimraf": "latest" } } diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/sample.env b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/sample.env new file mode 100644 index 000000000000..643a802c1060 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/sample.env @@ -0,0 +1,8 @@ +# Used in most samples. Retrieve these values from a Cognitive Services instance +# in the Azure Portal. +ANOMALY_DETECTOR_ENDPOINT="https://.cognitiveservices.azure.com/" +ANOMALY_DETECTOR_API_KEY="' + +# Our tests assume that TEST_MODE is "playback" by default. You can +# change it to "record" to generate new recordings, or "live" to bypass the recorder entirely. +# TEST_MODE=playback diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_change_point.ts b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_change_point.ts similarity index 95% rename from sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_change_point.ts rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_change_point.ts index 0a147ea67a08..e44f7772f254 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_change_point.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_change_point.ts @@ -3,6 +3,8 @@ /** * Demonstrates how to detect change points on entire series. + * + * @summary detects change points. */ import { @@ -10,7 +12,7 @@ import { DetectChangePointRequest, DetectChangePointResponse, TimeSeriesPoint, - TimeGranularity + KnownTimeGranularity } from "@azure/ai-anomaly-detector"; import { AzureKeyCredential } from "@azure/core-auth"; @@ -43,7 +45,7 @@ export async function main() { // construct request const request: DetectChangePointRequest = { series: read_series_from_file(timeSeriesDataPath), - granularity: TimeGranularity.daily + granularity: KnownTimeGranularity.daily }; // get change point detect results diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_entire_series_anomaly.ts b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_entire_series_anomaly.ts similarity index 94% rename from sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_entire_series_anomaly.ts rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_entire_series_anomaly.ts index e64a214b55a1..a1d6f240749a 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_entire_series_anomaly.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_entire_series_anomaly.ts @@ -3,6 +3,8 @@ /** * Demonstrates how to detect anomaly points on entire series. + * + * @summary detects anomaly points on entire series. */ import { @@ -10,7 +12,7 @@ import { DetectRequest, DetectEntireResponse, TimeSeriesPoint, - TimeGranularity + KnownTimeGranularity } from "@azure/ai-anomaly-detector"; import { AzureKeyCredential } from "@azure/core-auth"; @@ -43,7 +45,7 @@ export async function main() { // construct request const request: DetectRequest = { series: read_series_from_file(timeSeriesDataPath), - granularity: TimeGranularity.daily + granularity: KnownTimeGranularity.daily }; // get entire detect result diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_last_point_anomaly.ts b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_last_point_anomaly.ts similarity index 93% rename from sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_last_point_anomaly.ts rename to sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_last_point_anomaly.ts index 9dfe394860f6..8104490783ce 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/samples/typescript/src/sample_detect_last_point_anomaly.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/src/sample_detect_last_point_anomaly.ts @@ -3,6 +3,8 @@ /** * Demonstrates how to detect anomaly for the last point on the series. + * + * @summary detects anomaly for the last point on the series. */ import { @@ -10,7 +12,7 @@ import { DetectRequest, DetectLastPointResponse, TimeSeriesPoint, - TimeGranularity + KnownTimeGranularity } from "@azure/ai-anomaly-detector"; import { AzureKeyCredential } from "@azure/core-auth"; @@ -43,7 +45,7 @@ export async function main() { // construct request const request: DetectRequest = { series: read_series_from_file(timeSeriesDataPath), - granularity: TimeGranularity.daily + granularity: KnownTimeGranularity.daily }; // get last detect result diff --git a/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/tsconfig.json b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/tsconfig.json new file mode 100644 index 000000000000..416c2dd82e00 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/samples/v3/typescript/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2018", + "module": "commonjs", + "moduleResolution": "node", + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "alwaysStrict": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": [ + "src/**.ts" + ] +} diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/AnomalyDetectorClient.ts b/sdk/anomalydetector/ai-anomaly-detector/src/AnomalyDetectorClient.ts index b5d275098fe5..b747918e4c45 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/AnomalyDetectorClient.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/AnomalyDetectorClient.ts @@ -1,26 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. -import { - AnomalyDetectorClientOptions, - AnomalyDetectorClientDetectEntireResponse, - AnomalyDetectorClientDetectChangePointResponse, - AnomalyDetectorClientDetectLastPointResponse, - DetectChangePointRequest, - DetectRequest, - AnomalyDetectorClientModelInfo, - AnomalyDetectorClientTrainMultivariateModelResponse, - AnomalyDetectorClientGetMultivariateModelResponse, - AnomalyDetectorClientDetectAnomalyResponse, - DetectionRequest, - AnomalyDetectorClientGetDetectionResultResponse, - AnomalyDetectorClientExportModelResponse, - ListMultivariateModelOptionalParams, - AnomalyDetectorClientListMultivariateModelResponse, - ListMultivariateModelNextOptionalParams, - AnomalyDetectorClientListMultivariateModelNextResponse -} from "./models"; -import { GeneratedClient } from "./generated"; +import { AnomalyDetector } from "./generated"; import { KeyCredential, TokenCredential } from "@azure/core-auth"; import { SDK_VERSION, @@ -33,39 +14,15 @@ import { bearerTokenAuthenticationPolicy, InternalPipelineOptions, createPipelineFromOptions, - OperationOptions + PipelineOptions } from "@azure/core-http"; import { createAnomalyDetectorAzureKeyCredentialPolicy } from "./azureKeyCredentialPolicy"; import { logger } from "./logger"; -import { createSpan } from "./tracing"; -import { SpanStatusCode } from "@azure/core-tracing"; - -export type DetectEntireSeriesOptions = OperationOptions; -export type DetectLastPointOptions = OperationOptions; -export type DetectChangePointOptions = OperationOptions; -export type TrainMultivariateModelOptions = OperationOptions; -export type GetMultivariateModelOptions = OperationOptions; -export type DeleteMultivariateModelOptions = OperationOptions; -export type DetectAnomalyOptions = OperationOptions; -export type GetDetectionResultOptions = OperationOptions; -export type ExportModelOptions = OperationOptions; /** * Client class for interacting with Azure Anomaly Detector service. */ -export class AnomalyDetectorClient { - /** - * Url to an Azure Anomaly Detector service endpoint - */ - private readonly endpointUrl: string; - - /** - * @internal - * @hidden - * A reference to the auto-generated AnomalyDetector HTTP client. - */ - private client: GeneratedClient; - +export class AnomalyDetectorClient extends AnomalyDetector { /** * Creates an instance of AnomalyDetectorClient. * @@ -85,9 +42,9 @@ export class AnomalyDetectorClient { constructor( endpointUrl: string, credential: TokenCredential | KeyCredential, - options?: AnomalyDetectorClientOptions + /* eslint-disable-next-line @azure/azure-sdk/ts-naming-options */ + options?: PipelineOptions ) { - this.endpointUrl = endpointUrl; const { ...pipelineOptions } = options; const libInfo = `azsdk-js-ai-anomalydetector/${SDK_VERSION}`; @@ -117,330 +74,6 @@ export class AnomalyDetectorClient { const pipeline = createPipelineFromOptions(internalPipelineOptions, authPolicy); - this.client = new GeneratedClient(this.endpointUrl, pipeline); - } - - /** - * This operation generates a model with 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. - * @param options - The options parameters. - */ - public detectEntireSeries( - body: DetectRequest, - options?: DetectEntireSeriesOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-entireDetect", - realOptions - ); - - try { - return this.client.detectEntireSeries(body, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * 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. - * @param options - The options parameters. - */ - public detectLastPoint( - body: DetectRequest, - options?: DetectLastPointOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-lastDetect", - realOptions - ); - - try { - return this.client.detectLastPoint(body, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * 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. - * @param options - The options parameters. - */ - detectChangePoint( - body: DetectChangePointRequest, - options?: DetectChangePointOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-changePointDetect", - realOptions - ); - - try { - return this.client.detectChangePoint(body, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * Create and train a multivariate anomaly detection model. The request must include a source parameter - * to indicate an externally accessible Azure storage Uri (preferably a Shared Access Signature Uri). - * All time-series used in generate the model must be zipped into one single file. Each time-series - * will be in a single CSV file in which the first column is timestamp and the second column is value. - * @param modelRequest - Training request - * @param options - The options parameters. - */ - public trainMultivariateModel( - modelRequest: AnomalyDetectorClientModelInfo, - options?: TrainMultivariateModelOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-trainMultivariateModel", - realOptions - ); - - try { - return this.client.trainMultivariateModel(modelRequest, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * Get detailed information of multivariate model, including the training status and variables used in - * the model. - * @param modelId - Model identifier. - * @param options - The options parameters. - */ - public getMultivariateModel( - modelId: string, - options?: GetMultivariateModelOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-getMultivariateModel", - realOptions - ); - - try { - return this.client.getMultivariateModel(modelId, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * Delete an existing multivariate model according to the modelId - * @param modelId - Model identifier. - * @param options - The options parameters. - */ - public async deleteMultivariateModel( - modelId: string, - options?: DeleteMultivariateModelOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-deleteMultivariateModel", - realOptions - ); - - try { - await this.client.deleteMultivariateModel(modelId, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * Submit detection multivariate anomaly task with the trained model of modelId, the input schema - * should be the same with the training request. Thus request will be complete asynchronously and will - * return a resultId for querying the detection result.The request should be a source link to indicate - * an externally accessible Azure storage Uri (preferably a Shared Access Signature Uri). All - * time-series used in generate the model must be zipped into one single file. Each time-series will be - * as follows: the first column is timestamp and the second column is value. - * @param modelId - Model identifier. - * @param detectionRequest - Detect anomaly request - * @param options - The options parameters. - */ - public detectAnomaly( - modelId: string, - detectionRequest: DetectionRequest, - options?: DetectAnomalyOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-detectAnomaly", - realOptions - ); - - try { - return this.client.detectAnomaly(modelId, detectionRequest, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * Get multivariate anomaly detection result based on resultId returned by the DetectAnomalyAsync api - * @param resultId - Result identifier. - * @param options - The options parameters. - */ - public getDetectionResult( - resultId: string, - options?: GetDetectionResultOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-getDetectionResult", - realOptions - ); - - try { - return this.client.getDetectionResult(resultId, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * Export multivariate anomaly detection model based on modelId - * @param modelId - Model identifier. - * @param options - The options parameters. - */ - public exportModel( - modelId: string, - options?: ExportModelOptions - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-getDetectionResult", - realOptions - ); - - try { - return this.client.exportModel(modelId, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * List models of a subscription - * @param options - The options parameters. - */ - listMultivariateModel( - options?: ListMultivariateModelOptionalParams - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-getDetectionResult", - realOptions - ); - - try { - return this.client.listMultivariateModel(finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } - } - - /** - * List next Multivariate Model - * @param nextLink - The nextLink from the previous successful call to the ListMultivariateModel method. - * @param options - The options parameters. - */ - listMultivariateModelNext( - nextLink: string, - options?: ListMultivariateModelNextOptionalParams - ): Promise { - const realOptions = options || {}; - const { span, updatedOptions: finalOptions } = createSpan( - "anomalyDetectorClient-listMultivariateModelNext", - realOptions - ); - - try { - return this.client.listMultivariateModelNext(nextLink, finalOptions); - } catch (error) { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: error.message - }); - throw error; - } finally { - span.end(); - } + super(endpointUrl, pipeline); } } diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/anomalyDetector.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/anomalyDetector.ts new file mode 100644 index 000000000000..add6168c398f --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/src/generated/anomalyDetector.ts @@ -0,0 +1,647 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import * as coreHttp from "@azure/core-http"; +import "@azure/core-paging"; +import { PagedAsyncIterableIterator } from "@azure/core-paging"; +import { SpanStatusCode } from "@azure/core-tracing"; +import { createSpan } from "./tracing"; +import * as Parameters from "./models/parameters"; +import * as Mappers from "./models/mappers"; +import { AnomalyDetectorContext } from "./anomalyDetectorContext"; +import { + AnomalyDetectorOptionalParams, + ModelSnapshot, + AnomalyDetectorListMultivariateModelNextOptionalParams, + AnomalyDetectorListMultivariateModelOptionalParams, + DetectRequest, + AnomalyDetectorDetectEntireSeriesResponse, + AnomalyDetectorDetectLastPointResponse, + DetectChangePointRequest, + AnomalyDetectorDetectChangePointResponse, + ModelInfo, + AnomalyDetectorTrainMultivariateModelResponse, + AnomalyDetectorGetMultivariateModelResponse, + DetectionRequest, + AnomalyDetectorDetectAnomalyResponse, + AnomalyDetectorGetDetectionResultResponse, + AnomalyDetectorExportModelResponse, + AnomalyDetectorListMultivariateModelResponse, + AnomalyDetectorListMultivariateModelNextResponse +} from "./models"; + +/// +/** @hidden */ +export class AnomalyDetector extends AnomalyDetectorContext { + /** + * Initializes a new instance of the AnomalyDetector class. + * @param endpoint Supported Cognitive Services endpoints (protocol and hostname, for example: + * https://westus2.api.cognitive.microsoft.com). + * @param options The parameter options + */ + constructor(endpoint: string, options?: AnomalyDetectorOptionalParams) { + super(endpoint, options); + } + + /** + * List models of a subscription + * @param options The options parameters. + */ + public listMultivariateModel( + options?: AnomalyDetectorListMultivariateModelOptionalParams + ): PagedAsyncIterableIterator { + const iter = this.listMultivariateModelPagingAll(options); + return { + next() { + return iter.next(); + }, + [Symbol.asyncIterator]() { + return this; + }, + byPage: () => { + return this.listMultivariateModelPagingPage(options); + } + }; + } + + private async *listMultivariateModelPagingPage( + options?: AnomalyDetectorListMultivariateModelOptionalParams + ): AsyncIterableIterator { + let result = await this._listMultivariateModel(options); + yield result.models || []; + let continuationToken = result.nextLink; + while (continuationToken) { + result = await this._listMultivariateModelNext(continuationToken, options); + continuationToken = result.nextLink; + yield result.models || []; + } + } + + private async *listMultivariateModelPagingAll( + options?: AnomalyDetectorListMultivariateModelOptionalParams + ): AsyncIterableIterator { + for await (const page of this.listMultivariateModelPagingPage(options)) { + yield* page; + } + } + + /** + * This operation generates a model with 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. + * @param options The options parameters. + */ + async detectEntireSeries( + body: DetectRequest, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan( + "AnomalyDetector-detectEntireSeries", + options || {} + ); + const operationArguments: coreHttp.OperationArguments = { + body, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + detectEntireSeriesOperationSpec + ); + return result as AnomalyDetectorDetectEntireSeriesResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * 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. + * @param options The options parameters. + */ + async detectLastPoint( + body: DetectRequest, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan("AnomalyDetector-detectLastPoint", options || {}); + const operationArguments: coreHttp.OperationArguments = { + body, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + detectLastPointOperationSpec + ); + return result as AnomalyDetectorDetectLastPointResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * 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. + * @param options The options parameters. + */ + async detectChangePoint( + body: DetectChangePointRequest, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan("AnomalyDetector-detectChangePoint", options || {}); + const operationArguments: coreHttp.OperationArguments = { + body, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + detectChangePointOperationSpec + ); + return result as AnomalyDetectorDetectChangePointResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * Create and train a multivariate anomaly detection model. The request must include a source parameter + * to indicate an externally accessible Azure storage Uri (preferably a Shared Access Signature Uri). + * All time-series used in generate the model must be zipped into one single file. Each time-series + * will be in a single CSV file in which the first column is timestamp and the second column is value. + * @param modelRequest Training request + * @param options The options parameters. + */ + async trainMultivariateModel( + modelRequest: ModelInfo, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan( + "AnomalyDetector-trainMultivariateModel", + options || {} + ); + const operationArguments: coreHttp.OperationArguments = { + modelRequest, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + trainMultivariateModelOperationSpec + ); + return result as AnomalyDetectorTrainMultivariateModelResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * Get detailed information of multivariate model, including the training status and variables used in + * the model. + * @param modelId Model identifier. + * @param options The options parameters. + */ + async getMultivariateModel( + modelId: string, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan( + "AnomalyDetector-getMultivariateModel", + options || {} + ); + const operationArguments: coreHttp.OperationArguments = { + modelId, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + getMultivariateModelOperationSpec + ); + return result as AnomalyDetectorGetMultivariateModelResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * Delete an existing multivariate model according to the modelId + * @param modelId Model identifier. + * @param options The options parameters. + */ + async deleteMultivariateModel( + modelId: string, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan( + "AnomalyDetector-deleteMultivariateModel", + options || {} + ); + const operationArguments: coreHttp.OperationArguments = { + modelId, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + deleteMultivariateModelOperationSpec + ); + return result as coreHttp.RestResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * Submit detection multivariate anomaly task with the trained model of modelId, the input schema + * should be the same with the training request. Thus request will be complete asynchronously and will + * return a resultId for querying the detection result.The request should be a source link to indicate + * an externally accessible Azure storage Uri (preferably a Shared Access Signature Uri). All + * time-series used in generate the model must be zipped into one single file. Each time-series will be + * as follows: the first column is timestamp and the second column is value. + * @param modelId Model identifier. + * @param detectionRequest Detect anomaly request + * @param options The options parameters. + */ + async detectAnomaly( + modelId: string, + detectionRequest: DetectionRequest, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan("AnomalyDetector-detectAnomaly", options || {}); + const operationArguments: coreHttp.OperationArguments = { + modelId, + detectionRequest, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + detectAnomalyOperationSpec + ); + return result as AnomalyDetectorDetectAnomalyResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * Get multivariate anomaly detection result based on resultId returned by the DetectAnomalyAsync api + * @param resultId Result identifier. + * @param options The options parameters. + */ + async getDetectionResult( + resultId: string, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan( + "AnomalyDetector-getDetectionResult", + options || {} + ); + const operationArguments: coreHttp.OperationArguments = { + resultId, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + getDetectionResultOperationSpec + ); + return result as AnomalyDetectorGetDetectionResultResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * Export multivariate anomaly detection model based on modelId + * @param modelId Model identifier. + * @param options The options parameters. + */ + async exportModel( + modelId: string, + options?: coreHttp.OperationOptions + ): Promise { + const { span, updatedOptions } = createSpan("AnomalyDetector-exportModel", options || {}); + const operationArguments: coreHttp.OperationArguments = { + modelId, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest(operationArguments, exportModelOperationSpec); + return result as AnomalyDetectorExportModelResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * List models of a subscription + * @param options The options parameters. + */ + private async _listMultivariateModel( + options?: AnomalyDetectorListMultivariateModelOptionalParams + ): Promise { + const { span, updatedOptions } = createSpan( + "AnomalyDetector-_listMultivariateModel", + options || {} + ); + const operationArguments: coreHttp.OperationArguments = { + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + listMultivariateModelOperationSpec + ); + return result as AnomalyDetectorListMultivariateModelResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } + + /** + * ListMultivariateModelNext + * @param nextLink The nextLink from the previous successful call to the ListMultivariateModel method. + * @param options The options parameters. + */ + private async _listMultivariateModelNext( + nextLink: string, + options?: AnomalyDetectorListMultivariateModelNextOptionalParams + ): Promise { + const { span, updatedOptions } = createSpan( + "AnomalyDetector-_listMultivariateModelNext", + options || {} + ); + const operationArguments: coreHttp.OperationArguments = { + nextLink, + options: coreHttp.operationOptionsToRequestOptionsBase(updatedOptions || {}) + }; + try { + const result = await this.sendOperationRequest( + operationArguments, + listMultivariateModelNextOperationSpec + ); + return result as AnomalyDetectorListMultivariateModelNextResponse; + } catch (error) { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: error.message + }); + throw error; + } finally { + span.end(); + } + } +} +// Operation Specifications +const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); + +const detectEntireSeriesOperationSpec: coreHttp.OperationSpec = { + path: "/timeseries/entire/detect", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: Mappers.DetectEntireResponse + }, + default: { + bodyMapper: Mappers.AnomalyDetectorError + } + }, + requestBody: Parameters.body, + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.contentType, Parameters.accept], + mediaType: "json", + serializer +}; +const detectLastPointOperationSpec: coreHttp.OperationSpec = { + path: "/timeseries/last/detect", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: Mappers.DetectLastPointResponse + }, + default: { + bodyMapper: Mappers.AnomalyDetectorError + } + }, + requestBody: Parameters.body, + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.contentType, Parameters.accept], + mediaType: "json", + serializer +}; +const detectChangePointOperationSpec: coreHttp.OperationSpec = { + path: "/timeseries/changepoint/detect", + httpMethod: "POST", + responses: { + 200: { + bodyMapper: Mappers.DetectChangePointResponse + }, + default: { + bodyMapper: Mappers.AnomalyDetectorError + } + }, + requestBody: Parameters.body1, + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.contentType, Parameters.accept], + mediaType: "json", + serializer +}; +const trainMultivariateModelOperationSpec: coreHttp.OperationSpec = { + path: "/multivariate/models", + httpMethod: "POST", + responses: { + 201: { + headersMapper: Mappers.AnomalyDetectorTrainMultivariateModelHeaders + }, + default: { + bodyMapper: Mappers.ErrorResponse + } + }, + requestBody: Parameters.modelRequest, + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.contentType, Parameters.accept], + mediaType: "json", + serializer +}; +const getMultivariateModelOperationSpec: coreHttp.OperationSpec = { + path: "/multivariate/models/{modelId}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.Model + }, + default: { + bodyMapper: Mappers.ErrorResponse + } + }, + urlParameters: [Parameters.endpoint, Parameters.modelId], + headerParameters: [Parameters.accept], + serializer +}; +const deleteMultivariateModelOperationSpec: coreHttp.OperationSpec = { + path: "/multivariate/models/{modelId}", + httpMethod: "DELETE", + responses: { + 204: {}, + default: { + bodyMapper: Mappers.ErrorResponse + } + }, + urlParameters: [Parameters.endpoint, Parameters.modelId], + headerParameters: [Parameters.accept], + serializer +}; +const detectAnomalyOperationSpec: coreHttp.OperationSpec = { + path: "/multivariate/models/{modelId}/detect", + httpMethod: "POST", + responses: { + 201: { + headersMapper: Mappers.AnomalyDetectorDetectAnomalyHeaders + }, + default: { + bodyMapper: Mappers.ErrorResponse + } + }, + requestBody: Parameters.detectionRequest, + urlParameters: [Parameters.endpoint, Parameters.modelId], + headerParameters: [Parameters.contentType, Parameters.accept], + mediaType: "json", + serializer +}; +const getDetectionResultOperationSpec: coreHttp.OperationSpec = { + path: "/multivariate/results/{resultId}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.DetectionResult + }, + default: { + bodyMapper: Mappers.ErrorResponse + } + }, + urlParameters: [Parameters.endpoint, Parameters.resultId], + headerParameters: [Parameters.accept], + serializer +}; +const exportModelOperationSpec: coreHttp.OperationSpec = { + path: "/multivariate/models/{modelId}/export", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: { + type: { name: "Stream" }, + serializedName: "parsedResponse" + }, + headersMapper: Mappers.AnomalyDetectorExportModelHeaders + }, + default: {} + }, + urlParameters: [Parameters.endpoint, Parameters.modelId], + headerParameters: [Parameters.accept1], + serializer +}; +const listMultivariateModelOperationSpec: coreHttp.OperationSpec = { + path: "/multivariate/models", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.ModelList + }, + default: { + bodyMapper: Mappers.ErrorResponse + } + }, + queryParameters: [Parameters.skip, Parameters.top], + urlParameters: [Parameters.endpoint], + headerParameters: [Parameters.accept], + serializer +}; +const listMultivariateModelNextOperationSpec: coreHttp.OperationSpec = { + path: "{nextLink}", + httpMethod: "GET", + responses: { + 200: { + bodyMapper: Mappers.ModelList + }, + default: { + bodyMapper: Mappers.ErrorResponse + } + }, + queryParameters: [Parameters.skip, Parameters.top], + urlParameters: [Parameters.endpoint, Parameters.nextLink], + headerParameters: [Parameters.accept], + serializer +}; diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/generatedClientContext.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/anomalyDetectorContext.ts similarity index 77% rename from sdk/anomalydetector/ai-anomaly-detector/src/generated/generatedClientContext.ts rename to sdk/anomalydetector/ai-anomaly-detector/src/generated/anomalyDetectorContext.ts index 7375f2724549..ac8492c2768a 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/generated/generatedClientContext.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/generated/anomalyDetectorContext.ts @@ -7,21 +7,22 @@ */ import * as coreHttp from "@azure/core-http"; -import { GeneratedClientOptionalParams } from "./models"; +import { AnomalyDetectorOptionalParams } from "./models"; const packageName = "@azure/ai-form-recognizer"; const packageVersion = "3.0.0-beta.3"; -export class GeneratedClientContext extends coreHttp.ServiceClient { +/** @hidden */ +export class AnomalyDetectorContext extends coreHttp.ServiceClient { endpoint: string; /** - * Initializes a new instance of the GeneratedClientContext class. + * Initializes a new instance of the AnomalyDetectorContext class. * @param endpoint Supported Cognitive Services endpoints (protocol and hostname, for example: * https://westus2.api.cognitive.microsoft.com). * @param options The parameter options */ - constructor(endpoint: string, options?: GeneratedClientOptionalParams) { + constructor(endpoint: string, options?: AnomalyDetectorOptionalParams) { if (endpoint === undefined) { throw new Error("'endpoint' cannot be null"); } @@ -40,8 +41,7 @@ export class GeneratedClientContext extends coreHttp.ServiceClient { this.requestContentType = "application/json; charset=utf-8"; - this.baseUri = - options.endpoint || "{Endpoint}/anomalydetector/v1.1-preview"; + this.baseUri = options.endpoint || "{Endpoint}/anomalydetector/v1.1-preview"; // Parameter assignments this.endpoint = endpoint; diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/generatedClient.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/generatedClient.ts deleted file mode 100644 index f85a2189d4f6..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/src/generated/generatedClient.ts +++ /dev/null @@ -1,438 +0,0 @@ -/* - * Copyright (c) Microsoft Corporation. - * Licensed under the MIT License. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - * Changes may cause incorrect behavior and will be lost if the code is regenerated. - */ - -import * as coreHttp from "@azure/core-http"; -import * as Parameters from "./models/parameters"; -import * as Mappers from "./models/mappers"; -import { GeneratedClientContext } from "./generatedClientContext"; -import { - GeneratedClientOptionalParams, - DetectRequest, - GeneratedClientDetectEntireSeriesResponse, - GeneratedClientDetectLastPointResponse, - DetectChangePointRequest, - GeneratedClientDetectChangePointResponse, - ModelInfo, - GeneratedClientTrainMultivariateModelResponse, - GeneratedClientGetMultivariateModelResponse, - DetectionRequest, - GeneratedClientDetectAnomalyResponse, - GeneratedClientGetDetectionResultResponse, - GeneratedClientExportModelResponse, - GeneratedClientListMultivariateModelOptionalParams, - GeneratedClientListMultivariateModelResponse, - GeneratedClientListMultivariateModelNextOptionalParams, - GeneratedClientListMultivariateModelNextResponse -} from "./models"; - -export class GeneratedClient extends GeneratedClientContext { - /** - * Initializes a new instance of the GeneratedClient class. - * @param endpoint Supported Cognitive Services endpoints (protocol and hostname, for example: - * https://westus2.api.cognitive.microsoft.com). - * @param options The parameter options - */ - constructor(endpoint: string, options?: GeneratedClientOptionalParams) { - super(endpoint, options); - } - - /** - * This operation generates a model with 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. - * @param options The options parameters. - */ - detectEntireSeries( - body: DetectRequest, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { body, options: operationOptions }, - detectEntireSeriesOperationSpec - ) as Promise; - } - - /** - * 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. - * @param options The options parameters. - */ - detectLastPoint( - body: DetectRequest, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { body, options: operationOptions }, - detectLastPointOperationSpec - ) as Promise; - } - - /** - * 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. - * @param options The options parameters. - */ - detectChangePoint( - body: DetectChangePointRequest, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { body, options: operationOptions }, - detectChangePointOperationSpec - ) as Promise; - } - - /** - * Create and train a multivariate anomaly detection model. The request must include a source parameter - * to indicate an externally accessible Azure storage Uri (preferably a Shared Access Signature Uri). - * All time-series used in generate the model must be zipped into one single file. Each time-series - * will be in a single CSV file in which the first column is timestamp and the second column is value. - * @param modelRequest Training request - * @param options The options parameters. - */ - trainMultivariateModel( - modelRequest: ModelInfo, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { modelRequest, options: operationOptions }, - trainMultivariateModelOperationSpec - ) as Promise; - } - - /** - * Get detailed information of multivariate model, including the training status and variables used in - * the model. - * @param modelId Model identifier. - * @param options The options parameters. - */ - getMultivariateModel( - modelId: string, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { modelId, options: operationOptions }, - getMultivariateModelOperationSpec - ) as Promise; - } - - /** - * Delete an existing multivariate model according to the modelId - * @param modelId Model identifier. - * @param options The options parameters. - */ - deleteMultivariateModel( - modelId: string, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { modelId, options: operationOptions }, - deleteMultivariateModelOperationSpec - ) as Promise; - } - - /** - * Submit detection multivariate anomaly task with the trained model of modelId, the input schema - * should be the same with the training request. Thus request will be complete asynchronously and will - * return a resultId for querying the detection result.The request should be a source link to indicate - * an externally accessible Azure storage Uri (preferably a Shared Access Signature Uri). All - * time-series used in generate the model must be zipped into one single file. Each time-series will be - * as follows: the first column is timestamp and the second column is value. - * @param modelId Model identifier. - * @param detectionRequest Detect anomaly request - * @param options The options parameters. - */ - detectAnomaly( - modelId: string, - detectionRequest: DetectionRequest, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { modelId, detectionRequest, options: operationOptions }, - detectAnomalyOperationSpec - ) as Promise; - } - - /** - * Get multivariate anomaly detection result based on resultId returned by the DetectAnomalyAsync api - * @param resultId Result identifier. - * @param options The options parameters. - */ - getDetectionResult( - resultId: string, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { resultId, options: operationOptions }, - getDetectionResultOperationSpec - ) as Promise; - } - - /** - * Export multivariate anomaly detection model based on modelId - * @param modelId Model identifier. - * @param options The options parameters. - */ - exportModel( - modelId: string, - options?: coreHttp.OperationOptions - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { modelId, options: operationOptions }, - exportModelOperationSpec - ) as Promise; - } - - /** - * List models of a subscription - * @param options The options parameters. - */ - listMultivariateModel( - options?: GeneratedClientListMultivariateModelOptionalParams - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { options: operationOptions }, - listMultivariateModelOperationSpec - ) as Promise; - } - - /** - * ListMultivariateModelNext - * @param nextLink The nextLink from the previous successful call to the ListMultivariateModel method. - * @param options The options parameters. - */ - listMultivariateModelNext( - nextLink: string, - options?: GeneratedClientListMultivariateModelNextOptionalParams - ): Promise { - const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( - options || {} - ); - return this.sendOperationRequest( - { nextLink, options: operationOptions }, - listMultivariateModelNextOperationSpec - ) as Promise; - } -} -// Operation Specifications - -const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); - -const detectEntireSeriesOperationSpec: coreHttp.OperationSpec = { - path: "/timeseries/entire/detect", - httpMethod: "POST", - responses: { - 200: { - bodyMapper: Mappers.DetectEntireResponse - }, - default: { - bodyMapper: Mappers.AnomalyDetectorError - } - }, - requestBody: Parameters.body, - urlParameters: [Parameters.endpoint], - headerParameters: [Parameters.contentType, Parameters.accept], - mediaType: "json", - serializer -}; -const detectLastPointOperationSpec: coreHttp.OperationSpec = { - path: "/timeseries/last/detect", - httpMethod: "POST", - responses: { - 200: { - bodyMapper: Mappers.DetectLastPointResponse - }, - default: { - bodyMapper: Mappers.AnomalyDetectorError - } - }, - requestBody: Parameters.body, - urlParameters: [Parameters.endpoint], - headerParameters: [Parameters.contentType, Parameters.accept], - mediaType: "json", - serializer -}; -const detectChangePointOperationSpec: coreHttp.OperationSpec = { - path: "/timeseries/changepoint/detect", - httpMethod: "POST", - responses: { - 200: { - bodyMapper: Mappers.DetectChangePointResponse - }, - default: { - bodyMapper: Mappers.AnomalyDetectorError - } - }, - requestBody: Parameters.body1, - urlParameters: [Parameters.endpoint], - headerParameters: [Parameters.contentType, Parameters.accept], - mediaType: "json", - serializer -}; -const trainMultivariateModelOperationSpec: coreHttp.OperationSpec = { - path: "/multivariate/models", - httpMethod: "POST", - responses: { - 201: { - headersMapper: Mappers.GeneratedClientTrainMultivariateModelHeaders - }, - default: { - bodyMapper: Mappers.ErrorResponse - } - }, - requestBody: Parameters.modelRequest, - urlParameters: [Parameters.endpoint], - headerParameters: [Parameters.contentType, Parameters.accept], - mediaType: "json", - serializer -}; -const getMultivariateModelOperationSpec: coreHttp.OperationSpec = { - path: "/multivariate/models/{modelId}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.Model - }, - default: { - bodyMapper: Mappers.ErrorResponse - } - }, - urlParameters: [Parameters.endpoint, Parameters.modelId], - headerParameters: [Parameters.accept1], - serializer -}; -const deleteMultivariateModelOperationSpec: coreHttp.OperationSpec = { - path: "/multivariate/models/{modelId}", - httpMethod: "DELETE", - responses: { - 204: {}, - default: { - bodyMapper: Mappers.ErrorResponse - } - }, - urlParameters: [Parameters.endpoint, Parameters.modelId], - headerParameters: [Parameters.accept1], - serializer -}; -const detectAnomalyOperationSpec: coreHttp.OperationSpec = { - path: "/multivariate/models/{modelId}/detect", - httpMethod: "POST", - responses: { - 201: { - headersMapper: Mappers.GeneratedClientDetectAnomalyHeaders - }, - default: { - bodyMapper: Mappers.ErrorResponse - } - }, - requestBody: Parameters.detectionRequest, - urlParameters: [Parameters.endpoint, Parameters.modelId], - headerParameters: [Parameters.contentType, Parameters.accept], - mediaType: "json", - serializer -}; -const getDetectionResultOperationSpec: coreHttp.OperationSpec = { - path: "/multivariate/results/{resultId}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.DetectionResult - }, - default: { - bodyMapper: Mappers.ErrorResponse - } - }, - urlParameters: [Parameters.endpoint, Parameters.resultId], - headerParameters: [Parameters.accept1], - serializer -}; -const exportModelOperationSpec: coreHttp.OperationSpec = { - path: "/multivariate/models/{modelId}/export", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: { - type: { name: "Stream" }, - serializedName: "parsedResponse" - }, - headersMapper: Mappers.GeneratedClientExportModelHeaders - }, - default: {} - }, - urlParameters: [Parameters.endpoint, Parameters.modelId], - headerParameters: [Parameters.accept2], - serializer -}; -const listMultivariateModelOperationSpec: coreHttp.OperationSpec = { - path: "/multivariate/models", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.ModelList - }, - default: { - bodyMapper: Mappers.ErrorResponse - } - }, - queryParameters: [Parameters.skip, Parameters.top], - urlParameters: [Parameters.endpoint], - headerParameters: [Parameters.accept1], - serializer -}; -const listMultivariateModelNextOperationSpec: coreHttp.OperationSpec = { - path: "{nextLink}", - httpMethod: "GET", - responses: { - 200: { - bodyMapper: Mappers.ModelList - }, - default: { - bodyMapper: Mappers.ErrorResponse - } - }, - queryParameters: [Parameters.skip, Parameters.top], - urlParameters: [Parameters.endpoint, Parameters.nextLink], - headerParameters: [Parameters.accept1], - serializer -}; diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/index.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/index.ts index 3aebf3c9a56c..4b3dc0f751bd 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/generated/index.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/generated/index.ts @@ -6,6 +6,7 @@ * Changes may cause incorrect behavior and will be lost if the code is regenerated. */ +/// export * from "./models"; -export { GeneratedClient } from "./generatedClient"; -export { GeneratedClientContext } from "./generatedClientContext"; +export { AnomalyDetector } from "./anomalyDetector"; +export { AnomalyDetectorContext } from "./anomalyDetectorContext"; diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/index.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/index.ts index 7fd309dd6d13..5637f4a8acd1 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/index.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/index.ts @@ -9,230 +9,142 @@ import * as coreHttp from "@azure/core-http"; export interface DetectRequest { - /** - * 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. - */ + /** 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. */ series: TimeSeriesPoint[]; - /** - * 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. - */ + /** 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. */ granularity?: TimeGranularity; - /** - * 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}. - */ + /** 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}. */ customInterval?: number; - /** - * Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - */ + /** Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. */ period?: number; - /** - * Optional argument, advanced model parameter, max anomaly ratio in a time series. - */ + /** Optional argument, advanced model parameter, max anomaly ratio in a time series. */ maxAnomalyRatio?: number; - /** - * 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. - */ + /** 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. */ sensitivity?: number; } export interface TimeSeriesPoint { - /** - * Optional argument, timestamp of a data point (ISO8601 format). - */ + /** Optional argument, timestamp of a data point (ISO8601 format). */ timestamp?: Date; - /** - * The measurement of that point, should be float. - */ + /** The measurement of that point, should be float. */ value: number; } export interface DetectEntireResponse { - /** - * Frequency extracted from the series, zero means no recurrent pattern has been found. - */ + /** Frequency extracted from the series, zero means no recurrent pattern has been found. */ period: number; - /** - * ExpectedValues contain expected value for each input point. The index of the array is consistent with the input series. - */ + /** ExpectedValues contain expected value for each input point. The index of the array is consistent with the input series. */ expectedValues: number[]; - /** - * 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. - */ + /** 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. */ upperMargins: number[]; - /** - * 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. - */ + /** 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. */ lowerMargins: number[]; - /** - * 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. - */ + /** 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. */ isAnomaly: boolean[]; - /** - * 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. - */ + /** 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. */ isNegativeAnomaly: boolean[]; - /** - * 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. - */ + /** 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. */ isPositiveAnomaly: boolean[]; } -/** - * Error information returned by the API. - */ +/** Error information returned by the API. */ export interface AnomalyDetectorError { - /** - * The error code. - */ + /** The error code. */ code?: AnomalyDetectorErrorCodes; - /** - * A message explaining the error reported by the service. - */ + /** A message explaining the error reported by the service. */ message?: string; } export interface DetectLastPointResponse { - /** - * Frequency extracted from the series, zero means no recurrent pattern has been found. - */ + /** Frequency extracted from the series, zero means no recurrent pattern has been found. */ period: number; - /** - * Suggested input series points needed for detecting the latest point. - */ + /** Suggested input series points needed for detecting the latest point. */ suggestedWindow: number; - /** - * Expected value of the latest point. - */ + /** Expected value of the latest point. */ expectedValue: number; - /** - * 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. - */ + /** 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. */ upperMargin: number; - /** - * Lower margin of the latest point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. - */ + /** Lower margin of the latest point. LowerMargin is used to calculate lowerBoundary, which equals to expectedValue - (100 - marginScale)*lowerMargin. */ lowerMargin: number; - /** - * Anomaly status of the latest point, true means the latest point is an anomaly either in negative direction or positive direction. - */ + /** Anomaly status of the latest point, true means the latest point is an anomaly either in negative direction or positive direction. */ isAnomaly: boolean; - /** - * 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. - */ + /** 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. */ isNegativeAnomaly: boolean; - /** - * 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. - */ + /** 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. */ isPositiveAnomaly: boolean; } export interface DetectChangePointRequest { - /** - * Time series data points. Points should be sorted by timestamp in ascending order to match the change point detection result. - */ + /** Time series data points. Points should be sorted by timestamp in ascending order to match the change point detection result. */ series: TimeSeriesPoint[]; - /** - * Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid. - */ + /** Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid. */ granularity: TimeGranularity; - /** - * 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}. - */ + /** 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}. */ customInterval?: number; - /** - * Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - */ + /** Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. */ period?: number; - /** - * Optional argument, advanced model parameter, a default stableTrendWindow will be used in detection. - */ + /** Optional argument, advanced model parameter, a default stableTrendWindow will be used in detection. */ stableTrendWindow?: number; - /** - * 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. - */ + /** 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. */ threshold?: number; } export interface DetectChangePointResponse { /** * Frequency extracted from the series, zero means no recurrent pattern has been found. + * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly period?: number; - /** - * 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. - */ + /** 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. */ isChangePoint?: boolean[]; - /** - * the change point confidence of each point - */ + /** the change point confidence of each point */ confidenceScores?: number[]; } -/** - * Train result of a model including status, errors and diagnose info for model and variables. - */ +/** Train result of a model including status, errors and diagnose info for model and variables. */ export interface ModelInfo { - /** - * An optional field, indicates how many history points will be used to determine the anomaly score of one subsequent point. - */ + /** An optional field, indicates how many history points will be used to determine the anomaly score of one subsequent point. */ slidingWindow?: number; - /** - * An optional field, since those multivariate need to be aligned in the same timestamp before starting the detection. - */ + /** An optional field, since those multivariate need to be aligned in the same timestamp before starting the detection. */ alignPolicy?: AlignPolicy; - /** - * 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. - */ + /** 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. */ source: string; - /** - * require field, start time of data be used for generating multivariate anomaly detection model, should be data-time - */ + /** require field, start time of data be used for generating multivariate anomaly detection model, should be data-time */ startTime: Date; - /** - * require field, end time of data be used for generating multivariate anomaly detection model, should be data-time - */ + /** require field, end time of data be used for generating multivariate anomaly detection model, should be data-time */ endTime: Date; - /** - * optional field, name of the model - */ + /** optional field, name of the model */ displayName?: string; /** * Model training status. + * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status?: ModelStatus; /** * Error message when fails to create a model. + * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly errors?: ErrorResponse[]; /** * Used for deep analysis model and variables + * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly diagnosticsInfo?: DiagnosticsInfo; } export interface AlignPolicy { - /** - * An optional field, indicates how we align different variables into the same time-range which is required by the model.{Inner, Outer} - */ + /** An optional field, indicates how we align different variables into the same time-range which is required by the model.{Inner, Outer} */ alignMode?: AlignMode; - /** - * 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} - */ + /** 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} */ fillNAMethod?: FillNAMethod; - /** - * optional field, only be useful if FillNAMethod is set to Pad. - */ + /** optional field, only be useful if FillNAMethod is set to Pad. */ paddingValue?: number; } export interface ErrorResponse { - /** - * The error Code - */ + /** The error Code */ code: string; - /** - * A message explaining the error reported by the service. - */ + /** A message explaining the error reported by the service. */ message: string; } @@ -242,9 +154,7 @@ export interface DiagnosticsInfo { } export interface ModelState { - /** - * Epoch id - */ + /** Epoch id */ epochIds?: number[]; trainLosses?: number[]; validationLosses?: number[]; @@ -252,238 +162,164 @@ export interface ModelState { } export interface VariableState { - /** - * Variable name. - */ + /** Variable name. */ variable?: string; - /** - * Merged NA ratio of a variable. - */ + /** Merged NA ratio of a variable. */ filledNARatio?: number; - /** - * Effective time-series points count. - */ + /** Effective time-series points count. */ effectiveCount?: number; - /** - * Start time of a variable - */ + /** Start time of a variable */ startTime?: Date; - /** - * End time of a variable - */ + /** End time of a variable */ endTime?: Date; - /** - * Error message when parse variable - */ + /** Error message when parse variable */ errors?: ErrorResponse[]; } -/** - * Response of get model. - */ +/** Response of get model. */ export interface Model { - /** - * Model identifier. - */ + /** Model identifier. */ modelId: string; - /** - * Date and time (UTC) when the model was created. - */ + /** Date and time (UTC) when the model was created. */ createdTime: Date; - /** - * Date and time (UTC) when the model was last updated. - */ + /** Date and time (UTC) when the model was last updated. */ lastUpdatedTime: Date; - /** - * Training Status of the model. - */ + /** Training Status of the model. */ modelInfo?: ModelInfo; } -/** - * Request to submit a detection. - */ +/** Request to submit a detection. */ export interface DetectionRequest { - /** - * 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. - */ + /** 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. */ source: string; - /** - * A require field, start time of data be used for detection, should be date-time. - */ + /** A require field, start time of data be used for detection, should be date-time. */ startTime: Date; - /** - * A require field, end time of data be used for detection, should be date-time. - */ + /** A require field, end time of data be used for detection, should be date-time. */ endTime: Date; } -/** - * Anomaly Response of one detection corresponds to a resultId. - */ +/** Anomaly Response of one detection corresponds to a resultId. */ export interface DetectionResult { resultId: string; - /** - * Multivariate anomaly detection status - */ + /** Multivariate anomaly detection status */ summary: DetectionResultSummary; - /** - * anomaly status of each timestamp - */ + /** anomaly status of each timestamp */ results: AnomalyState[]; } export interface DetectionResultSummary { - /** - * Multivariate anomaly detection status - */ + /** Multivariate anomaly detection status */ status: DetectionStatus; - /** - * Error message when creating or training model fails. - */ + /** Error message when creating or training model fails. */ errors?: ErrorResponse[]; variableStates?: VariableState[]; - /** - * Request when creating the model. - */ + /** Request when creating the model. */ setupInfo: DetectionRequest; } export interface AnomalyState { - /** - * timestamp - */ + /** timestamp */ timestamp: Date; value?: AnomalyValue; - /** - * Error message when inference this timestamp - */ + /** Error message when inference this timestamp */ errors?: ErrorResponse[]; } export interface AnomalyValue { - /** - * 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. - */ + /** 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. */ contributors?: AnomalyContributor[]; - /** - * To indicate whether current timestamp is anomaly or not - */ + /** To indicate whether current timestamp is anomaly or not */ isAnomaly: boolean; - /** - * anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be - */ + /** anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be */ severity: number; - /** - * anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be, score measures global significance - */ + /** anomaly score of the current timestamp, the more significant an anomaly is, the higher the score will be, score measures global significance */ score?: number; } export interface AnomalyContributor { - /** - * The higher the contribution score is, the more likely the variable to be the root cause of a anomaly. - */ + /** The higher the contribution score is, the more likely the variable to be the root cause of a anomaly. */ contributionScore?: number; - /** - * Variable name of a contributor - */ + /** Variable name of a contributor */ variable?: string; } -/** - * Response to the list models operation. - */ +/** Response to the list models operation. */ export interface ModelList { - /** - * List of models - */ + /** List of models */ models: ModelSnapshot[]; - /** - * Current count of trained multivariate models. - */ + /** Current count of trained multivariate models. */ currentCount: number; - /** - * Max number of models that can be trained for this subscription. - */ + /** Max number of models that can be trained for this subscription. */ maxCount: number; - /** - * next link to fetch more models - */ + /** next link to fetch more models */ nextLink?: string; } export interface ModelSnapshot { - /** - * Model identifier. - */ + /** Model identifier. */ modelId: string; - /** - * Date and time (UTC) when the model was created. - */ + /** Date and time (UTC) when the model was created. */ createdTime: Date; - /** - * Date and time (UTC) when the model was last updated. - */ + /** Date and time (UTC) when the model was last updated. */ lastUpdatedTime: Date; /** * Model training status. + * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly status: ModelStatus; displayName?: string; - /** - * Count of variables - */ + /** Count of variables */ variablesCount: number; } -/** - * Defines headers for GeneratedClient_trainMultivariateModel operation. - */ -export interface GeneratedClientTrainMultivariateModelHeaders { - /** - * Location and ID of the model being saved. - */ +/** Defines headers for AnomalyDetector_trainMultivariateModel operation. */ +export interface AnomalyDetectorTrainMultivariateModelHeaders { + /** Location and ID of the model being saved. */ location?: string; } -/** - * Defines headers for GeneratedClient_detectAnomaly operation. - */ -export interface GeneratedClientDetectAnomalyHeaders { - /** - * Location and ID of the detection result being saved. - */ +/** Defines headers for AnomalyDetector_detectAnomaly operation. */ +export interface AnomalyDetectorDetectAnomalyHeaders { + /** Location and ID of the detection result being saved. */ location?: string; } -/** - * Defines headers for GeneratedClient_exportModel operation. - */ -export interface GeneratedClientExportModelHeaders { - /** - * application/zip - */ +/** Defines headers for AnomalyDetector_exportModel operation. */ +export interface AnomalyDetectorExportModelHeaders { + /** application/zip */ contentType?: string; } +/** Known values of {@link AnomalyDetectorErrorCodes} that the service accepts. */ +export const enum KnownAnomalyDetectorErrorCodes { + InvalidCustomInterval = "InvalidCustomInterval", + BadArgument = "BadArgument", + InvalidGranularity = "InvalidGranularity", + InvalidPeriod = "InvalidPeriod", + InvalidModelArgument = "InvalidModelArgument", + InvalidSeries = "InvalidSeries", + InvalidJsonFormat = "InvalidJsonFormat", + RequiredGranularity = "RequiredGranularity", + RequiredSeries = "RequiredSeries" +} + /** - * Defines values for AnomalyDetectorErrorCodes. - */ -export type AnomalyDetectorErrorCodes = - | "InvalidCustomInterval" - | "BadArgument" - | "InvalidGranularity" - | "InvalidPeriod" - | "InvalidModelArgument" - | "InvalidSeries" - | "InvalidJsonFormat" - | "RequiredGranularity" - | "RequiredSeries" - | string; -/** - * Defines values for TimeGranularity. + * Defines values for AnomalyDetectorErrorCodes. \ + * {@link KnownAnomalyDetectorErrorCodes} can be used interchangeably with AnomalyDetectorErrorCodes, + * this enum contains the known values that the service supports. + * ### Know values supported by the service + * **InvalidCustomInterval** \ + * **BadArgument** \ + * **InvalidGranularity** \ + * **InvalidPeriod** \ + * **InvalidModelArgument** \ + * **InvalidSeries** \ + * **InvalidJsonFormat** \ + * **RequiredGranularity** \ + * **RequiredSeries** */ +export type AnomalyDetectorErrorCodes = string; +/** Defines values for TimeGranularity. */ export type TimeGranularity = | "yearly" | "monthly" @@ -494,13 +330,9 @@ export type TimeGranularity = | "secondly" | "microsecond" | "none"; -/** - * Defines values for AlignMode. - */ +/** Defines values for AlignMode. */ export type AlignMode = "Inner" | "Outer"; -/** - * Defines values for FillNAMethod. - */ +/** Defines values for FillNAMethod. */ export type FillNAMethod = | "Previous" | "Subsequent" @@ -508,149 +340,91 @@ export type FillNAMethod = | "Zero" | "Pad" | "NotFill"; -/** - * Defines values for ModelStatus. - */ +/** Defines values for ModelStatus. */ export type ModelStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; -/** - * Defines values for DetectionStatus. - */ +/** Defines values for DetectionStatus. */ export type DetectionStatus = "CREATED" | "RUNNING" | "READY" | "FAILED"; -/** - * Contains response data for the detectEntireSeries operation. - */ -export type GeneratedClientDetectEntireSeriesResponse = DetectEntireResponse & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the detectEntireSeries operation. */ +export type AnomalyDetectorDetectEntireSeriesResponse = DetectEntireResponse & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The response body as text (string format) - */ + /** The response body as text (string format) */ bodyAsText: string; - /** - * The response body as parsed JSON or XML - */ + /** The response body as parsed JSON or XML */ parsedBody: DetectEntireResponse; }; }; -/** - * Contains response data for the detectLastPoint operation. - */ -export type GeneratedClientDetectLastPointResponse = DetectLastPointResponse & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the detectLastPoint operation. */ +export type AnomalyDetectorDetectLastPointResponse = DetectLastPointResponse & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The response body as text (string format) - */ + /** The response body as text (string format) */ bodyAsText: string; - /** - * The response body as parsed JSON or XML - */ + /** The response body as parsed JSON or XML */ parsedBody: DetectLastPointResponse; }; }; -/** - * Contains response data for the detectChangePoint operation. - */ -export type GeneratedClientDetectChangePointResponse = DetectChangePointResponse & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the detectChangePoint operation. */ +export type AnomalyDetectorDetectChangePointResponse = DetectChangePointResponse & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The response body as text (string format) - */ + /** The response body as text (string format) */ bodyAsText: string; - /** - * The response body as parsed JSON or XML - */ + /** The response body as parsed JSON or XML */ parsedBody: DetectChangePointResponse; }; }; -/** - * Contains response data for the trainMultivariateModel operation. - */ -export type GeneratedClientTrainMultivariateModelResponse = GeneratedClientTrainMultivariateModelHeaders & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the trainMultivariateModel operation. */ +export type AnomalyDetectorTrainMultivariateModelResponse = AnomalyDetectorTrainMultivariateModelHeaders & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The parsed HTTP response headers. - */ - parsedHeaders: GeneratedClientTrainMultivariateModelHeaders; + /** The parsed HTTP response headers. */ + parsedHeaders: AnomalyDetectorTrainMultivariateModelHeaders; }; }; -/** - * Contains response data for the getMultivariateModel operation. - */ -export type GeneratedClientGetMultivariateModelResponse = Model & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the getMultivariateModel operation. */ +export type AnomalyDetectorGetMultivariateModelResponse = Model & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The response body as text (string format) - */ + /** The response body as text (string format) */ bodyAsText: string; - /** - * The response body as parsed JSON or XML - */ + /** The response body as parsed JSON or XML */ parsedBody: Model; }; }; -/** - * Contains response data for the detectAnomaly operation. - */ -export type GeneratedClientDetectAnomalyResponse = GeneratedClientDetectAnomalyHeaders & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the detectAnomaly operation. */ +export type AnomalyDetectorDetectAnomalyResponse = AnomalyDetectorDetectAnomalyHeaders & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The parsed HTTP response headers. - */ - parsedHeaders: GeneratedClientDetectAnomalyHeaders; + /** The parsed HTTP response headers. */ + parsedHeaders: AnomalyDetectorDetectAnomalyHeaders; }; }; -/** - * Contains response data for the getDetectionResult operation. - */ -export type GeneratedClientGetDetectionResultResponse = DetectionResult & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the getDetectionResult operation. */ +export type AnomalyDetectorGetDetectionResultResponse = DetectionResult & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The response body as text (string format) - */ + /** The response body as text (string format) */ bodyAsText: string; - /** - * The response body as parsed JSON or XML - */ + /** The response body as parsed JSON or XML */ parsedBody: DetectionResult; }; }; -/** - * Contains response data for the exportModel operation. - */ -export type GeneratedClientExportModelResponse = GeneratedClientExportModelHeaders & { +/** Contains response data for the exportModel operation. */ +export type AnomalyDetectorExportModelResponse = AnomalyDetectorExportModelHeaders & { /** * BROWSER ONLY * @@ -666,94 +440,58 @@ export type GeneratedClientExportModelResponse = GeneratedClientExportModelHeade */ readableStreamBody?: NodeJS.ReadableStream; - /** - * The underlying HTTP response. - */ + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The parsed HTTP response headers. - */ - parsedHeaders: GeneratedClientExportModelHeaders; + /** The parsed HTTP response headers. */ + parsedHeaders: AnomalyDetectorExportModelHeaders; }; }; -/** - * Optional parameters. - */ -export interface GeneratedClientListMultivariateModelOptionalParams +/** Optional parameters. */ +export interface AnomalyDetectorListMultivariateModelOptionalParams extends coreHttp.OperationOptions { - /** - * $skip indicates how many models will be skipped. - */ + /** $skip indicates how many models will be skipped. */ skip?: number; - /** - * $top indicates how many models will be fetched. - */ + /** $top indicates how many models will be fetched. */ top?: number; } -/** - * Contains response data for the listMultivariateModel operation. - */ -export type GeneratedClientListMultivariateModelResponse = ModelList & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the listMultivariateModel operation. */ +export type AnomalyDetectorListMultivariateModelResponse = ModelList & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The response body as text (string format) - */ + /** The response body as text (string format) */ bodyAsText: string; - /** - * The response body as parsed JSON or XML - */ + /** The response body as parsed JSON or XML */ parsedBody: ModelList; }; }; -/** - * Optional parameters. - */ -export interface GeneratedClientListMultivariateModelNextOptionalParams +/** Optional parameters. */ +export interface AnomalyDetectorListMultivariateModelNextOptionalParams extends coreHttp.OperationOptions { - /** - * $skip indicates how many models will be skipped. - */ + /** $skip indicates how many models will be skipped. */ skip?: number; - /** - * $top indicates how many models will be fetched. - */ + /** $top indicates how many models will be fetched. */ top?: number; } -/** - * Contains response data for the listMultivariateModelNext operation. - */ -export type GeneratedClientListMultivariateModelNextResponse = ModelList & { - /** - * The underlying HTTP response. - */ +/** Contains response data for the listMultivariateModelNext operation. */ +export type AnomalyDetectorListMultivariateModelNextResponse = ModelList & { + /** The underlying HTTP response. */ _response: coreHttp.HttpResponse & { - /** - * The response body as text (string format) - */ + /** The response body as text (string format) */ bodyAsText: string; - /** - * The response body as parsed JSON or XML - */ + /** The response body as parsed JSON or XML */ parsedBody: ModelList; }; }; -/** - * Optional parameters. - */ -export interface GeneratedClientOptionalParams +/** Optional parameters. */ +export interface AnomalyDetectorOptionalParams extends coreHttp.ServiceClientOptions { - /** - * Overrides client endpoint. - */ + /** Overrides client endpoint. */ endpoint?: string; } diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/mappers.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/mappers.ts index 7b4d57188925..7c810498d872 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/mappers.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/mappers.ts @@ -18,7 +18,12 @@ export const DetectRequest: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Composite", className: "TimeSeriesPoint" } } + element: { + type: { + name: "Composite", + className: "TimeSeriesPoint" + } + } } }, granularity: { @@ -105,7 +110,11 @@ export const DetectEntireResponse: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } }, upperMargins: { @@ -113,7 +122,11 @@ export const DetectEntireResponse: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } }, lowerMargins: { @@ -121,7 +134,11 @@ export const DetectEntireResponse: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } }, isAnomaly: { @@ -129,7 +146,11 @@ export const DetectEntireResponse: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Boolean" } } + element: { + type: { + name: "Boolean" + } + } } }, isNegativeAnomaly: { @@ -137,7 +158,11 @@ export const DetectEntireResponse: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Boolean" } } + element: { + type: { + name: "Boolean" + } + } } }, isPositiveAnomaly: { @@ -145,7 +170,11 @@ export const DetectEntireResponse: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Boolean" } } + element: { + type: { + name: "Boolean" + } + } } } } @@ -248,7 +277,12 @@ export const DetectChangePointRequest: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Composite", className: "TimeSeriesPoint" } } + element: { + type: { + name: "Composite", + className: "TimeSeriesPoint" + } + } } }, granularity: { @@ -313,14 +347,22 @@ export const DetectChangePointResponse: coreHttp.CompositeMapper = { serializedName: "isChangePoint", type: { name: "Sequence", - element: { type: { name: "Boolean" } } + element: { + type: { + name: "Boolean" + } + } } }, confidenceScores: { serializedName: "confidenceScores", type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } } } @@ -388,7 +430,12 @@ export const ModelInfo: coreHttp.CompositeMapper = { readOnly: true, type: { name: "Sequence", - element: { type: { name: "Composite", className: "ErrorResponse" } } + element: { + type: { + name: "Composite", + className: "ErrorResponse" + } + } } }, diagnosticsInfo: { @@ -477,7 +524,12 @@ export const DiagnosticsInfo: coreHttp.CompositeMapper = { serializedName: "variableStates", type: { name: "Sequence", - element: { type: { name: "Composite", className: "VariableState" } } + element: { + type: { + name: "Composite", + className: "VariableState" + } + } } } } @@ -493,28 +545,44 @@ export const ModelState: coreHttp.CompositeMapper = { serializedName: "epochIds", type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } }, trainLosses: { serializedName: "trainLosses", type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } }, validationLosses: { serializedName: "validationLosses", type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } }, latenciesInSeconds: { serializedName: "latenciesInSeconds", type: { name: "Sequence", - element: { type: { name: "Number" } } + element: { + type: { + name: "Number" + } + } } } } @@ -534,7 +602,8 @@ export const VariableState: coreHttp.CompositeMapper = { }, filledNARatio: { constraints: { - InclusiveMaximum: 1 + InclusiveMaximum: 1, + InclusiveMinimum: 0 }, serializedName: "filledNARatio", type: { @@ -563,7 +632,12 @@ export const VariableState: coreHttp.CompositeMapper = { serializedName: "errors", type: { name: "Sequence", - element: { type: { name: "Composite", className: "ErrorResponse" } } + element: { + type: { + name: "Composite", + className: "ErrorResponse" + } + } } } } @@ -661,7 +735,12 @@ export const DetectionResult: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Composite", className: "AnomalyState" } } + element: { + type: { + name: "Composite", + className: "AnomalyState" + } + } } } } @@ -685,14 +764,24 @@ export const DetectionResultSummary: coreHttp.CompositeMapper = { serializedName: "errors", type: { name: "Sequence", - element: { type: { name: "Composite", className: "ErrorResponse" } } + element: { + type: { + name: "Composite", + className: "ErrorResponse" + } + } } }, variableStates: { serializedName: "variableStates", type: { name: "Sequence", - element: { type: { name: "Composite", className: "VariableState" } } + element: { + type: { + name: "Composite", + className: "VariableState" + } + } } }, setupInfo: { @@ -729,7 +818,12 @@ export const AnomalyState: coreHttp.CompositeMapper = { serializedName: "errors", type: { name: "Sequence", - element: { type: { name: "Composite", className: "ErrorResponse" } } + element: { + type: { + name: "Composite", + className: "ErrorResponse" + } + } } } } @@ -746,7 +840,10 @@ export const AnomalyValue: coreHttp.CompositeMapper = { type: { name: "Sequence", element: { - type: { name: "Composite", className: "AnomalyContributor" } + type: { + name: "Composite", + className: "AnomalyContributor" + } } } }, @@ -759,7 +856,8 @@ export const AnomalyValue: coreHttp.CompositeMapper = { }, severity: { constraints: { - InclusiveMaximum: 1 + InclusiveMaximum: 1, + InclusiveMinimum: 0 }, serializedName: "severity", required: true, @@ -769,7 +867,8 @@ export const AnomalyValue: coreHttp.CompositeMapper = { }, score: { constraints: { - InclusiveMaximum: 2 + InclusiveMaximum: 2, + InclusiveMinimum: 0 }, serializedName: "score", type: { @@ -787,7 +886,8 @@ export const AnomalyContributor: coreHttp.CompositeMapper = { modelProperties: { contributionScore: { constraints: { - InclusiveMaximum: 2 + InclusiveMaximum: 2, + InclusiveMinimum: 0 }, serializedName: "contributionScore", type: { @@ -814,7 +914,12 @@ export const ModelList: coreHttp.CompositeMapper = { required: true, type: { name: "Sequence", - element: { type: { name: "Composite", className: "ModelSnapshot" } } + element: { + type: { + name: "Composite", + className: "ModelSnapshot" + } + } } }, currentCount: { @@ -893,10 +998,10 @@ export const ModelSnapshot: coreHttp.CompositeMapper = { } }; -export const GeneratedClientTrainMultivariateModelHeaders: coreHttp.CompositeMapper = { +export const AnomalyDetectorTrainMultivariateModelHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", - className: "GeneratedClientTrainMultivariateModelHeaders", + className: "AnomalyDetectorTrainMultivariateModelHeaders", modelProperties: { location: { serializedName: "location", @@ -908,10 +1013,10 @@ export const GeneratedClientTrainMultivariateModelHeaders: coreHttp.CompositeMap } }; -export const GeneratedClientDetectAnomalyHeaders: coreHttp.CompositeMapper = { +export const AnomalyDetectorDetectAnomalyHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", - className: "GeneratedClientDetectAnomalyHeaders", + className: "AnomalyDetectorDetectAnomalyHeaders", modelProperties: { location: { serializedName: "location", @@ -923,10 +1028,10 @@ export const GeneratedClientDetectAnomalyHeaders: coreHttp.CompositeMapper = { } }; -export const GeneratedClientExportModelHeaders: coreHttp.CompositeMapper = { +export const AnomalyDetectorExportModelHeaders: coreHttp.CompositeMapper = { type: { name: "Composite", - className: "GeneratedClientExportModelHeaders", + className: "AnomalyDetectorExportModelHeaders", modelProperties: { contentType: { serializedName: "content-type", diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/parameters.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/parameters.ts index c4dd5cdcef3f..c9ae15e3b8f0 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/parameters.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/generated/models/parameters.ts @@ -69,18 +69,6 @@ export const modelRequest: OperationParameter = { mapper: ModelInfoMapper }; -export const accept1: OperationParameter = { - parameterPath: "accept", - mapper: { - defaultValue: "application/json", - isConstant: true, - serializedName: "Accept", - type: { - name: "String" - } - } -}; - export const modelId: OperationURLParameter = { parameterPath: "modelId", mapper: { @@ -108,7 +96,7 @@ export const resultId: OperationURLParameter = { } }; -export const accept2: OperationParameter = { +export const accept1: OperationParameter = { parameterPath: "accept", mapper: { defaultValue: "application/zip", diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/generated/tracing.ts b/sdk/anomalydetector/ai-anomaly-detector/src/generated/tracing.ts new file mode 100644 index 000000000000..fc934f6d05b9 --- /dev/null +++ b/sdk/anomalydetector/ai-anomaly-detector/src/generated/tracing.ts @@ -0,0 +1,14 @@ +/* + * Copyright (c) Microsoft Corporation. + * Licensed under the MIT License. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is regenerated. + */ + +import { createSpanFunction } from "@azure/core-tracing"; + +export const createSpan = createSpanFunction({ + namespace: "Microsoft.CognitiveServices", + packagePrefix: "Azure.CognitiveServices.AnomalyDetector" +}); diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/index.ts b/sdk/anomalydetector/ai-anomaly-detector/src/index.ts index 11082547fadb..32737a93c4f2 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/index.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/index.ts @@ -1,16 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. +export { AnomalyDetectorClient } from "./AnomalyDetectorClient"; export { - AnomalyDetectorClient, - DetectEntireSeriesOptions, - DetectLastPointOptions, - DetectChangePointOptions, - TrainMultivariateModelOptions, - GetMultivariateModelOptions, - DeleteMultivariateModelOptions, - DetectAnomalyOptions, - GetDetectionResultOptions, - ExportModelOptions -} from "./AnomalyDetectorClient"; + AnomalyDetector, + AnomalyDetectorContext, + AnomalyDetectorOptionalParams +} from "./generated"; export * from "./models"; diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/models.ts b/sdk/anomalydetector/ai-anomaly-detector/src/models.ts index 3cbe012a0867..7599002ce24d 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/src/models.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/src/models.ts @@ -2,14 +2,13 @@ // Licensed under the MIT license. import { PipelineOptions } from "@azure/core-http"; -import { TimeSeriesPoint } from "./generated"; /** * Client options used to configure Form Recognizer API requests. */ export interface AnomalyDetectorClientOptions extends PipelineOptions {} -export enum TimeGranularity { +export enum KnownTimeGranularity { /** * Yearly time granularity */ @@ -48,71 +47,19 @@ export enum TimeGranularity { none = "none" } -export interface DetectRequest { - /** - * 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. - */ - series: TimeSeriesPoint[]; - /** - * Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid. - */ - granularity: TimeGranularity; - /** - * 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}`. - */ - customInterval?: number; - /** - * Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - */ - period?: number; - /** - * Optional argument, advanced model parameter, max anomaly ratio in a time series. - */ - maxAnomalyRatio?: number; - /** - * 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. - */ - sensitivity?: number; -} - -export interface DetectChangePointRequest { - /** - * Time series data points. Points should be sorted by timestamp in ascending order to match the change point detection result. - */ - series: TimeSeriesPoint[]; - /** - * Can only be one of yearly, monthly, weekly, daily, hourly, minutely or secondly. Granularity is used for verify whether input series is valid. - */ - granularity: TimeGranularity; - /** - * 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}`. - */ - customInterval?: number; - /** - * Optional argument, periodic value of a time series. If the value is null or does not present, the API will determine the period automatically. - */ - period?: number; - /** - * Optional argument, advanced model parameter, a default stableTrendWindow will be used in detection. - */ - stableTrendWindow?: number; - /** - * 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. - */ - threshold?: number; -} - export { - GeneratedClientDetectChangePointResponse as AnomalyDetectorClientDetectChangePointResponse, - GeneratedClientDetectEntireSeriesResponse as AnomalyDetectorClientDetectEntireResponse, - GeneratedClientDetectLastPointResponse as AnomalyDetectorClientDetectLastPointResponse, + DetectRequest, + DetectChangePointRequest, + AnomalyDetectorDetectChangePointResponse, + AnomalyDetectorDetectEntireSeriesResponse, + AnomalyDetectorDetectLastPointResponse, DetectLastPointResponse, DetectChangePointResponse, DetectEntireResponse, TimeSeriesPoint, - GeneratedClientTrainMultivariateModelResponse as AnomalyDetectorClientTrainMultivariateModelResponse, - GeneratedClientGetMultivariateModelResponse as AnomalyDetectorClientGetMultivariateModelResponse, - GeneratedClientDetectAnomalyResponse as AnomalyDetectorClientDetectAnomalyResponse, + AnomalyDetectorTrainMultivariateModelResponse, + AnomalyDetectorGetMultivariateModelResponse, + AnomalyDetectorDetectAnomalyResponse, DetectionRequest, DetectionResult, DetectionResultSummary, @@ -120,12 +67,12 @@ export { AnomalyState, AnomalyValue, AnomalyContributor, - GeneratedClientGetDetectionResultResponse as AnomalyDetectorClientGetDetectionResultResponse, - GeneratedClientExportModelResponse as AnomalyDetectorClientExportModelResponse, - GeneratedClientListMultivariateModelOptionalParams as ListMultivariateModelOptionalParams, - GeneratedClientListMultivariateModelNextOptionalParams as ListMultivariateModelNextOptionalParams, - GeneratedClientListMultivariateModelResponse as AnomalyDetectorClientListMultivariateModelResponse, - GeneratedClientListMultivariateModelNextResponse as AnomalyDetectorClientListMultivariateModelNextResponse, + AnomalyDetectorGetDetectionResultResponse, + AnomalyDetectorExportModelResponse, + AnomalyDetectorListMultivariateModelNextOptionalParams, + AnomalyDetectorListMultivariateModelOptionalParams, + AnomalyDetectorListMultivariateModelResponse, + AnomalyDetectorListMultivariateModelNextResponse, Model as AnomalyDetectorClientModel, ModelInfo as AnomalyDetectorClientModelInfo, ModelList as AnomalyDetectorClientModelList, @@ -138,7 +85,8 @@ export { AlignMode, DiagnosticsInfo, FillNAMethod, - GeneratedClientDetectAnomalyHeaders as AnomalyDetectorClientDetectAnomalyHeaders, - GeneratedClientExportModelHeaders as AnomalyDetectorClientExportModelHeaders, - GeneratedClientTrainMultivariateModelHeaders as AnomalyDetectorClientTrainMultivariateModelHeaders + AnomalyDetectorDetectAnomalyHeaders, + AnomalyDetectorExportModelHeaders, + AnomalyDetectorTrainMultivariateModelHeaders, + TimeGranularity } from "./generated/models"; diff --git a/sdk/anomalydetector/ai-anomaly-detector/src/tracing.ts b/sdk/anomalydetector/ai-anomaly-detector/src/tracing.ts deleted file mode 100644 index 2c88a5a12c9b..000000000000 --- a/sdk/anomalydetector/ai-anomaly-detector/src/tracing.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. - -import { createSpanFunction } from "@azure/core-tracing"; - -/** - * Creates a span using the global tracer. - * @internal - */ -export const createSpan = createSpanFunction({ - packagePrefix: "Azure.CognitiveServices.AnomalyDetector", - namespace: "Microsoft.CognitiveServices" -}); diff --git a/sdk/anomalydetector/ai-anomaly-detector/swagger/readme.md b/sdk/anomalydetector/ai-anomaly-detector/swagger/readme.md index 4b4bca33fb87..b2e0cc2eafd0 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/swagger/readme.md +++ b/sdk/anomalydetector/ai-anomaly-detector/swagger/readme.md @@ -7,17 +7,19 @@ ```yaml v3: true package-name: "@azure/ai-form-recognizer" -title: GeneratedClient +title: AnomalyDetector description: AnomalyDetector Client generate-metadata: false license-header: MICROSOFT_MIT_NO_VERSION output-folder: ../ source-code-folder-path: ./src/generated -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cognitiveservices/data-plane/AnomalyDetector/preview/v1.0/AnomalyDetector.json +require: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/cognitiveservices/data-plane/AnomalyDetector/readme.md add-credentials: false -use-extension: - "@autorest/typescript": "6.0.0-dev.20200817.1" -package-version: "3.0.0-preview.1" +package-version: "3.0.0-beta.3" +tracing-info: + namespace: "Microsoft.CognitiveServices" + packagePrefix: "Azure.CognitiveServices.AnomalyDetector" +hide-clients: true ``` ```yaml diff --git a/sdk/anomalydetector/ai-anomaly-detector/test/testData.ts b/sdk/anomalydetector/ai-anomaly-detector/test/testData.ts index 3dee372fee9c..4fe0d6b6566b 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/test/testData.ts +++ b/sdk/anomalydetector/ai-anomaly-detector/test/testData.ts @@ -2,13 +2,14 @@ // Licensed under the MIT license. import { + DetectEntireResponse, TimeGranularity, - DetectRequest, DetectChangePointRequest, - DetectEntireResponse + DetectRequest, + KnownTimeGranularity } from "../src"; -const granularity: TimeGranularity = TimeGranularity.monthly; +const granularity: TimeGranularity = KnownTimeGranularity.monthly; export const testTrendPointseries: DetectChangePointRequest = { series: [ @@ -253,7 +254,7 @@ export const testTrendPointseries: DetectChangePointRequest = { timestamp: new Date("2019-03-01T00:00:00Z") } ], - granularity: TimeGranularity.daily, + granularity: KnownTimeGranularity.daily, customInterval: 1, stableTrendWindow: 5, threshold: 0.9, diff --git a/sdk/anomalydetector/ai-anomaly-detector/tsconfig.json b/sdk/anomalydetector/ai-anomaly-detector/tsconfig.json index a75dd56d9519..fb1129975949 100644 --- a/sdk/anomalydetector/ai-anomaly-detector/tsconfig.json +++ b/sdk/anomalydetector/ai-anomaly-detector/tsconfig.json @@ -2,7 +2,10 @@ "extends": "../../../tsconfig.package", "compilerOptions": { "outDir": "./dist-esm", - "declarationDir": "./types" + "declarationDir": "./types", + "paths": { + "@azure/ai-anomaly-detector": ["./src/index"] + } }, "exclude": [ "node_modules",