Skip to content

Commit

Permalink
[Sample] Typescript samples for ai-anomaly-detector (Azure#10979)
Browse files Browse the repository at this point in the history
* update ts sample for ai-anomaly-detector

* update package.json

* remove unsued imports

* fix broken link

* fix broken links

Co-authored-by: [email protected] <[email protected]>
  • Loading branch information
guinao and [email protected] authored Sep 9, 2020
1 parent d670bde commit 734954a
Show file tree
Hide file tree
Showing 7 changed files with 344 additions and 112 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
---
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
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@
"homepage": "https://github.com/Azure/azure-sdk-for-js/tree/master/sdk/anomalydetector/ai-anomaly-detector",
"sideEffects": false,
"dependencies": {
"@azure/ai-anomaly-detector": "../..",
"@azure/identity": "latest",
"@azure/ai-anomaly-detector": "latest",
"csv-parse": "^4.4.0",
"dotenv": "^8.2.0"
},
"devDependencies": {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

/**
* Demonstrates how to detect change points on entire series.
*/

import {
AnomalyDetectorClient,
DetectChangePointRequest,
DetectChangePointResponse,
TimeSeriesPoint,
TimeGranularity
} 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<TimeSeriesPoint> {
let result = Array<TimeSeriesPoint>();
let input = fs.readFileSync(path).toString();
let parsed = parse(input, { skip_empty_lines: true });
parsed.forEach(function(e: Array<string>) {
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
});
return result;
}

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: TimeGranularity.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);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

/**
* Demonstrates how to detect anomaly points on entire series.
*/

import {
AnomalyDetectorClient,
DetectRequest,
DetectEntireResponse,
TimeSeriesPoint,
TimeGranularity
} 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<TimeSeriesPoint> {
let result = Array<TimeSeriesPoint>();
let input = fs.readFileSync(path).toString();
let parsed = parse(input, { skip_empty_lines: true });
parsed.forEach(function(e: Array<string>) {
result.push({ timestamp: new Date(e[0]), value: Number(e[1]) });
});
return result;
}

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: TimeGranularity.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);
});
Loading

0 comments on commit 734954a

Please sign in to comment.