Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add .net samples #14579

Merged
merged 11 commits into from
Sep 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions sdk/anomalydetector/Azure.AI.AnomalyDetector/samples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
page_type: sample
languages:
- csharp
products:
- azure
- azure-cognitive-services
- azure-anomaly-detector
name: Azure Anomaly Detector samples for .NET
description: Samples for the Azure.AI.AnomalyDetector client library
---

# Azure Anomaly Detector client SDK Samples
These code samples show common scenario operations with the Anomaly Detector client library.

|**Sample Name**|**Description**|
|----------------|-------------|
|[Sample1_DetectEntireSeriesAnomaly][sample_detect_entire_series_anomaly] |Detecting anomalies in the entire time series.|
|[Sample2_DetectLastPointAnomaly][sample_detect_last_point_anomaly] |Detecting the anomaly status of the latest data point.|
|[Sample3_DetectChangePoint][sample_detect_change_point] |Detecting change points in the entire time series.|

[sample_detect_entire_series_anomaly]: ./Sample1_DetectEntireSeriesAnomaly.md
[sample_detect_last_point_anomaly]: ./Sample2_DetectLastPointAnomaly.md
[sample_detect_change_point]: ./Sample3_DetectChangePoint.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Detect Entire Series Anomaly
This sample shows how to detect all the anomalies in the entire time series.

To get started, make sure you have satisfied all the prerequisites and got all the resources required by [README][README].

## Create an AnomalyDetectorClient

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.

You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.

```C# Snippet:CreateAnomalyDetectorClient
ShivangiReja marked this conversation as resolved.
Show resolved Hide resolved
//read endpoint and apiKey
string endpoint = TestEnvironment.Endpoint;
string apiKey = TestEnvironment.ApiKey;

var endpointUri = new Uri(endpoint);
var credential = new AzureKeyCredential(apiKey);

//create client
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);

//read data
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
```

## Load time series and create DetectRequest

You could download our [sample data][SampleData], read in the time series data and add it to a `DetectRequest` object.

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.

Make a `DetectRequest` object with the series of points, and `TimeGranularity.Daily` for the granularity (or periodicity) of the data points.

```C# Snippet:ReadSeriesData
List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
.Where(e => e.Trim().Length != 0)
.Select(e => e.Split(','))
.Where(e => e.Length == 2)
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();

//create request
DetectRequest request = new DetectRequest(list, TimeGranularity.Daily);
```

## Detect anomalies of the entire series
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.

```C# Snippet:DetectEntireSeriesAnomaly
//detect
Console.WriteLine("Detecting anomalies in the entire time series.");

EntireDetectResponse result = await client.DetectEntireSeriesAsync(request).ConfigureAwait(false);

if (result.IsAnomaly.Contains(true))
{
Console.WriteLine("An anomaly was detected at index:");
for (int i = 0; i < request.Series.Count; ++i)
{
if (result.IsAnomaly[i])
{
Console.Write(i);
Console.Write(" ");
}
}
Console.WriteLine();
}
else
{
Console.WriteLine(" No anomalies detected in the series.");
}
```
To see the full example source files, see:

* [Detect Entire Series Anomaly](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/Sample1_DetectEntireSeriesAnomaly.cs)

