Skip to content

Commit 1769c1d

Browse files
authored
add .net samples (Azure#14579)
add .net samples
1 parent b800a64 commit 1769c1d

File tree

9 files changed

+526
-0
lines changed

9 files changed

+526
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
page_type: sample
3+
languages:
4+
- csharp
5+
products:
6+
- azure
7+
- azure-cognitive-services
8+
- azure-anomaly-detector
9+
name: Azure Anomaly Detector samples for .NET
10+
description: Samples for the Azure.AI.AnomalyDetector client library
11+
---
12+
13+
# Azure Anomaly Detector client SDK Samples
14+
These code samples show common scenario operations with the Anomaly Detector client library.
15+
16+
|**Sample Name**|**Description**|
17+
|----------------|-------------|
18+
|[Sample1_DetectEntireSeriesAnomaly][sample_detect_entire_series_anomaly] |Detecting anomalies in the entire time series.|
19+
|[Sample2_DetectLastPointAnomaly][sample_detect_last_point_anomaly] |Detecting the anomaly status of the latest data point.|
20+
|[Sample3_DetectChangePoint][sample_detect_change_point] |Detecting change points in the entire time series.|
21+
22+
[sample_detect_entire_series_anomaly]: ./Sample1_DetectEntireSeriesAnomaly.md
23+
[sample_detect_last_point_anomaly]: ./Sample2_DetectLastPointAnomaly.md
24+
[sample_detect_change_point]: ./Sample3_DetectChangePoint.md
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
# Detect Entire Series Anomaly
2+
This sample shows how to detect all the anomalies in the entire time series.
3+
4+
To get started, make sure you have satisfied all the prerequisites and got all the resources required by [README][README].
5+
6+
## Create an AnomalyDetectorClient
7+
8+
To create a new `AnomalyDetectorClient` you need the endpoint and credentials from your resource. In the sample below you'll use an Anomaly Detector API key credential by creating an `AzureKeyCredential` object.
9+
10+
You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.
11+
12+
```C# Snippet:CreateAnomalyDetectorClient
13+
//read endpoint and apiKey
14+
string endpoint = TestEnvironment.Endpoint;
15+
string apiKey = TestEnvironment.ApiKey;
16+
17+
var endpointUri = new Uri(endpoint);
18+
var credential = new AzureKeyCredential(apiKey);
19+
20+
//create client
21+
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);
22+
23+
//read data
24+
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
25+
```
26+
27+
## Load time series and create DetectRequest
28+
29+
You could download our [sample data][SampleData], read in the time series data and add it to a `DetectRequest` object.
30+
31+
Call `File.ReadAllLines` with the file path and create a list of `TimeSeriesPoint` objects, and strip any new line characters. Extract the values and separate the timestamp from its numerical value, and add them to a new `TimeSeriesPoint` object.
32+
33+
Make a `DetectRequest` object with the series of points, and `TimeGranularity.Daily` for the granularity (or periodicity) of the data points.
34+
35+
```C# Snippet:ReadSeriesData
36+
List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
37+
.Where(e => e.Trim().Length != 0)
38+
.Select(e => e.Split(','))
39+
.Where(e => e.Length == 2)
40+
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();
41+
42+
//create request
43+
DetectRequest request = new DetectRequest(list, TimeGranularity.Daily);
44+
```
45+
46+
## Detect anomalies of the entire series
47+
Call the client's `DetectEntireSeriesAsync` method with the `DetectRequest` object and await the response as an `EntireDetectResponse` object. Iterate through the response's `IsAnomaly` values and print any that are true. These values correspond to the index of anomalous data points, if any were found.
48+
49+
```C# Snippet:DetectEntireSeriesAnomaly
50+
//detect
51+
Console.WriteLine("Detecting anomalies in the entire time series.");
52+
53+
EntireDetectResponse result = await client.DetectEntireSeriesAsync(request).ConfigureAwait(false);
54+
55+
if (result.IsAnomaly.Contains(true))
56+
{
57+
Console.WriteLine("An anomaly was detected at index:");
58+
for (int i = 0; i < request.Series.Count; ++i)
59+
{
60+
if (result.IsAnomaly[i])
61+
{
62+
Console.Write(i);
63+
Console.Write(" ");
64+
}
65+
}
66+
Console.WriteLine();
67+
}
68+
else
69+
{
70+
Console.WriteLine(" No anomalies detected in the series.");
71+
}
72+
```
73+
To see the full example source files, see:
74+
75+
* [Detect Entire Series Anomaly](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/Sample1_DetectEntireSeriesAnomaly.cs)
76+
77+
[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/README.md
78+
[SampleData]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/data/request-data.csv
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Detect Last Point Anomaly
2+
This sample shows how to detect the anomaly status of the latest data point.
3+
4+
To get started, make sure you have satisfied all the prerequisites and got all the resources required by [README][README].
5+
6+
## Create an AnomalyDetectorClient
7+
8+
To create a new `AnomalyDetectorClient` you need the endpoint and credentials from your resource. In the sample below you'll use an Anomaly Detector API key credential by creating an `AzureKeyCredential` object.
9+
10+
You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.
11+
12+
```C# Snippet:CreateAnomalyDetectorClient
13+
//read endpoint and apiKey
14+
string endpoint = TestEnvironment.Endpoint;
15+
string apiKey = TestEnvironment.ApiKey;
16+
17+
var endpointUri = new Uri(endpoint);
18+
var credential = new AzureKeyCredential(apiKey);
19+
20+
//create client
21+
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);
22+
23+
//read data
24+
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
25+
```
26+
27+
## Load time series and create DetectRequest
28+
29+
You could download our [sample data][SampleData], read in the time series data and add it to a `DetectRequest` object.
30+
31+
Call `File.ReadAllLines` with the file path and create a list of `TimeSeriesPoint` objects, and strip any new line characters. Extract the values and separate the timestamp from its numerical value, and add them to a new `TimeSeriesPoint` object.
32+
33+
Make a `DetectRequest` object with the series of points, and `TimeGranularity.Daily` for the granularity (or periodicity) of the data points.
34+
35+
```C# Snippet:ReadSeriesData
36+
List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
37+
.Where(e => e.Trim().Length != 0)
38+
.Select(e => e.Split(','))
39+
.Where(e => e.Length == 2)
40+
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();
41+
42+
//create request
43+
DetectRequest request = new DetectRequest(list, TimeGranularity.Daily);
44+
```
45+
46+
## Detect anomaly status of the latest data point
47+
Call the client's `DetectLastPointAsync` method with the `DetectRequest` object and await the response as a `LastDetectResponse` object. Check the response's `IsAnomaly` attribute to determine if the latest data point sent was an anomaly or not.
48+
49+
```C# Snippet:DetectLastPointAnomaly
50+
//detect
51+
Console.WriteLine("Detecting the anomaly status of the latest point in the series.");
52+
53+
LastDetectResponse result = await client.DetectLastPointAsync(request).ConfigureAwait(false);
54+
55+
if (result.IsAnomaly)
56+
{
57+
Console.WriteLine("The latest point was detected as an anomaly.");
58+
}
59+
else
60+
{
61+
Console.WriteLine("The latest point was not detected as an anomaly.");
62+
}
63+
```
64+
To see the full example source files, see:
65+
66+
* [Detect Last Point Anomaly](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/Sample2_DetectLastPointAnomaly.cs)
67+
68+
[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/README.md
69+
[SampleData]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/data/request-data.csv
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Detect Change Point
2+
This sample shows how to detect the change point in time series.
3+
4+
To get started, make sure you have satisfied all the prerequisites and got all the resources required by [README][README].
5+
6+
## Create an AnomalyDetectorClient
7+
8+
To create a new `AnomalyDetectorClient` you need the endpoint and credentials from your resource. In the sample below you'll use an Anomaly Detector API key credential by creating an `AzureKeyCredential` object.
9+
10+
You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.
11+
12+
```C# Snippet:CreateAnomalyDetectorClient
13+
//read endpoint and apiKey
14+
string endpoint = TestEnvironment.Endpoint;
15+
string apiKey = TestEnvironment.ApiKey;
16+
17+
var endpointUri = new Uri(endpoint);
18+
var credential = new AzureKeyCredential(apiKey);
19+
20+
//create client
21+
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);
22+
23+
//read data
24+
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
25+
```
26+
27+
## Load time series and create ChangePointDetectRequest
28+
29+
You could download our [sample data][SampleData], read in the time series data and add it to a `ChangePointDetectRequest` object.
30+
31+
Call `File.ReadAllLines` with the file path and create a list of `TimeSeriesPoint` objects, and strip any new line characters. Extract the values and separate the timestamp from its numerical value, and add them to a new `TimeSeriesPoint` object.
32+
33+
Make a `ChangePointDetectRequest` object with the series of points, and `TimeGranularity.Daily` for the granularity (or periodicity) of the data points.
34+
35+
```C# Snippet:ReadSeriesDataForChangePoint
36+
//read data
37+
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
38+
39+
List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
40+
.Where(e => e.Trim().Length != 0)
41+
.Select(e => e.Split(','))
42+
.Where(e => e.Length == 2)
43+
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();
44+
45+
//create request
46+
ChangePointDetectRequest request = new ChangePointDetectRequest(list, TimeGranularity.Daily);
47+
```
48+
49+
## Detect change point
50+
Call the client's `DetectChangePointAsync` method with the `ChangePointDetectRequest` object and await the response as a `ChangePointDetectResponse` object. Iterate through the response's `IsChangePoint` values and print any that are true. These values correspond to the index of change points, if any were found.
51+
52+
```C# Snippet:DetectChangePoint
53+
//detect
54+
Console.WriteLine("Detecting the change point in the series.");
55+
56+
ChangePointDetectResponse result = await client.DetectChangePointAsync(request).ConfigureAwait(false);
57+
58+
if (result.IsChangePoint.Contains(true))
59+
{
60+
Console.WriteLine("A change point was detected at index:");
61+
for (int i = 0; i < request.Series.Count; ++i)
62+
{
63+
if (result.IsChangePoint[i])
64+
{
65+
Console.Write(i);
66+
Console.Write(" ");
67+
}
68+
}
69+
Console.WriteLine();
70+
}
71+
else
72+
{
73+
Console.WriteLine("No change point detected in the series.");
74+
}
75+
```
76+
To see the full example source files, see:
77+
78+
* [Detect Change Point](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/Sample3_DetectChangePoint.cs)
79+
80+
[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/README.md
81+
[SampleData]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/data/request-data.csv

sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/Azure.AI.AnomalyDetector.Tests.csproj

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,16 @@
1111
<PackageReference Include="Azure.Identity" />
1212
</ItemGroup>
1313

14+
<ItemGroup>
15+
<None Include="samples\data\*" CopyToOutputDirectory="PreserveNewest" />
16+
</ItemGroup>
17+
1418
<ItemGroup>
1519
<ProjectReference Include="$(AzureCoreTestFramework)" />
1620
<ProjectReference Include="..\src\Azure.AI.AnomalyDetector.csproj" />
1721
</ItemGroup>
22+
23+
<ItemGroup>
24+
<Folder Include="samples\data\" />
25+
</ItemGroup>
1826
</Project>
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.IO;
7+
using System.Linq;
8+
using System.Reflection;
9+
using System.Text;
10+
using System.Threading.Tasks;
11+
using Azure.AI.AnomalyDetector.Models;
12+
using Azure.Core.TestFramework;
13+
using NUnit.Framework;
14+
15+
namespace Azure.AI.AnomalyDetector.Tests.Samples
16+
{
17+
public partial class AnomalyDetectorSamples : SamplesBase<AnomalyDetectorTestEnvironment>
18+
{
19+
[Test]
20+
public async Task DetectEntireSeriesAnomaly()
21+
{
22+
#region Snippet:CreateAnomalyDetectorClient
23+
24+
//read endpoint and apiKey
25+
string endpoint = TestEnvironment.Endpoint;
26+
string apiKey = TestEnvironment.ApiKey;
27+
28+
var endpointUri = new Uri(endpoint);
29+
var credential = new AzureKeyCredential(apiKey);
30+
31+
//create client
32+
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);
33+
34+
//read data
35+
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
36+
37+
#endregion
38+
39+
#region Snippet:ReadSeriesData
40+
41+
List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
42+
.Where(e => e.Trim().Length != 0)
43+
.Select(e => e.Split(','))
44+
.Where(e => e.Length == 2)
45+
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();
46+
47+
//create request
48+
DetectRequest request = new DetectRequest(list, TimeGranularity.Daily);
49+
50+
#endregion
51+
52+
#region Snippet:DetectEntireSeriesAnomaly
53+
54+
//detect
55+
Console.WriteLine("Detecting anomalies in the entire time series.");
56+
57+
EntireDetectResponse result = await client.DetectEntireSeriesAsync(request).ConfigureAwait(false);
58+
59+
if (result.IsAnomaly.Contains(true))
60+
{
61+
Console.WriteLine("An anomaly was detected at index:");
62+
for (int i = 0; i < request.Series.Count; ++i)
63+
{
64+
if (result.IsAnomaly[i])
65+
{
66+
Console.Write(i);
67+
Console.Write(" ");
68+
}
69+
}
70+
Console.WriteLine();
71+
}
72+
else
73+
{
74+
Console.WriteLine(" No anomalies detected in the series.");
75+
}
76+
77+
#endregion
78+
}
79+
}
80+
}

0 commit comments

Comments
 (0)