Skip to content

Commit effcf48

Browse files
multi-AD sample (Azure#20807)
* multi-AD sample * rename placeholder
1 parent 2f82ab1 commit effcf48

File tree

1 file changed

+189
-0
lines changed

1 file changed

+189
-0
lines changed
Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
package com.azure.ai.anomalydetector;
5+
6+
import com.azure.ai.anomalydetector.models.*;
7+
import com.azure.core.credential.AzureKeyCredential;
8+
import com.azure.core.http.*;
9+
import com.azure.core.http.policy.*;
10+
import com.azure.core.http.rest.PagedIterable;
11+
import com.azure.core.http.rest.PagedResponse;
12+
import com.azure.core.http.rest.Response;
13+
import com.azure.core.http.rest.StreamResponse;
14+
import com.azure.core.util.Context;
15+
import reactor.core.publisher.Flux;
16+
17+
import java.io.FileNotFoundException;
18+
import java.io.FileOutputStream;
19+
import java.io.IOException;
20+
import java.io.UncheckedIOException;
21+
import java.nio.ByteBuffer;
22+
import java.nio.file.Files;
23+
import java.nio.file.Path;
24+
import java.nio.file.Paths;
25+
import java.time.*;
26+
import java.time.format.DateTimeFormatter;
27+
import java.util.Iterator;
28+
import java.util.List;
29+
import java.util.UUID;
30+
import java.util.concurrent.TimeUnit;
31+
import java.util.stream.Collectors;
32+
33+
34+
public class MultivariateSample {
35+
private static void close(FileOutputStream fos) {
36+
try {
37+
fos.close();
38+
System.out.println("closed");
39+
} catch (IOException e) {
40+
throw new UncheckedIOException(e);
41+
}
42+
}
43+
44+
private static void write(FileOutputStream fos, ByteBuffer b) {
45+
try {
46+
fos.write(b.array());
47+
} catch (IOException e) {
48+
throw new UncheckedIOException(e);
49+
}
50+
}
51+
52+
private static AnomalyDetectorClient getClient(String endpoint, String key) {
53+
HttpHeaders headers = new HttpHeaders()
54+
.put("Accept", ContentType.APPLICATION_JSON);
55+
56+
HttpPipelinePolicy authPolicy = new AzureKeyCredentialPolicy("Ocp-Apim-Subscription-Key",
57+
new AzureKeyCredential(key));
58+
AddHeadersPolicy addHeadersPolicy = new AddHeadersPolicy(headers);
59+
60+
HttpPipeline httpPipeline = new HttpPipelineBuilder().httpClient(HttpClient.createDefault())
61+
.policies(authPolicy, addHeadersPolicy).build();
62+
// Instantiate a client that will be used to call the service.
63+
HttpLogOptions httpLogOptions = new HttpLogOptions();
64+
httpLogOptions.setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS);
65+
66+
AnomalyDetectorClient anomalyDetectorClient = new AnomalyDetectorClientBuilder()
67+
.pipeline(httpPipeline)
68+
.endpoint(endpoint)
69+
.httpLogOptions(httpLogOptions)
70+
.buildClient();
71+
return anomalyDetectorClient;
72+
}
73+
74+
private static UUID getMetricId(AnomalyDetectorClient client, ModelInfo request) {
75+
TrainMultivariateModelResponse trainMultivariateModelResponse = client.trainMultivariateModelWithResponse(request, Context.NONE);
76+
String header = trainMultivariateModelResponse.getDeserializedHeaders().getLocation();
77+
String[] model_ids = header.split("/");
78+
UUID model_id = UUID.fromString(model_ids[model_ids.length - 1]);
79+
return model_id;
80+
}
81+
82+
private static ModelStatus getModelStatus(AnomalyDetectorClient client, UUID model_id) {
83+
Response<Model> response = client.getMultivariateModelWithResponse(model_id, Context.NONE);
84+
UUID model = response.getValue().getModelId();
85+
System.out.println("training");
86+
return response.getValue().getModelInfo().getStatus();
87+
}
88+
89+
private static UUID getResultId(AnomalyDetectorClient client, UUID modelId, DetectionRequest detectionRequest) {
90+
DetectAnomalyResponse detectAnomalyResponse = client.detectAnomalyWithResponse(modelId, detectionRequest, Context.NONE);
91+
String response = detectAnomalyResponse.getDeserializedHeaders().getLocation();
92+
String[] result = response.split("/");
93+
UUID resultId = UUID.fromString(result[result.length - 1]);
94+
return resultId;
95+
}
96+
97+
private static DetectionStatus getInferenceStatus(AnomalyDetectorClient client, UUID resultId) {
98+
DetectionResult response = client.getDetectionResult(resultId);
99+
DetectionStatus status = response.getSummary().getStatus();
100+
return status;
101+
}
102+
103+
private static void ExportResult(AnomalyDetectorClient client, UUID modelId, String path) throws FileNotFoundException {
104+
StreamResponse response = client.exportModelWithResponse(modelId, Context.NONE);
105+
Flux<ByteBuffer> value = response.getValue();
106+
FileOutputStream bw = new FileOutputStream(path);
107+
value.subscribe(s -> write(bw, s), (e) -> close(bw), () -> close(bw));
108+
}
109+
110+
private static void GetModelList(AnomalyDetectorClient client, Integer skip, Integer top){
111+
PagedIterable<ModelSnapshot> response = client.listMultivariateModel(skip, top);
112+
Iterator<PagedResponse<ModelSnapshot>> ite = response.iterableByPage().iterator();
113+
int i =1;
114+
while(ite.hasNext()){
115+
PagedResponse<ModelSnapshot> items= ite.next();
116+
System.out.println("The result in the page "+i);
117+
i++;
118+
for (ModelSnapshot item: items.getValue()
119+
) {
120+
System.out.println("\t"+item.getModelId());
121+
}
122+
break;
123+
}
124+
}
125+
126+
127+
public static void main(final String[] args) throws IOException, InterruptedException {
128+
String endpoint = "<anomaly-detector-resource-endpoint>";
129+
String key = "<anomaly-detector-resource-key>";
130+
//Get multivariate client
131+
AnomalyDetectorClient client = getClient(endpoint, key);
132+
133+
134+
//Start training and get Model ID
135+
Integer window = 28;
136+
AlignMode alignMode = AlignMode.OUTER;
137+
FillNAMethod fillNAMethod = FillNAMethod.LINEAR;
138+
Integer paddingValue = 0;
139+
AlignPolicy alignPolicy = new AlignPolicy().setAlignMode(alignMode).setFillNAMethod(fillNAMethod).setPaddingValue(paddingValue);
140+
String source = "<Your own data source>";
141+
OffsetDateTime startTime = OffsetDateTime.of(2021, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
142+
;
143+
OffsetDateTime endTime = OffsetDateTime.of(2021, 1, 2, 12, 0, 0, 0, ZoneOffset.UTC);
144+
;
145+
String displayName = "<placeholder>";
146+
ModelInfo request = new ModelInfo().setSlidingWindow(window).setAlignPolicy(alignPolicy).setSource(source).setStartTime(startTime).setEndTime(endTime).setDisplayName(displayName);
147+
UUID modelId = getMetricId(client, request);
148+
System.out.println(modelId);
149+
150+
//Check model status util the model get ready
151+
while (true) {
152+
ModelStatus modelStatus = getModelStatus(client, modelId);
153+
TimeUnit.SECONDS.sleep(5);
154+
assert modelStatus != ModelStatus.FAILED;
155+
if (modelStatus == ModelStatus.READY) {
156+
break;
157+
}
158+
}
159+
160+
//Start inference and get the Result ID
161+
DetectionRequest detectionRequest = new DetectionRequest().setSource(source).setStartTime(startTime).setEndTime(endTime);
162+
UUID resultId = getResultId(client, modelId, detectionRequest);
163+
164+
165+
//Check inference status util the result get ready
166+
while (true) {
167+
DetectionStatus detectionStatus = getInferenceStatus(client, resultId);
168+
TimeUnit.SECONDS.sleep(5);
169+
assert detectionStatus != DetectionStatus.FAILED;
170+
if (detectionStatus == DetectionStatus.READY) {
171+
break;
172+
}
173+
}
174+
175+
//Export result files to local
176+
String path = "<path for the saving zip file>";
177+
ExportResult(client, modelId, path);
178+
179+
180+
//Delete model
181+
Response<Void> deleteMultivariateModelWithResponse = client.deleteMultivariateModelWithResponse(modelId, Context.NONE);
182+
183+
184+
//Get model list
185+
Integer skip = 0;
186+
Integer top = 5;
187+
GetModelList(client, skip, top);
188+
}
189+
}

0 commit comments

Comments
 (0)