[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/README.md
[SampleData]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/data/request-data.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Detect Last Point Anomaly
This sample shows how to detect the anomaly status of the latest data point.

To get started, make sure you have satisfied all the prerequisites and got all the resources required by [README][README].

## Create an AnomalyDetectorClient

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.

You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.

```C# Snippet:CreateAnomalyDetectorClient
//read endpoint and apiKey
string endpoint = TestEnvironment.Endpoint;
string apiKey = TestEnvironment.ApiKey;

var endpointUri = new Uri(endpoint);
var credential = new AzureKeyCredential(apiKey);

//create client
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);

//read data
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
```

## Load time series and create DetectRequest

You could download our [sample data][SampleData], read in the time series data and add it to a `DetectRequest` object.

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.

Make a `DetectRequest` object with the series of points, and `TimeGranularity.Daily` for the granularity (or periodicity) of the data points.

```C# Snippet:ReadSeriesData
List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
.Where(e => e.Trim().Length != 0)
.Select(e => e.Split(','))
.Where(e => e.Length == 2)
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();

//create request
DetectRequest request = new DetectRequest(list, TimeGranularity.Daily);
```

## Detect anomaly status of the latest data point
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.

```C# Snippet:DetectLastPointAnomaly
//detect
Console.WriteLine("Detecting the anomaly status of the latest point in the series.");

LastDetectResponse result = await client.DetectLastPointAsync(request).ConfigureAwait(false);

if (result.IsAnomaly)
{
Console.WriteLine("The latest point was detected as an anomaly.");
}
else
{
Console.WriteLine("The latest point was not detected as an anomaly.");
}
```
To see the full example source files, see:

* [Detect Last Point Anomaly](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/Sample2_DetectLastPointAnomaly.cs)

[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/README.md
[SampleData]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/data/request-data.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Detect Change Point
This sample shows how to detect the change point in time series.

To get started, make sure you have satisfied all the prerequisites and got all the resources required by [README][README].

## Create an AnomalyDetectorClient

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.

You can set `endpoint` and `apiKey` based on an environment variable, a configuration setting, or any way that works for your application.

```C# Snippet:CreateAnomalyDetectorClient
//read endpoint and apiKey
string endpoint = TestEnvironment.Endpoint;
string apiKey = TestEnvironment.ApiKey;

var endpointUri = new Uri(endpoint);
var credential = new AzureKeyCredential(apiKey);

//create client
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);

//read data
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");
```

## Load time series and create ChangePointDetectRequest

You could download our [sample data][SampleData], read in the time series data and add it to a `ChangePointDetectRequest` object.

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.

Make a `ChangePointDetectRequest` object with the series of points, and `TimeGranularity.Daily` for the granularity (or periodicity) of the data points.

```C# Snippet:ReadSeriesDataForChangePoint
//read data
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");

List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
.Where(e => e.Trim().Length != 0)
.Select(e => e.Split(','))
.Where(e => e.Length == 2)
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();

//create request
ChangePointDetectRequest request = new ChangePointDetectRequest(list, TimeGranularity.Daily);
```

## Detect change point
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.

```C# Snippet:DetectChangePoint
//detect
Console.WriteLine("Detecting the change point in the series.");

ChangePointDetectResponse result = await client.DetectChangePointAsync(request).ConfigureAwait(false);

if (result.IsChangePoint.Contains(true))
{
Console.WriteLine("A change point was detected at index:");
for (int i = 0; i < request.Series.Count; ++i)
{
if (result.IsChangePoint[i])
{
Console.Write(i);
Console.Write(" ");
}
}
Console.WriteLine();
}
else
{
Console.WriteLine("No change point detected in the series.");
}
```
To see the full example source files, see:

* [Detect Change Point](https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/Sample3_DetectChangePoint.cs)

[README]: https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/README.md
[SampleData]: https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/anomalydetector/Azure.AI.AnomalyDetector/tests/samples/data/request-data.csv
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,16 @@
<PackageReference Include="Azure.Identity" />
</ItemGroup>

<ItemGroup>
<None Include="samples\data\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="$(AzureCoreTestFramework)" />
<ProjectReference Include="..\src\Azure.AI.AnomalyDetector.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="samples\data\" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Azure.AI.AnomalyDetector.Models;
using Azure.Core.TestFramework;
using NUnit.Framework;

namespace Azure.AI.AnomalyDetector.Tests.Samples
{
public partial class AnomalyDetectorSamples : SamplesBase<AnomalyDetectorTestEnvironment>
{
[Test]
public async Task DetectEntireSeriesAnomaly()
{
#region Snippet:CreateAnomalyDetectorClient

//read endpoint and apiKey
string endpoint = TestEnvironment.Endpoint;
string apiKey = TestEnvironment.ApiKey;

var endpointUri = new Uri(endpoint);
var credential = new AzureKeyCredential(apiKey);

//create client
AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential);

//read data
string datapath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "samples", "data", "request-data.csv");

#endregion

#region Snippet:ReadSeriesData

List<TimeSeriesPoint> list = File.ReadAllLines(datapath, Encoding.UTF8)
.Where(e => e.Trim().Length != 0)
.Select(e => e.Split(','))
.Where(e => e.Length == 2)
.Select(e => new TimeSeriesPoint(DateTime.Parse(e[0]), float.Parse(e[1]))).ToList();

//create request
DetectRequest request = new DetectRequest(list, TimeGranularity.Daily);

#endregion

#region Snippet:DetectEntireSeriesAnomaly

//detect
Console.WriteLine("Detecting anomalies in the entire time series.");

EntireDetectResponse result = await client.DetectEntireSeriesAsync(request).ConfigureAwait(false);

if (result.IsAnomaly.Contains(true))
{
Console.WriteLine("An anomaly was detected at index:");
for (int i = 0; i < request.Series.Count; ++i)
{
if (result.IsAnomaly[i])
{
Console.Write(i);
Console.Write(" ");
}
}
Console.WriteLine();
}
else
{
Console.WriteLine(" No anomalies detected in the series.");
}

#endregion
}
}
}
Loading