public async Task DetectLastPointAnomaly() { //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"); 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(float.Parse(e[1])) { Timestamp = DateTime.Parse(e[0]) }).ToList(); //create request DetectRequest request = new DetectRequest(list) { Granularity = TimeGranularity.Daily }; #region Snippet:DetectLastPointAnomaly //detect Console.WriteLine("Detecting the anomaly status of the latest point in the series."); try { 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."); } } catch (RequestFailedException ex) { Console.WriteLine(String.Format("Last detection failed: {0}", ex.Message)); throw; } catch (Exception ex) { Console.WriteLine(String.Format("Detection error. {0}", ex.Message)); throw; } #endregion }
public static async Task RunAsync(string endpoint, string key) { Console.WriteLine("Sample of detecting anomalies in the entire series."); IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; // Detection Request request = Program.GetRequest(); request.MaxAnomalyRatio = 0.25; request.Sensitivity = 95; EntireDetectResponse result = await client.EntireDetectAsync(request).ConfigureAwait(false); if (result.IsAnomaly.Contains(true)) { Console.WriteLine("Anomaly was detected from the series 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("There is no anomaly detected from the series."); } }
public static async Task RunAsync(string endpoint, string key) { Console.WriteLine("Sample of detecting whether the latest point in series is anomaly."); IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; // Detection Request request = Program.GetRequest(); request.MaxAnomalyRatio = 0.25; request.Sensitivity = 95; LastDetectResponse result = await client.LastDetectAsync(request).ConfigureAwait(false); if (result.IsAnomaly) { Console.WriteLine("The latest point is detected as anomaly."); } else { Console.WriteLine("The latest point is not detected as anomaly."); } }
public async Task MultivariateDetect() { //read endpoint and apiKey string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; string datasource = TestEnvironment.DataSource; Console.WriteLine(endpoint); var endpointUri = new Uri(endpoint); var credential = new AzureKeyCredential(apiKey); //create client AnomalyDetectorClient client = new AnomalyDetectorClient(endpointUri, credential); // train TimeSpan offset = new TimeSpan(0); DateTimeOffset start_time = new DateTimeOffset(2021, 1, 1, 0, 0, 0, offset); DateTimeOffset end_time = new DateTimeOffset(2021, 1, 2, 12, 0, 0, offset); Guid? model_id_raw = null; try { model_id_raw = await TrainAsync(client, datasource, start_time, end_time).ConfigureAwait(false); Console.WriteLine(model_id_raw); Guid model_id = model_id_raw.GetValueOrDefault(); // detect start_time = end_time; end_time = new DateTimeOffset(2021, 1, 3, 0, 0, 0, offset); DetectionResult result = await DetectAsync(client, datasource, model_id, start_time, end_time).ConfigureAwait(false); if (result != null) { Console.WriteLine(String.Format("Result ID: {0}", result.ResultId)); Console.WriteLine(String.Format("Result summary: {0}", result.Summary)); Console.WriteLine(String.Format("Result length: {0}", result.Results.Count)); } //detect last await DetectLastAsync(client, model_id).ConfigureAwait(false); // export model await ExportAsync(client, model_id).ConfigureAwait(false); // delete await DeleteAsync(client, model_id).ConfigureAwait(false); } catch (Exception e) { String msg = String.Format("Multivariate error. {0}", e.Message); if (model_id_raw != null) { await DeleteAsync(client, model_id_raw.GetValueOrDefault()).ConfigureAwait(false); } Console.WriteLine(msg); throw; } }
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 }
private async Task deleteAsync(AnomalyDetectorClient client, Guid model_id) { await client.DeleteMultivariateModelAsync(model_id).ConfigureAwait(false); int model_number = await getModelNumberAsync(client).ConfigureAwait(false); Console.WriteLine(String.Format("{0} available models after deletion.", model_number)); }
static IAnomalyDetectorClient createClient(string endpoint, string key) { IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; return(client); }
protected IAnomalyDetectorClient GetAnomalyDetectorClient(DelegatingHandler handler) { IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(AnomalyDetectorSubscriptionKey), handlers: handler) { Endpoint = "https://westus2.api.cognitive.microsoft.com" }; return(client); }
private async Task <Guid?> TrainAsync(AnomalyDetectorClient client, string datasource, DateTimeOffset start_time, DateTimeOffset end_time, int max_tryout = 500) { try { Console.WriteLine("Training new model..."); int model_number = await GetModelNumberAsync(client, false).ConfigureAwait(false); Console.WriteLine(String.Format("{0} available models before training.", model_number)); ModelInfo data_feed = new ModelInfo(datasource, start_time, end_time); Response response_header = client.TrainMultivariateModel(data_feed); response_header.Headers.TryGetValue("Location", out string trained_model_id_path); Guid trained_model_id = Guid.Parse(trained_model_id_path.Split('/').LastOrDefault()); Console.WriteLine(trained_model_id); // Wait until the model is ready. It usually takes several minutes Response <Model> get_response = await client.GetMultivariateModelAsync(trained_model_id).ConfigureAwait(false); ModelStatus?model_status = null; int tryout_count = 0; while (tryout_count < max_tryout & model_status != ModelStatus.Ready) { System.Threading.Thread.Sleep(10000); get_response = await client.GetMultivariateModelAsync(trained_model_id).ConfigureAwait(false); ModelInfo model_info = get_response.Value.ModelInfo; Console.WriteLine(String.Format("model_id: {0}, createdTime: {1}, lastUpdateTime: {2}, status: {3}.", get_response.Value.ModelId, get_response.Value.CreatedTime, get_response.Value.LastUpdatedTime, model_info.Status)); if (model_info != null) { model_status = model_info.Status; } tryout_count += 1; } ; get_response = await client.GetMultivariateModelAsync(trained_model_id).ConfigureAwait(false); if (model_status != ModelStatus.Ready) { Console.WriteLine(String.Format("Request timeout after {0} tryouts", max_tryout)); } model_number = await GetModelNumberAsync(client).ConfigureAwait(false); Console.WriteLine(String.Format("{0} available models after training.", model_number)); return(trained_model_id); } catch (Exception e) { Console.WriteLine(String.Format("Train error. {0}", e.Message)); throw; } }
static IAnomalyDetectorClient createClient() { string endpoint = GetEnvironmentVariable("AnormalDetecEndpoint"); string key = GetEnvironmentVariable("AnormalDetecKey"); IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; return(client); }
public static async Task RunAsync(string endpoint, string key) { Console.WriteLine("Sample of detecting whether the latest point in series is anomaly."); IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; // Create time series var series = new List <Point> { new Point(DateTime.Parse("1962-01-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-02-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-03-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-04-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-05-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-06-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-07-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-08-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-09-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-10-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-11-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-12-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-01-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-02-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-03-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-04-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-05-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-06-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-07-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-08-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-09-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-10-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-11-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-12-01T00:00:00Z"), 0) }; // Detection Request request = new Request(series, Granularity.Monthly); request.MaxAnomalyRatio = 0.25; request.Sensitivity = 95; LastDetectResponse result = await client.LastDetectAsync(request).ConfigureAwait(false); if (result.IsAnomaly) { Console.WriteLine("The latest point is detected as anomaly."); } else { Console.WriteLine("The latest point is not detected as anomaly."); } }
private async Task <Guid?> trainAsync(AnomalyDetectorClient client, string datasource, DateTimeOffset start_time, DateTimeOffset end_time) { try { Console.WriteLine("Training new model..."); int model_number = await getModelNumberAsync(client, false).ConfigureAwait(false); Console.WriteLine(String.Format("{0} available models before training.", model_number)); ModelInfo data_feed = new ModelInfo(datasource, start_time, end_time); Response response_header = client.TrainMultivariateModel(data_feed); response_header.Headers.TryGetValue("Location", out string trained_model_id_path); Guid trained_model_id = Guid.Parse(trained_model_id_path.Split('/').LastOrDefault()); Console.WriteLine(trained_model_id); // Wait until the model is ready. It usually takes several minutes Response <Model> get_response = await client.GetMultivariateModelAsync(trained_model_id).ConfigureAwait(false); while (get_response.Value.ModelInfo.Status != ModelStatus.Ready & get_response.Value.ModelInfo.Status != ModelStatus.Failed) { System.Threading.Thread.Sleep(10000); get_response = await client.GetMultivariateModelAsync(trained_model_id).ConfigureAwait(false); Console.WriteLine(String.Format("model_id: {0}, createdTime: {1}, lastUpdateTime: {2}, status: {3}.", get_response.Value.ModelId, get_response.Value.CreatedTime, get_response.Value.LastUpdatedTime, get_response.Value.ModelInfo.Status)); } if (get_response.Value.ModelInfo.Status != ModelStatus.Ready) { Console.WriteLine(String.Format("Trainig failed.")); IReadOnlyList <ErrorResponse> errors = get_response.Value.ModelInfo.Errors; foreach (ErrorResponse error in errors) { Console.WriteLine(String.Format("Error code: {0}.", error.Code)); Console.WriteLine(String.Format("Error message: {0}.", error.Message)); } throw new Exception("Training failed."); } model_number = await getModelNumberAsync(client).ConfigureAwait(false); Console.WriteLine(String.Format("{0} available models after training.", model_number)); return(trained_model_id); } catch (Exception e) { Console.WriteLine(String.Format("Train error. {0}", e.Message)); throw new Exception(e.Message); } }
private async Task <int> getModelNumberAsync(AnomalyDetectorClient client, bool delete = false) { int count = 0; AsyncPageable <ModelSnapshot> model_list = client.ListMultivariateModelAsync(0, 10000); await foreach (ModelSnapshot x in model_list) { count += 1; Console.WriteLine(String.Format("model_id: {0}, createdTime: {1}, lastUpdateTime: {2}.", x.ModelId, x.CreatedTime, x.LastUpdatedTime)); if (delete & count < 4) { await client.DeleteMultivariateModelAsync(x.ModelId).ConfigureAwait(false); } } return(count); }
/// <summary> /// Creates a <see cref="AnomalyDetectorClient" /> with the endpoint and API key provided via environment /// variables and instruments it to make use of the Azure Core Test Framework functionalities. /// </summary> /// <param name="useTokenCredential">Whether or not to use a <see cref="TokenCredential"/> to authenticate. An <see cref="AzureKeyCredential"/> is used by default.</param> /// <param name="apiKey">The API key to use for authentication. Defaults to <see cref="AnomalyDetectorTestEnvironment.ApiKey"/>.</param> /// <param name="skipInstrumenting">Whether or not instrumenting should be skipped. Avoid skipping it as much as possible.</param> /// <returns>The instrumented <see cref="AnomalyDetectorClient" />.</returns> protected AnomalyDetectorClient CreateAnomalyDetectorClient(bool useTokenCredential = false, string apiKey = default, bool skipInstrumenting = false) { var endpoint = new Uri(TestEnvironment.Endpoint); var options = InstrumentClientOptions(new AnomalyDetectorClientOptions()); AnomalyDetectorClient client; if (useTokenCredential) { client = new AnomalyDetectorClient(endpoint, TestEnvironment.Credential, options: options); } else { var credential = new AzureKeyCredential(apiKey ?? TestEnvironment.ApiKey); client = new AnomalyDetectorClient(endpoint, credential, options: options); } return(skipInstrumenting ? client : InstrumentClient(client)); }
static async Task LastDetectSampleAsync(string endpoint, string key, Request request) { Console.WriteLine("Sample of detecting whether the latest point in series is anomaly."); IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; LastDetectResponse result = await client.LastDetectAsync(request).ConfigureAwait(false); if (result.IsAnomaly) { Console.WriteLine("The latest point is detected as anomaly."); } else { Console.WriteLine("The latest point is not detected as anomaly."); } }
private async Task exportAsync(AnomalyDetectorClient client, Guid model_id, string model_path = "model.zip") { try { Stream model = await client.ExportModelAsync(model_id).ConfigureAwait(false); if (model != null) { var fileStream = File.Create(model_path); model.Seek(0, SeekOrigin.Begin); model.CopyTo(fileStream); fileStream.Close(); } } catch (Exception e) { Console.WriteLine(String.Format("Export error. {0}", e.Message)); throw new Exception(e.Message); } }
private async Task <DetectionResult> detectAsync(AnomalyDetectorClient client, string datasource, Guid model_id, DateTimeOffset start_time, DateTimeOffset end_time) { try { Console.WriteLine("Start detect..."); Response <Model> get_response = await client.GetMultivariateModelAsync(model_id).ConfigureAwait(false); DetectionRequest detectionRequest = new DetectionRequest(datasource, start_time, end_time); Response result_response = await client.DetectAnomalyAsync(model_id, detectionRequest).ConfigureAwait(false); var ok = result_response.Headers.TryGetValue("Location", out string result_id_path); Guid result_id = Guid.Parse(result_id_path.Split('/').LastOrDefault()); // get detection result Response <DetectionResult> result = await client.GetDetectionResultAsync(result_id).ConfigureAwait(false); while (result.Value.Summary.Status != DetectionStatus.Ready & result.Value.Summary.Status != DetectionStatus.Failed) { System.Threading.Thread.Sleep(2000); result = await client.GetDetectionResultAsync(result_id).ConfigureAwait(false); } if (result.Value.Summary.Status != DetectionStatus.Ready) { Console.WriteLine(String.Format("Inference failed.")); IReadOnlyList <ErrorResponse> errors = result.Value.Summary.Errors; foreach (ErrorResponse error in errors) { Console.WriteLine(String.Format("Error code: {0}.", error.Code)); Console.WriteLine(String.Format("Error message: {0}.", error.Message)); } return(null); } return(result.Value); } catch (Exception e) { Console.WriteLine(String.Format("Detection error. {0}", e.Message)); throw new Exception(e.Message); } }
private async Task <DetectionResult> DetectAsync(AnomalyDetectorClient client, string datasource, Guid model_id, DateTimeOffset start_time, DateTimeOffset end_time, int max_tryout = 500) { try { Console.WriteLine("Start detect..."); Response <Model> get_response = await client.GetMultivariateModelAsync(model_id).ConfigureAwait(false); DetectionRequest detectionRequest = new DetectionRequest(datasource, start_time, end_time); Response result_response = await client.DetectAnomalyAsync(model_id, detectionRequest).ConfigureAwait(false); var ok = result_response.Headers.TryGetValue("Location", out string result_id_path); Guid result_id = Guid.Parse(result_id_path.Split('/').LastOrDefault()); // get detection result Response <DetectionResult> result = await client.GetDetectionResultAsync(result_id).ConfigureAwait(false); int tryout_count = 0; while (result.Value.Summary.Status != DetectionStatus.Ready & tryout_count < max_tryout) { System.Threading.Thread.Sleep(2000); result = await client.GetDetectionResultAsync(result_id).ConfigureAwait(false); tryout_count += 1; } if (result.Value.Summary.Status != DetectionStatus.Ready) { Console.WriteLine(String.Format("Request timeout after {0} tryouts", max_tryout)); return(null); } return(result.Value); } catch (Exception e) { Console.WriteLine(String.Format("Detection error. {0}", e.Message)); throw; } }
private async Task <LastDetectionResult> DetectLastAsync(AnomalyDetectorClient client, Guid model_id) { Console.WriteLine("Start detect..."); List <VariableValues> variables = new List <VariableValues>(); variables.Add(new VariableValues("variables_name1", new[] { "2021-01-01 00:00:00", "2021-01-01 01:00:00", "2021-01-01 02:00:00" }, new[] { 0.0f, 0.0f, 0.0f })); variables.Add(new VariableValues("variables_name2", new[] { "2021-01-01 00:00:00", "2021-01-01 01:00:00", "2021-01-01 02:00:00" }, new[] { 0.0f, 0.0f, 0.0f })); LastDetectionRequest lastDetectionRequest = new LastDetectionRequest(variables, 1); try { Response <LastDetectionResult> response = await client.LastDetectAnomalyAsync(model_id, lastDetectionRequest).ConfigureAwait(false); if (response.GetRawResponse().Status == 200) { foreach (AnomalyState state in response.Value.Results) { Console.WriteLine(String.Format("timestamp: {}, isAnomaly: {}, score: {}.", state.Timestamp, state.Value.IsAnomaly, state.Value.Score)); } } return(response); } catch (RequestFailedException ex) { Console.WriteLine(String.Format("Last detection failed: {0}", ex.Message)); throw; } catch (Exception ex) { Console.WriteLine(String.Format("Detection error. {0}", ex.Message)); throw; } }
static void Main(string[] args) { DotEnv.AutoConfig(); AnomalyDetectorClient client = new AnomalyDetectorClient( new Uri(Environment.GetEnvironmentVariable("ANOMALY_DECTECTOR_API_ENDPOINT")), new AzureKeyCredential(Environment.GetEnvironmentVariable("ANOMALY_DECTECTOR_API_KEY"))); // ref: https://westus2.dev.cognitive.microsoft.com/docs/services/AnomalyDetector/operations/post-timeseries-entire-detect, the request here matches the sample. DynamicResponse res = client.DetectEntireSeriesAsync(new { series = new[] { new { timestamp = "1972-01-01T00:00:00Z", value = 826 }, new { timestamp = "1972-02-01T00:00:00Z", value = 799 }, new { timestamp = "1972-03-01T00:00:00Z", value = 890 }, new { timestamp = "1972-04-01T00:00:00Z", value = 900 }, new { timestamp = "1972-05-01T00:00:00Z", value = 961 }, new { timestamp = "1972-06-01T00:00:00Z", value = 935 }, new { timestamp = "1972-07-01T00:00:00Z", value = 894 }, new { timestamp = "1972-08-01T00:00:00Z", value = 855 }, new { timestamp = "1972-09-01T00:00:00Z", value = 809 }, new { timestamp = "1972-10-01T00:00:00Z", value = 810 }, new { timestamp = "1972-11-01T00:00:00Z", value = 766 }, new { timestamp = "1972-12-01T00:00:00Z", value = 805 }, new { timestamp = "1973-01-01T00:00:00Z", value = 821 }, new { timestamp = "1973-02-01T00:00:00Z", value = 773 }, new { timestamp = "1973-03-01T00:00:00Z", value = 883 }, new { timestamp = "1973-04-01T00:00:00Z", value = 898 }, new { timestamp = "1973-05-01T00:00:00Z", value = 957 }, new { timestamp = "1973-06-01T00:00:00Z", value = 924 }, new { timestamp = "1973-07-01T00:00:00Z", value = 881 }, new { timestamp = "1973-08-01T00:00:00Z", value = 837 }, new { timestamp = "1973-09-01T00:00:00Z", value = 784 }, new { timestamp = "1973-10-01T00:00:00Z", value = 791 }, new { timestamp = "1973-11-01T00:00:00Z", value = 760 }, new { timestamp = "1973-12-01T00:00:00Z", value = 802 }, new { timestamp = "1974-01-01T00:00:00Z", value = 828 }, new { timestamp = "1974-02-01T00:00:00Z", value = 1030 }, new { timestamp = "1974-03-01T00:00:00Z", value = 889 }, new { timestamp = "1974-04-01T00:00:00Z", value = 902 }, new { timestamp = "1974-05-01T00:00:00Z", value = 969 }, new { timestamp = "1974-06-01T00:00:00Z", value = 947 }, new { timestamp = "1974-07-01T00:00:00Z", value = 908 }, new { timestamp = "1974-08-01T00:00:00Z", value = 867 }, new { timestamp = "1974-09-01T00:00:00Z", value = 815 }, new { timestamp = "1974-10-01T00:00:00Z", value = 812 }, new { timestamp = "1974-11-01T00:00:00Z", value = 773 }, new { timestamp = "1974-12-01T00:00:00Z", value = 813 }, new { timestamp = "1975-01-01T00:00:00Z", value = 834 }, new { timestamp = "1975-02-01T00:00:00Z", value = 782 }, new { timestamp = "1975-03-01T00:00:00Z", value = 892 }, new { timestamp = "1975-04-01T00:00:00Z", value = 903 }, new { timestamp = "1975-05-01T00:00:00Z", value = 966 }, new { timestamp = "1975-06-01T00:00:00Z", value = 937 }, new { timestamp = "1975-07-01T00:00:00Z", value = 896 }, new { timestamp = "1975-08-01T00:00:00Z", value = 858 }, new { timestamp = "1975-09-01T00:00:00Z", value = 817 }, new { timestamp = "1975-10-01T00:00:00Z", value = 827 }, new { timestamp = "1975-11-01T00:00:00Z", value = 797 }, new { timestamp = "1975-12-01T00:00:00Z", value = 843 } }, granularity = "monthly", maxAnomalyRatio = 0.25, sensitivity = 95, }).GetAwaiter().GetResult(); // TODO(matell): This is kinda tedious, I think we need to be able to make this cleaner. if (res.GetRawResponse().Status == 200) { foreach (bool isAnomaly in res.Content.isAnomaly) { Console.WriteLine(isAnomaly); } } else if (res.GetRawResponse().Status == 400) { Console.WriteLine($"Bad request code: {res.Content.code}, message: {res.Content.message}"); } }
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); #endregion #region Snippet:ReadSeriesData //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(float.Parse(e[1])) { Timestamp = DateTime.Parse(e[0]) }).ToList(); //create request DetectRequest request = new DetectRequest(list) { Granularity = TimeGranularity.Daily }; #endregion #region Snippet:DetectEntireSeriesAnomaly //detect Console.WriteLine("Detecting anomalies in the entire time series."); try { EntireDetectResponse result = await client.DetectEntireSeriesAsync(request).ConfigureAwait(false); bool hasAnomaly = false; for (int i = 0; i < request.Series.Count; ++i) { if (result.IsAnomaly[i]) { Console.WriteLine("An anomaly was detected at index: {0}.", i); hasAnomaly = true; } } if (!hasAnomaly) { Console.WriteLine("No anomalies detected in the series."); } } catch (RequestFailedException ex) { Console.WriteLine(String.Format("Entire detection failed: {0}", ex.Message)); throw; } catch (Exception ex) { Console.WriteLine(String.Format("Detection error. {0}", ex.Message)); throw; } #endregion }
public static async Task RunAsync(string endpoint, string key) { Console.WriteLine("Sample of detecting anomalies in the entire series."); IAnomalyDetectorClient client = new AnomalyDetectorClient(new ApiKeyServiceClientCredentials(key)) { Endpoint = endpoint }; // Create time series var series = new List <Point> { new Point(DateTime.Parse("1962-01-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-02-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-03-01T00:00:00Z"), 0), new Point(DateTime.Parse("1962-04-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-05-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-06-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-07-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-08-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-09-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-10-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-11-01T00:00:00Z"), 1), new Point(DateTime.Parse("1962-12-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-01-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-02-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-03-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-04-01T00:00:00Z"), 0), new Point(DateTime.Parse("1963-05-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-06-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-07-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-08-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-09-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-10-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-11-01T00:00:00Z"), 1), new Point(DateTime.Parse("1963-12-01T00:00:00Z"), 1) }; // Detection Request request = new Request(series, Granularity.Monthly); request.MaxAnomalyRatio = 0.25; request.Sensitivity = 95; EntireDetectResponse result = await client.EntireDetectAsync(request).ConfigureAwait(false); if (result.IsAnomaly.Contains(true)) { Console.WriteLine("Anomaly was detected from the series at index:"); for (int i = 0; i < series.Count; ++i) { if (result.IsAnomaly[i]) { Console.Write(i); Console.Write(" "); } } Console.WriteLine(); } else { Console.WriteLine("There is no anomaly detected from the series."); } }