Skip to content

Commit

Permalink
[anomaly-detector] Update projects to use snippets (#32472)
Browse files Browse the repository at this point in the history
### Packages impacted by this PR

- @azure-rest/ai-anomaly-detector

### Issues associated with this PR

- #32416

### Describe the problem that is addressed by this PR

Updates snippets for all projects under the `anomalydetector` folder.

### What are the possible designs available to address the problem? If
there are more than one possible design, why was the one in this PR
chosen?


### Are there test cases added in this PR? _(If not, why?)_


### Provide a list of related PRs _(if any)_


### Command used to generate this PR:**_(Applicable only to SDK release
request PRs)_

### Checklists
- [ ] Added impacted package name to the issue description
- [ ] Does this PR needs any fixes in the SDK Generator?** _(If so,
create an Issue in the
[Autorest/typescript](https://github.com/Azure/autorest.typescript)
repository and link it here)_
- [ ] Added a changelog (if necessary)
  • Loading branch information
mpodwysocki authored Jan 9, 2025
1 parent 814b725 commit 8b31480
Show file tree
Hide file tree
Showing 9 changed files with 345 additions and 181 deletions.
230 changes: 127 additions & 103 deletions sdk/anomalydetector/ai-anomaly-detector-rest/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,148 +89,172 @@ The following section provides several code snippets covering some of the most c

### Batch detection

```typescript
```ts snippet:batch_detection
import {
TimeSeriesPoint,
AnomalyDetector,
DetectUnivariateEntireSeriesParameters,
isUnexpected,
} from "@azure-rest/ai-anomaly-detector";
import { parse } from "csv-parse/sync";
import { AzureKeyCredential } from "@azure/core-auth";

const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
const timeSeriesDataPath = "./samples-dev/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 });
const result = Array<TimeSeriesPoint>();
const input = fs.readFileSync(path).toString();
const 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;
}

export async function main() {
// create client
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);

// construct request
const options: DetectUnivariateEntireSeriesParameters = {
body: {
granularity: "daily",
imputeMode: "auto",
maxAnomalyRatio: 0.25,
sensitivity: 95,
series: read_series_from_file(timeSeriesDataPath),
},
headers: { "Content-Type": "application/json" },
};

// get last detect result
const result = await client.path("/timeseries/entire/detect").post(options);
if (isUnexpected(result)) {
throw result;
}

if (result.body.isAnomaly) {
result.body.isAnomaly.forEach(function (anomaly, index) {
if (anomaly === true) {
console.log(index);
}
});
} else {
console.log("There is no anomaly detected from the series.");
}
// create client
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);

// construct request
const options: DetectUnivariateEntireSeriesParameters = {
body: {
granularity: "daily",
imputeMode: "auto",
maxAnomalyRatio: 0.25,
sensitivity: 95,
series: read_series_from_file(timeSeriesDataPath),
},
headers: { "Content-Type": "application/json" },
};

// get last detect result
const result = await client.path("/timeseries/entire/detect").post(options);
if (isUnexpected(result)) {
throw result;
}

if (result.body.isAnomaly) {
result.body.isAnomaly.forEach(function (anomaly, index) {
if (anomaly === true) {
console.log(index);
}
});
} else {
console.log("There is no anomaly detected from the series.");
}
```

### Streaming Detection

```typescript
```ts snippet:streaming_detection
import {
TimeSeriesPoint,
AnomalyDetector,
DetectUnivariateLastPointParameters,
isUnexpected,
} from "@azure-rest/ai-anomaly-detector";
import { parse } from "csv-parse/sync";
import { AzureKeyCredential } from "@azure/core-auth";

const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
const timeSeriesDataPath = "./samples-dev/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 });
const result = Array<TimeSeriesPoint>();
const input = fs.readFileSync(path).toString();
const 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;
}

export async function main() {
// create client
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);

// construct request
const options: DetectUnivariateLastPointParameters = {
body: {
granularity: "daily",
imputeFixedValue: 800,
imputeMode: "fixed",
maxAnomalyRatio: 0.25,
sensitivity: 95,
series: read_series_from_file(timeSeriesDataPath),
},
headers: { "Content-Type": "application/json" },
};

// get last detect result
const result = await client.path("/timeseries/last/detect").post(options);
if (isUnexpected(result)) {
throw result;
}

if (result.body.isAnomaly) {
console.log("The latest point is detected as anomaly.");
} else {
console.log("The latest point is not detected as anomaly.");
}
// create client
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);

// construct request
const options: DetectUnivariateLastPointParameters = {
body: {
granularity: "daily",
imputeFixedValue: 800,
imputeMode: "fixed",
maxAnomalyRatio: 0.25,
sensitivity: 95,
series: read_series_from_file(timeSeriesDataPath),
},
headers: { "Content-Type": "application/json" },
};

// get last detect result
const result = await client.path("/timeseries/last/detect").post(options);
if (isUnexpected(result)) {
throw result;
}

if (result.body.isAnomaly) {
console.log("The latest point is detected as anomaly.");
} else {
console.log("The latest point is not detected as anomaly.");
}
```

### Detect change points

```typescript
```ts snippet:detect_change_points
import {
TimeSeriesPoint,
AnomalyDetector,
DetectUnivariateChangePointParameters,
isUnexpected,
} from "@azure-rest/ai-anomaly-detector";
import { parse } from "csv-parse/sync";
import { AzureKeyCredential } from "@azure/core-auth";

const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
const timeSeriesDataPath = "./samples-dev/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 });
const result = Array<TimeSeriesPoint>();
const input = fs.readFileSync(path).toString();
const 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;
}

export async function main() {
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);
const options: DetectUnivariateChangePointParameters = {
body: {
granularity: "daily",
series: read_series_from_file(timeSeriesDataPath),
},
headers: { "Content-Type": "application/json" },
};
const result = await client.path("/timeseries/changepoint/detect").post(options);
if (isUnexpected(result)) {
throw result;
}

if (result.body.isChangePoint === undefined) throw new Error("Empty isChangePoint");
if (
result.body.isChangePoint.some(function (changePoint) {
return changePoint === true;
})
) {
console.log("Change points were detected from the series at index:");
result.body.isChangePoint.forEach(function (changePoint, index) {
if (changePoint === true) console.log(index);
});
} else {
console.log("There is no change point detected from the series.");
}
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);
const options: DetectUnivariateChangePointParameters = {
body: {
granularity: "daily",
series: read_series_from_file(timeSeriesDataPath),
},
headers: { "Content-Type": "application/json" },
};
const result = await client.path("/timeseries/changepoint/detect").post(options);
if (isUnexpected(result)) {
throw result;
}

if (result.body.isChangePoint === undefined) throw new Error("Empty isChangePoint");
if (
result.body.isChangePoint.some(function (changePoint) {
return changePoint === true;
})
) {
console.log("Change points were detected from the series at index:");
result.body.isChangePoint.forEach(function (changePoint, index) {
if (changePoint === true) console.log(index);
});
} else {
console.log("There is no change point detected from the series.");
}
```

### Multivariate Anomaly Detection Sample
Expand All @@ -245,8 +269,8 @@ To see how to use Anomaly Detector library to conduct Multivariate Anomaly Detec

Enabling logging may help uncover useful information about failures. In order to see a log of HTTP requests and responses, set the `AZURE_LOG_LEVEL` environment variable to `info`. Alternatively, logging can be enabled at runtime by calling `setLogLevel` in the `@azure/logger`:

```javascript
const { setLogLevel } = require("@azure/logger");
```ts snippet:SetLogLevel
import { setLogLevel } from "@azure/logger";

setLogLevel("info");
```
Expand Down
16 changes: 8 additions & 8 deletions sdk/anomalydetector/ai-anomaly-detector-rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,18 @@
"unit-test": "npm run unit-test:node && npm run unit-test:browser",
"unit-test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser",
"unit-test:node": "dev-tool run test:vitest",
"update-snippets": "echo skipped"
"update-snippets": "dev-tool run update-snippets"
},
"sideEffects": false,
"autoPublish": false,
"dependencies": {
"@azure-rest/core-client": "^1.0.0",
"@azure/core-auth": "^1.3.0",
"@azure/core-lro": "^2.2.0",
"@azure/core-paging": "^1.2.0",
"@azure/core-rest-pipeline": "^1.8.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0"
"@azure-rest/core-client": "^2.3.1",
"@azure/core-auth": "^1.9.0",
"@azure/core-lro": "^2.7.2",
"@azure/core-paging": "^1.6.2",
"@azure/core-rest-pipeline": "^1.18.1",
"@azure/logger": "^1.1.4",
"tslib": "^2.8.1"
},
"devDependencies": {
"@azure-tools/test-credential": "^2.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,18 @@
* @summary detects change points.
*/

import AnomalyDetector, {
import type {
DetectUnivariateChangePointParameters,
isUnexpected,
TimeSeriesPoint,
} from "@azure-rest/ai-anomaly-detector";
import AnomalyDetector, { isUnexpected } from "@azure-rest/ai-anomaly-detector";
import { AzureKeyCredential } from "@azure/core-auth";

import { parse } from "csv-parse/sync";
import * as fs from "node:fs";

// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();
import "dotenv/config";

// You will need to set this environment variables or edit the following values

Expand All @@ -28,16 +27,16 @@ const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
const timeSeriesDataPath = "./samples-dev/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 });
const result = Array<TimeSeriesPoint>();
const input = fs.readFileSync(path).toString();
const 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;
}

export async function main() {
export async function main(): Promise<void> {
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);
const options: DetectUnivariateChangePointParameters = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,35 @@
* @summary detects anomaly points on entire series.
*/

import AnomalyDetector, {
import type {
DetectUnivariateEntireSeriesParameters,
isUnexpected,
TimeSeriesPoint,
} from "@azure-rest/ai-anomaly-detector";
import AnomalyDetector, { isUnexpected } from "@azure-rest/ai-anomaly-detector";
import { AzureKeyCredential } from "@azure/core-auth";

import { parse } from "csv-parse/sync";
import * as fs from "node:fs";

// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();
import "dotenv/config";

// You will need to set this environment variables or edit the following values
const apiKey = process.env["ANOMALY_DETECTOR_API_KEY"] || "";
const endpoint = process.env["ANOMALY_DETECTOR_ENDPOINT"] || "";
const timeSeriesDataPath = "./samples-dev/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 });
const result = Array<TimeSeriesPoint>();
const input = fs.readFileSync(path).toString();
const 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;
}

export async function main() {
export async function main(): Promise<void> {
// create client
const credential = new AzureKeyCredential(apiKey);
const client = AnomalyDetector(endpoint, credential);
Expand Down
Loading

0 comments on commit 8b31480

Please sign in to comment.