diff options
Diffstat (limited to 'examples/examples-adaptive/src/main/java')
9 files changed, 1709 insertions, 0 deletions
diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java new file mode 100644 index 000000000..f574c74ec --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AnomalyDetection.java @@ -0,0 +1,243 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.concepts; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * The Class AnomalyDetection is used as a Java context for Adaptive anomaly detection in the adaptive domain. + */ +public class AnomalyDetection implements Serializable { + private static final long serialVersionUID = -823013127095523727L; + + private static final int HASH_PRIME_1 = 31; + private static final int HASH_PRIME_2 = 1231; + private static final int HASH_PRIME_3 = 1237; + + private boolean firstRound = true; + private int frequency = 0; + + /** + * The Constructor creates an AnomalyDetection instance. + */ + public AnomalyDetection() { + firstRound = true; + frequency = 0; + } + + private List<Double> anomalyScores = new LinkedList<>(); + private List<Double> frequencyForecasted; + + /** + * Checks if the AnomalyDetection instance is initialized. + * + * @return true, if the AnomalyDetection instance is initialized + */ + public boolean isInitialized() { + return (frequencyForecasted != null); + } + + /** + * Initializes the AnomalyDetection instance. + * + * @param incomingFrequency the frequency + */ + public void init(final int incomingFrequency) { + frequencyForecasted = new ArrayList<>(incomingFrequency); + for (int i = 0; i < incomingFrequency; i++) { + frequencyForecasted.add(null); + } + } + + /** + * Indicates if this is the first round of the algorithm. + * + * @return true if this is the first round of the algorithm + */ + public boolean getFirstRound() { + return firstRound; + } + + /** + * Sets the first round indicator of the algorithm. + * + * @param firstRound the first round indicator of the algorithm + */ + public void setFirstRound(final boolean firstRound) { + this.firstRound = firstRound; + } + + /** + * Gets the frequency value of the algorithm. + * + * @return the frequency value of the algorithm + */ + public int getFrequency() { + return frequency; + } + + /** + * Sets the frequency value of the algorithm. + * + * @param frequency the frequency value of the algorithm + */ + public void setFrequency(final int frequency) { + this.frequency = frequency; + } + + /** + * Gets the anomaly score values of the algorithm. + * + * @return the anomaly score values of the algorithm + */ + public List<Double> getAnomalyScores() { + return anomalyScores; + } + + /** + * Sets the anomaly score values of the algorithm. + * + * @param anomalyScores the anomaly score values of the algorithm + */ + public void setAnomalyScores(final LinkedList<Double> anomalyScores) { + this.anomalyScores = anomalyScores; + } + + /** + * Check if the anomaly score values of the algorithm are set. + * + * @return true, if the anomaly score values of the algorithm are set + */ + public boolean checkSetAnomalyScores() { + return ((anomalyScores != null) && (!anomalyScores.isEmpty())); + } + + /** + * Unset the anomaly score values of the algorithm. + */ + public void unsetAnomalyScores() { + anomalyScores = null; + } + + /** + * Gets the frequency forecasted by the algorithm. + * + * @return the frequency forecasted by the algorithm + */ + public List<Double> getFrequencyForecasted() { + return frequencyForecasted; + } + + /** + * Sets the frequency forecasted by the algorithm. + * + * @param frequencyForecasted the frequency forecasted by the algorithm + */ + public void setFrequencyForecasted(final List<Double> frequencyForecasted) { + this.frequencyForecasted = frequencyForecasted; + } + + /** + * Check if the frequency forecasted by the algorithm is set. + * + * @return true, if the frequency forecasted by the algorithm is set + */ + public boolean checkSetFrequencyForecasted() { + return ((frequencyForecasted != null) && (!frequencyForecasted.isEmpty())); + } + + /** + * Unset the frequency forecasted by the algorithm. + */ + public void unsetFrequencyForecasted() { + frequencyForecasted = null; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "AnomalyDetection [firstRound=" + firstRound + ", frequency=" + frequency + ", anomalyScores=" + + anomalyScores + ", frequencyForecasted=" + frequencyForecasted + "]"; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = HASH_PRIME_1; + int result = 1; + result = prime * result + ((anomalyScores == null) ? 0 : anomalyScores.hashCode()); + result = prime * result + (firstRound ? HASH_PRIME_2 : HASH_PRIME_3); + result = prime * result + frequency; + result = prime * result + ((frequencyForecasted == null) ? 0 : frequencyForecasted.hashCode()); + return result; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AnomalyDetection other = (AnomalyDetection) obj; + if (anomalyScores == null) { + if (other.anomalyScores != null) { + return false; + } + } else if (!anomalyScores.equals(other.anomalyScores)) { + return false; + } + if (firstRound != other.firstRound) { + return false; + } + if (frequency != other.frequency) { + return false; + } + if (frequencyForecasted == null) { + if (other.frequencyForecasted != null) { + return false; + } + } else if (!frequencyForecasted.equals(other.frequencyForecasted)) { + return false; + } + return true; + } +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AutoLearn.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AutoLearn.java new file mode 100644 index 000000000..f2e27725b --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/AutoLearn.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.concepts; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * The Class AutoLearn is used as a Java context for Adaptive auto-learning of trends towards a fixed value in the + * adaptive domain. + */ +public class AutoLearn implements Serializable { + private static final long serialVersionUID = 3825970380434170754L; + + private List<Double> avDiffs = null; + + private List<Long> counts = null; + + /** + * The Constructor creates an AutoLearn concept. + */ + public AutoLearn() {} + + /** + * Checks if the Autolearn instance is initialized. + * + * @return true, if the Autolearn instance is initialized + */ + public boolean isInitialized() { + return (avDiffs != null && counts != null); + } + + /** + * initializes the auto learning algorithm with the number of convergent variables to use. + * + * @param size the number of convergent variables to use + */ + public void init(final int size) { + if (avDiffs == null || avDiffs.size() == 0) { + avDiffs = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + avDiffs.add(i, Double.NaN); + } + } + + if (counts == null || counts.size() == 0) { + counts = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + counts.add(i, 0L); + } + } + } + + /** + * Gets the average difference values of the algorithm. + * + * @return the average difference values of the algorithm + */ + public List<Double> getAvDiffs() { + return avDiffs; + } + + /** + * Sets the average difference values of the algorithm. + * + * @param avDiffs the average difference values of the algorithm + */ + public void setAvDiffs(final List<Double> avDiffs) { + this.avDiffs = avDiffs; + } + + /** + * Check if the average difference values of the algorithm are set. + * + * @return true, if check set av diffs + */ + public boolean checkSetAvDiffs() { + return ((avDiffs != null) && (!avDiffs.isEmpty())); + } + + /** + * Unset the average difference values of the algorithm. + */ + public void unsetAvDiffs() { + avDiffs = null; + } + + /** + * Gets the count values of the algorithm. + * + * @return the count values of the algorithm + */ + public List<Long> getCounts() { + return counts; + } + + /** + * Sets the count values of the algorithm. + * + * @param counts the count values of the algorithm + */ + public void setCounts(final List<Long> counts) { + this.counts = counts; + } + + /** + * Check if the count values of the algorithm are set. + * + * @return true, if the count values of the algorithm are set + */ + public boolean checkSetCounts() { + return ((counts != null) && (!counts.isEmpty())); + } + + /** + * Unset the count values of the algorithm. + */ + public void unsetCounts() { + counts = null; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "AutoLearn [avDiffs=" + avDiffs + ", counts=" + counts + "]"; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((avDiffs == null) ? 0 : avDiffs.hashCode()); + result = prime * result + ((counts == null) ? 0 : counts.hashCode()); + return result; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final AutoLearn other = (AutoLearn) obj; + if (avDiffs == null) { + if (other.avDiffs != null) { + return false; + } + } else if (!avDiffs.equals(other.avDiffs)) { + return false; + } + if (counts == null) { + if (other.counts != null) { + return false; + } + } else if (!counts.equals(other.counts)) { + return false; + } + return true; + } +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/package-info.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/package-info.java new file mode 100644 index 000000000..8561ed074 --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/concepts/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Provides Java types that are used in the Adaptive domain. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +package org.onap.policy.apex.examples.adaptive.concepts; diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelFactory.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelFactory.java new file mode 100644 index 000000000..6242b1618 --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelFactory.java @@ -0,0 +1,558 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.model; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexRuntimeException; +import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxKeyInformation; +import org.onap.policy.apex.model.basicmodel.concepts.AxReferenceKey; +import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbum; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextAlbums; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchema; +import org.onap.policy.apex.model.contextmodel.concepts.AxContextSchemas; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvent; +import org.onap.policy.apex.model.eventmodel.concepts.AxEvents; +import org.onap.policy.apex.model.eventmodel.concepts.AxField; +import org.onap.policy.apex.model.policymodel.concepts.AxLogicReader; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicies; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicy; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; +import org.onap.policy.apex.model.policymodel.concepts.AxState; +import org.onap.policy.apex.model.policymodel.concepts.AxStateOutput; +import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskOutputType; +import org.onap.policy.apex.model.policymodel.concepts.AxStateTaskReference; +import org.onap.policy.apex.model.policymodel.concepts.AxTask; +import org.onap.policy.apex.model.policymodel.concepts.AxTaskLogic; +import org.onap.policy.apex.model.policymodel.concepts.AxTaskSelectionLogic; +import org.onap.policy.apex.model.policymodel.concepts.AxTasks; +import org.onap.policy.apex.model.policymodel.handling.PolicyLogicReader; + +/** + * The Class AdaptiveDomainModelFactory. + */ +public class AdaptiveDomainModelFactory { + + /** + * Gets the anomaly detection policy model. + * + * @return the anomaly detection policy model + */ + // CHECKSTYLE:OFF: checkstyle:maximumMethodLength + public AxPolicyModel getAnomalyDetectionPolicyModel() { + // CHECKSTYLE:ON: checkstyle:maximumMethodLength + // Data types for event parameters + final AxContextSchema monitoredValue = + new AxContextSchema(new AxArtifactKey("MonitoredValue", "0.0.1"), "Java", "java.lang.Double"); + final AxContextSchema iteration = + new AxContextSchema(new AxArtifactKey("Iteration", "0.0.1"), "Java", "java.lang.Integer"); + + final AxContextSchemas adContextSchemas = new AxContextSchemas(new AxArtifactKey("AADMDatatypes", "0.0.1")); + adContextSchemas.getSchemasMap().put(monitoredValue.getKey(), monitoredValue); + adContextSchemas.getSchemasMap().put(iteration.getKey(), iteration); + + final AxEvent anomalyDetectionTriggerEvent = + new AxEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + anomalyDetectionTriggerEvent.setSource("External"); + anomalyDetectionTriggerEvent.setTarget("Match"); + anomalyDetectionTriggerEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(anomalyDetectionTriggerEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + anomalyDetectionTriggerEvent.getParameterMap().put("Iteration", new AxField( + new AxReferenceKey(anomalyDetectionTriggerEvent.getKey(), "Iteration"), iteration.getKey())); + + final AxEvent anomalyDetectionMatchEvent = new AxEvent(new AxArtifactKey("AnomalyDetectionMatchEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + anomalyDetectionMatchEvent.setSource("Match"); + anomalyDetectionMatchEvent.setTarget("Establish"); + anomalyDetectionMatchEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(anomalyDetectionMatchEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + anomalyDetectionMatchEvent.getParameterMap().put("Iteration", + new AxField(new AxReferenceKey(anomalyDetectionMatchEvent.getKey(), "Iteration"), iteration.getKey())); + + final AxEvent anomalyDetectionEstablishEvent = + new AxEvent(new AxArtifactKey("AnomalyDetectionEstablishEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + anomalyDetectionEstablishEvent.setSource("Establish"); + anomalyDetectionEstablishEvent.setTarget("Decide"); + anomalyDetectionEstablishEvent.getParameterMap().put("MonitoredValue", + new AxField(new AxReferenceKey(anomalyDetectionEstablishEvent.getKey(), "MonitoredValue"), + monitoredValue.getKey())); + anomalyDetectionEstablishEvent.getParameterMap().put("Iteration", new AxField( + new AxReferenceKey(anomalyDetectionEstablishEvent.getKey(), "Iteration"), iteration.getKey())); + + final AxEvent anomalyDetectionDecideEvent = + new AxEvent(new AxArtifactKey("AnomalyDetectionDecideEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + anomalyDetectionDecideEvent.setSource("Decide"); + anomalyDetectionDecideEvent.setTarget("Act"); + anomalyDetectionDecideEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(anomalyDetectionDecideEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + anomalyDetectionDecideEvent.getParameterMap().put("Iteration", + new AxField(new AxReferenceKey(anomalyDetectionDecideEvent.getKey(), "Iteration"), iteration.getKey())); + + final AxEvent anomalyDetectionActEvent = new AxEvent(new AxArtifactKey("AnomalyDetectionActEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + anomalyDetectionActEvent.setSource("Act"); + anomalyDetectionActEvent.setTarget("External"); + anomalyDetectionActEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(anomalyDetectionActEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + anomalyDetectionActEvent.getParameterMap().put("Iteration", + new AxField(new AxReferenceKey(anomalyDetectionActEvent.getKey(), "Iteration"), iteration.getKey())); + + final AxEvents anomalyDetectionEvents = new AxEvents(new AxArtifactKey("AnomalyDetectionEvents", "0.0.1")); + anomalyDetectionEvents.getEventMap().put(anomalyDetectionTriggerEvent.getKey(), anomalyDetectionTriggerEvent); + anomalyDetectionEvents.getEventMap().put(anomalyDetectionMatchEvent.getKey(), anomalyDetectionMatchEvent); + anomalyDetectionEvents.getEventMap().put(anomalyDetectionEstablishEvent.getKey(), + anomalyDetectionEstablishEvent); + anomalyDetectionEvents.getEventMap().put(anomalyDetectionDecideEvent.getKey(), anomalyDetectionDecideEvent); + anomalyDetectionEvents.getEventMap().put(anomalyDetectionActEvent.getKey(), anomalyDetectionActEvent); + + // Data types for context + final AxContextSchema anomalyDetection = new AxContextSchema(new AxArtifactKey("AnomalyDetection", "0.0.1"), + "Java", "org.onap.policy.apex.examples.adaptive.concepts.AnomalyDetection"); + adContextSchemas.getSchemasMap().put(anomalyDetection.getKey(), anomalyDetection); + + // One context map + final AxContextAlbum anomalyDetectionAlbum = new AxContextAlbum( + new AxArtifactKey("AnomalyDetectionAlbum", "0.0.1"), "APPLICATION", true, anomalyDetection.getKey()); + final AxContextAlbums anomalyDetectionAlbums = + new AxContextAlbums(new AxArtifactKey("AnomalyDetectionAlbums", "0.0.1")); + anomalyDetectionAlbums.getAlbumsMap().put(anomalyDetectionAlbum.getKey(), anomalyDetectionAlbum); + + // Tasks + final AxLogicReader logicReader = + new PolicyLogicReader().setLogicPackage(this.getClass().getPackage().getName()) + .setDefaultLogic("DefaultAnomalyDetectionTask_Logic"); + + final AxTask anomalyDetectionMatchTask = new AxTask(new AxArtifactKey("AnomalyDetectionMatchTask", "0.0.1")); + anomalyDetectionMatchTask.duplicateInputFields(anomalyDetectionTriggerEvent.getParameterMap()); + anomalyDetectionMatchTask.duplicateOutputFields(anomalyDetectionMatchEvent.getParameterMap()); + anomalyDetectionMatchTask + .setTaskLogic(new AxTaskLogic(anomalyDetectionMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask anomalyDetectionEstablishTask = + new AxTask(new AxArtifactKey("AnomalyDetectionEstablishTask", "0.0.1")); + anomalyDetectionEstablishTask.duplicateInputFields(anomalyDetectionMatchEvent.getParameterMap()); + anomalyDetectionEstablishTask.duplicateOutputFields(anomalyDetectionEstablishEvent.getParameterMap()); + anomalyDetectionEstablishTask.setTaskLogic( + new AxTaskLogic(anomalyDetectionEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask anomalyDetectionDecideTask0 = + new AxTask(new AxArtifactKey("AnomalyDetectionDecideTask0", "0.0.1")); + anomalyDetectionDecideTask0.duplicateInputFields(anomalyDetectionEstablishEvent.getParameterMap()); + anomalyDetectionDecideTask0.duplicateOutputFields(anomalyDetectionDecideEvent.getParameterMap()); + anomalyDetectionDecideTask0 + .setTaskLogic(new AxTaskLogic(anomalyDetectionDecideTask0.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask anomalyDetectionDecideTask1 = + new AxTask(new AxArtifactKey("AnomalyDetectionDecideTask1", "0.0.1")); + anomalyDetectionDecideTask1.duplicateInputFields(anomalyDetectionEstablishEvent.getParameterMap()); + anomalyDetectionDecideTask1.duplicateOutputFields(anomalyDetectionDecideEvent.getParameterMap()); + anomalyDetectionDecideTask1 + .setTaskLogic(new AxTaskLogic(anomalyDetectionDecideTask1.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask anomalyDetectionDecideTask2 = + new AxTask(new AxArtifactKey("AnomalyDetectionDecideTask2", "0.0.1")); + anomalyDetectionDecideTask2.duplicateInputFields(anomalyDetectionEstablishEvent.getParameterMap()); + anomalyDetectionDecideTask2.duplicateOutputFields(anomalyDetectionDecideEvent.getParameterMap()); + anomalyDetectionDecideTask2 + .setTaskLogic(new AxTaskLogic(anomalyDetectionDecideTask2.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask anomalyDetectionActTask = new AxTask(new AxArtifactKey("AnomalyDetectionActTask", "0.0.1")); + anomalyDetectionActTask.duplicateInputFields(anomalyDetectionDecideEvent.getParameterMap()); + anomalyDetectionActTask.duplicateOutputFields(anomalyDetectionActEvent.getParameterMap()); + anomalyDetectionActTask + .setTaskLogic(new AxTaskLogic(anomalyDetectionActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTasks anomalyDetectionTasks = new AxTasks(new AxArtifactKey("AnomalyDetectionTasks", "0.0.1")); + anomalyDetectionTasks.getTaskMap().put(anomalyDetectionMatchTask.getKey(), anomalyDetectionMatchTask); + anomalyDetectionTasks.getTaskMap().put(anomalyDetectionEstablishTask.getKey(), anomalyDetectionEstablishTask); + anomalyDetectionTasks.getTaskMap().put(anomalyDetectionDecideTask0.getKey(), anomalyDetectionDecideTask0); + anomalyDetectionTasks.getTaskMap().put(anomalyDetectionDecideTask1.getKey(), anomalyDetectionDecideTask1); + anomalyDetectionTasks.getTaskMap().put(anomalyDetectionDecideTask2.getKey(), anomalyDetectionDecideTask2); + anomalyDetectionTasks.getTaskMap().put(anomalyDetectionActTask.getKey(), anomalyDetectionActTask); + + // Policies + logicReader.setDefaultLogic("DefaultState_Logic"); + + final AxPolicy anomalyDetectionPolicy = new AxPolicy(new AxArtifactKey("AnomalyDetectionPolicy", "0.0.1")); + anomalyDetectionPolicy.setTemplate("MEDA"); + + final AxState anomalyDetectionActState = + new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Act")); + anomalyDetectionActState.setTrigger(anomalyDetectionDecideEvent.getKey()); + final AxStateOutput adAct2Out = new AxStateOutput(anomalyDetectionActState.getKey(), + AxReferenceKey.getNullKey(), anomalyDetectionActEvent.getKey()); + anomalyDetectionActState.getStateOutputs().put(adAct2Out.getKey().getLocalName(), adAct2Out); + anomalyDetectionActState.setTaskSelectionLogic( + new AxTaskSelectionLogic(anomalyDetectionActState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + anomalyDetectionActState.setDefaultTask(anomalyDetectionActTask.getKey()); + anomalyDetectionActState.getTaskReferences().put(anomalyDetectionActTask.getKey(), + new AxStateTaskReference(anomalyDetectionActState.getKey(), anomalyDetectionActTask.getKey(), + AxStateTaskOutputType.DIRECT, adAct2Out.getKey())); + + logicReader.setDefaultLogic(null); + + final AxState anomalyDetectionDecideState = + new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Decide")); + anomalyDetectionDecideState.setTrigger(anomalyDetectionEstablishEvent.getKey()); + final AxStateOutput adDec2Act = new AxStateOutput(anomalyDetectionDecideState.getKey(), + anomalyDetectionActState.getKey(), anomalyDetectionDecideEvent.getKey()); + anomalyDetectionDecideState.getStateOutputs().put(adDec2Act.getKey().getLocalName(), adDec2Act); + anomalyDetectionDecideState.setTaskSelectionLogic(new AxTaskSelectionLogic(anomalyDetectionDecideState.getKey(), + "TaskSelectionLogic", "JAVA", logicReader)); + anomalyDetectionDecideState.setDefaultTask(anomalyDetectionDecideTask0.getKey()); + anomalyDetectionDecideState.getContextAlbumReferences().add(anomalyDetectionAlbum.getKey()); + anomalyDetectionDecideState.getTaskReferences().put(anomalyDetectionDecideTask0.getKey(), + new AxStateTaskReference(anomalyDetectionDecideState.getKey(), anomalyDetectionDecideTask0.getKey(), + AxStateTaskOutputType.DIRECT, adDec2Act.getKey())); + anomalyDetectionDecideState.getTaskReferences().put(anomalyDetectionDecideTask1.getKey(), + new AxStateTaskReference(anomalyDetectionDecideState.getKey(), anomalyDetectionDecideTask1.getKey(), + AxStateTaskOutputType.DIRECT, adDec2Act.getKey())); + anomalyDetectionDecideState.getTaskReferences().put(anomalyDetectionDecideTask2.getKey(), + new AxStateTaskReference(anomalyDetectionDecideState.getKey(), anomalyDetectionDecideTask2.getKey(), + AxStateTaskOutputType.DIRECT, adDec2Act.getKey())); + + logicReader.setDefaultLogic("DefaultState_Logic"); + + final AxState anomalyDetectionEstablishState = + new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Establish")); + anomalyDetectionEstablishState.setTrigger(anomalyDetectionMatchEvent.getKey()); + final AxStateOutput adEst2Dec = new AxStateOutput(anomalyDetectionEstablishState.getKey(), + anomalyDetectionDecideState.getKey(), anomalyDetectionEstablishEvent.getKey()); + anomalyDetectionEstablishState.getStateOutputs().put(adEst2Dec.getKey().getLocalName(), adEst2Dec); + anomalyDetectionEstablishState.setTaskSelectionLogic(new AxTaskSelectionLogic( + anomalyDetectionEstablishState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + anomalyDetectionEstablishState.setDefaultTask(anomalyDetectionEstablishTask.getKey()); + anomalyDetectionEstablishState.getTaskReferences().put(anomalyDetectionEstablishTask.getKey(), + new AxStateTaskReference(anomalyDetectionEstablishState.getKey(), + anomalyDetectionEstablishTask.getKey(), AxStateTaskOutputType.DIRECT, adEst2Dec.getKey())); + + final AxState anomalyDetectionMatchState = + new AxState(new AxReferenceKey(anomalyDetectionPolicy.getKey(), "Match")); + anomalyDetectionMatchState.setTrigger(anomalyDetectionTriggerEvent.getKey()); + final AxStateOutput adMat2Est = new AxStateOutput(anomalyDetectionMatchState.getKey(), + anomalyDetectionEstablishState.getKey(), anomalyDetectionMatchEvent.getKey()); + anomalyDetectionMatchState.getStateOutputs().put(adMat2Est.getKey().getLocalName(), adMat2Est); + anomalyDetectionMatchState.setTaskSelectionLogic(new AxTaskSelectionLogic(anomalyDetectionMatchState.getKey(), + "TaskSelectionLogic", "MVEL", logicReader)); + anomalyDetectionMatchState.setDefaultTask(anomalyDetectionMatchTask.getKey()); + anomalyDetectionMatchState.getTaskReferences().put(anomalyDetectionMatchTask.getKey(), + new AxStateTaskReference(anomalyDetectionMatchState.getKey(), anomalyDetectionMatchTask.getKey(), + AxStateTaskOutputType.DIRECT, adMat2Est.getKey())); + + anomalyDetectionPolicy.setFirstState(anomalyDetectionMatchState.getKey().getLocalName()); + anomalyDetectionPolicy.getStateMap().put(anomalyDetectionMatchState.getKey().getLocalName(), + anomalyDetectionMatchState); + anomalyDetectionPolicy.getStateMap().put(anomalyDetectionEstablishState.getKey().getLocalName(), + anomalyDetectionEstablishState); + anomalyDetectionPolicy.getStateMap().put(anomalyDetectionDecideState.getKey().getLocalName(), + anomalyDetectionDecideState); + anomalyDetectionPolicy.getStateMap().put(anomalyDetectionActState.getKey().getLocalName(), + anomalyDetectionActState); + + final AxPolicies anomalyDetectionPolicies = + new AxPolicies(new AxArtifactKey("AnomalyDetectionPolicies", "0.0.1")); + anomalyDetectionPolicies.getPolicyMap().put(anomalyDetectionPolicy.getKey(), anomalyDetectionPolicy); + + final AxKeyInformation keyInformation = + new AxKeyInformation(new AxArtifactKey("AnomalyDetectionKeyInformation", "0.0.1")); + final AxPolicyModel anomalyDetectionPolicyModel = + new AxPolicyModel(new AxArtifactKey("AnomalyDetectionPolicyModel", "0.0.1")); + anomalyDetectionPolicyModel.setPolicies(anomalyDetectionPolicies); + anomalyDetectionPolicyModel.setEvents(anomalyDetectionEvents); + anomalyDetectionPolicyModel.setTasks(anomalyDetectionTasks); + anomalyDetectionPolicyModel.setAlbums(anomalyDetectionAlbums); + anomalyDetectionPolicyModel.setSchemas(adContextSchemas); + anomalyDetectionPolicyModel.setKeyInformation(keyInformation); + anomalyDetectionPolicyModel.getKeyInformation().generateKeyInfo(anomalyDetectionPolicyModel); + + final AxValidationResult result = anomalyDetectionPolicyModel.validate(new AxValidationResult()); + if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.VALID)) { + throw new ApexRuntimeException("model " + anomalyDetectionPolicyModel.getID() + " is not valid" + result); + } + return anomalyDetectionPolicyModel; + } + + /** + * Gets the auto learn policy model. + * + * @return the auto learn policy model + */ + // CHECKSTYLE:OFF: checkstyle:maximumMethodLength + public AxPolicyModel getAutoLearnPolicyModel() { + // CHECKSTYLE:ON: checkstyle:maximumMethodLength + // Data types for event parameters + final AxContextSchema monitoredValue = + new AxContextSchema(new AxArtifactKey("MonitoredValue", "0.0.1"), "Java", "java.lang.Double"); + + final AxContextSchemas alContextSchemas = new AxContextSchemas(new AxArtifactKey("ALDatatypes", "0.0.1")); + alContextSchemas.getSchemasMap().put(monitoredValue.getKey(), monitoredValue); + + final AxEvent autoLearnTriggerEvent = new AxEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + autoLearnTriggerEvent.setSource("External"); + autoLearnTriggerEvent.setTarget("Match"); + autoLearnTriggerEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(autoLearnTriggerEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + autoLearnTriggerEvent.getParameterMap().put("LastMonitoredValue", new AxField( + new AxReferenceKey(autoLearnTriggerEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); + + final AxEvent autoLearnMatchEvent = new AxEvent(new AxArtifactKey("AutoLearnMatchEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + autoLearnMatchEvent.setSource("Match"); + autoLearnMatchEvent.setTarget("Establish"); + autoLearnMatchEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(autoLearnMatchEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + autoLearnMatchEvent.getParameterMap().put("LastMonitoredValue", new AxField( + new AxReferenceKey(autoLearnMatchEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); + + final AxEvent autoLearnEstablishEvent = new AxEvent(new AxArtifactKey("AutoLearnEstablishEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + autoLearnEstablishEvent.setSource("Establish"); + autoLearnEstablishEvent.setTarget("Decide"); + autoLearnEstablishEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(autoLearnEstablishEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + autoLearnEstablishEvent.getParameterMap().put("LastMonitoredValue", new AxField( + new AxReferenceKey(autoLearnEstablishEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); + + final AxEvent autoLearnDecideEvent = new AxEvent(new AxArtifactKey("AutoLearnDecideEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + autoLearnDecideEvent.setSource("Decide"); + autoLearnDecideEvent.setTarget("Act"); + autoLearnDecideEvent.getParameterMap().put("MonitoredValue", new AxField( + new AxReferenceKey(autoLearnDecideEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + autoLearnDecideEvent.getParameterMap().put("LastMonitoredValue", new AxField( + new AxReferenceKey(autoLearnDecideEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); + + final AxEvent autoLearnActEvent = new AxEvent(new AxArtifactKey("AutoLearnActEvent", "0.0.1"), + "org.onap.policy.apex.examples.adaptive.events"); + autoLearnActEvent.setSource("Act"); + autoLearnActEvent.setTarget("External"); + autoLearnActEvent.getParameterMap().put("MonitoredValue", + new AxField(new AxReferenceKey(autoLearnActEvent.getKey(), "MonitoredValue"), monitoredValue.getKey())); + autoLearnActEvent.getParameterMap().put("LastMonitoredValue", new AxField( + new AxReferenceKey(autoLearnActEvent.getKey(), "LastMonitoredValue"), monitoredValue.getKey())); + + final AxEvents autoLearnEvents = new AxEvents(new AxArtifactKey("AutoLearnEvents", "0.0.1")); + autoLearnEvents.getEventMap().put(autoLearnTriggerEvent.getKey(), autoLearnTriggerEvent); + autoLearnEvents.getEventMap().put(autoLearnMatchEvent.getKey(), autoLearnMatchEvent); + autoLearnEvents.getEventMap().put(autoLearnEstablishEvent.getKey(), autoLearnEstablishEvent); + autoLearnEvents.getEventMap().put(autoLearnDecideEvent.getKey(), autoLearnDecideEvent); + autoLearnEvents.getEventMap().put(autoLearnActEvent.getKey(), autoLearnActEvent); + + // Data types for context + final AxContextSchema autoLearn = new AxContextSchema(new AxArtifactKey("AutoLearn", "0.0.1"), "Java", + "org.onap.policy.apex.examples.adaptive.concepts.AutoLearn"); + alContextSchemas.getSchemasMap().put(autoLearn.getKey(), autoLearn); + + // One context map + final AxContextAlbum autoLearnAlbum = new AxContextAlbum(new AxArtifactKey("AutoLearnAlbum", "0.0.1"), + "APPLICATION", true, autoLearn.getKey()); + + final AxContextAlbums autoLearnAlbums = new AxContextAlbums(new AxArtifactKey("AutoLearnContext", "0.0.1")); + autoLearnAlbums.getAlbumsMap().put(autoLearnAlbum.getKey(), autoLearnAlbum); + + // Tasks + final AxLogicReader logicReader = new PolicyLogicReader() + .setLogicPackage(this.getClass().getPackage().getName()).setDefaultLogic("DefaultAutoLearnTask_Logic"); + + final AxTask autoLearnMatchTask = new AxTask(new AxArtifactKey("AutoLearnMatchTask", "0.0.1")); + autoLearnMatchTask.duplicateInputFields(autoLearnTriggerEvent.getParameterMap()); + autoLearnMatchTask.duplicateOutputFields(autoLearnMatchEvent.getParameterMap()); + autoLearnMatchTask.setTaskLogic(new AxTaskLogic(autoLearnMatchTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask autoLearnEstablishTask = new AxTask(new AxArtifactKey("AutoLearnEstablishTask", "0.0.1")); + autoLearnEstablishTask.duplicateInputFields(autoLearnMatchEvent.getParameterMap()); + autoLearnEstablishTask.duplicateOutputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnEstablishTask + .setTaskLogic(new AxTaskLogic(autoLearnEstablishTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + logicReader.setDefaultLogic(null); + + final AxTask autoLearnDecideTask0 = new AxTask(new AxArtifactKey("AutoLearnDecideTask0", "0.0.1")); + autoLearnDecideTask0.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnDecideTask0.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnDecideTask0 + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask0.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask autoLearnDecideTask1 = new AxTask(new AxArtifactKey("AutoLearnDecideTask1", "0.0.1")); + autoLearnDecideTask1.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnDecideTask1.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnDecideTask1 + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask1.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask autoLearnDecideTask2 = new AxTask(new AxArtifactKey("AutoLearnDecideTask2", "0.0.1")); + autoLearnDecideTask2.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnDecideTask2.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnDecideTask2 + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask2.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask autoLearnDecideTask3 = new AxTask(new AxArtifactKey("AutoLearnDecideTask3", "0.0.1")); + autoLearnDecideTask3.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnDecideTask3.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnDecideTask3 + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask3.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask autoLearnDecideTask4 = new AxTask(new AxArtifactKey("AutoLearnDecideTask4", "0.0.1")); + autoLearnDecideTask4.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnDecideTask4.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnDecideTask4 + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask4.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask autoLearnDecideTask5 = new AxTask(new AxArtifactKey("AutoLearnDecideTask5", "0.0.1")); + autoLearnDecideTask5.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnDecideTask5.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnDecideTask5 + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask5.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTask autoLearnDecideTask6 = new AxTask(new AxArtifactKey("AutoLearnDecideTask6", "0.0.1")); + autoLearnDecideTask6.duplicateInputFields(autoLearnEstablishEvent.getParameterMap()); + autoLearnDecideTask6.duplicateOutputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnDecideTask6 + .setTaskLogic(new AxTaskLogic(autoLearnDecideTask6.getKey(), "TaskLogic", "MVEL", logicReader)); + + logicReader.setDefaultLogic("DefaultAutoLearnTask_Logic"); + + final AxTask autoLearnActTask = new AxTask(new AxArtifactKey("AutoLearnActTask", "0.0.1")); + autoLearnActTask.duplicateInputFields(autoLearnDecideEvent.getParameterMap()); + autoLearnActTask.duplicateOutputFields(autoLearnActEvent.getParameterMap()); + autoLearnActTask.setTaskLogic(new AxTaskLogic(autoLearnActTask.getKey(), "TaskLogic", "MVEL", logicReader)); + + final AxTasks autoLearnTasks = new AxTasks(new AxArtifactKey("AutoLearnTasks", "0.0.1")); + autoLearnTasks.getTaskMap().put(autoLearnMatchTask.getKey(), autoLearnMatchTask); + autoLearnTasks.getTaskMap().put(autoLearnEstablishTask.getKey(), autoLearnEstablishTask); + autoLearnTasks.getTaskMap().put(autoLearnDecideTask0.getKey(), autoLearnDecideTask0); + autoLearnTasks.getTaskMap().put(autoLearnDecideTask1.getKey(), autoLearnDecideTask1); + autoLearnTasks.getTaskMap().put(autoLearnDecideTask2.getKey(), autoLearnDecideTask2); + autoLearnTasks.getTaskMap().put(autoLearnDecideTask3.getKey(), autoLearnDecideTask3); + autoLearnTasks.getTaskMap().put(autoLearnDecideTask4.getKey(), autoLearnDecideTask4); + autoLearnTasks.getTaskMap().put(autoLearnDecideTask5.getKey(), autoLearnDecideTask5); + autoLearnTasks.getTaskMap().put(autoLearnDecideTask6.getKey(), autoLearnDecideTask6); + autoLearnTasks.getTaskMap().put(autoLearnActTask.getKey(), autoLearnActTask); + + // Policies + logicReader.setDefaultLogic("DefaultState_Logic"); + + final AxPolicy autoLearnPolicy = new AxPolicy(new AxArtifactKey("AutoLearnPolicy", "0.0.1")); + autoLearnPolicy.setTemplate("MEDA"); + + final AxState autoLearnActState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Act")); + autoLearnActState.setTrigger(autoLearnDecideEvent.getKey()); + final AxStateOutput alAct2Out = + new AxStateOutput(autoLearnActState.getKey(), AxReferenceKey.getNullKey(), autoLearnActEvent.getKey()); + autoLearnActState.getStateOutputs().put(alAct2Out.getKey().getLocalName(), alAct2Out); + autoLearnActState.setTaskSelectionLogic( + new AxTaskSelectionLogic(autoLearnActState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + autoLearnActState.setDefaultTask(autoLearnActTask.getKey()); + autoLearnActState.getTaskReferences().put(autoLearnActTask.getKey(), + new AxStateTaskReference(autoLearnActState.getKey(), autoLearnActTask.getKey(), + AxStateTaskOutputType.DIRECT, alAct2Out.getKey())); + + logicReader.setDefaultLogic(null); + + final AxState autoLearnDecideState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Decide")); + autoLearnDecideState.setTrigger(autoLearnEstablishEvent.getKey()); + final AxStateOutput alDec2Act = new AxStateOutput(autoLearnDecideState.getKey(), autoLearnActState.getKey(), + autoLearnDecideEvent.getKey()); + autoLearnDecideState.getStateOutputs().put(alDec2Act.getKey().getLocalName(), alDec2Act); + autoLearnDecideState.getContextAlbumReferences().add(autoLearnAlbum.getKey()); + autoLearnDecideState.setTaskSelectionLogic( + new AxTaskSelectionLogic(autoLearnDecideState.getKey(), "TaskSelectionLogic", "JAVA", logicReader)); + autoLearnDecideState.setDefaultTask(autoLearnDecideTask0.getKey()); + autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask0.getKey(), + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask0.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask1.getKey(), + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask1.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask2.getKey(), + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask2.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask3.getKey(), + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask3.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask4.getKey(), + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask4.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask5.getKey(), + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask5.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + autoLearnDecideState.getTaskReferences().put(autoLearnDecideTask6.getKey(), + new AxStateTaskReference(autoLearnDecideState.getKey(), autoLearnDecideTask6.getKey(), + AxStateTaskOutputType.DIRECT, alDec2Act.getKey())); + + logicReader.setDefaultLogic("DefaultState_Logic"); + + final AxState autoLearnEstablishState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Establish")); + autoLearnEstablishState.setTrigger(autoLearnMatchEvent.getKey()); + final AxStateOutput alEst2Dec = new AxStateOutput(autoLearnEstablishState.getKey(), + autoLearnDecideState.getKey(), autoLearnEstablishEvent.getKey()); + autoLearnEstablishState.getStateOutputs().put(alEst2Dec.getKey().getLocalName(), alEst2Dec); + autoLearnEstablishState.setTaskSelectionLogic( + new AxTaskSelectionLogic(autoLearnEstablishState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + autoLearnEstablishState.setDefaultTask(autoLearnEstablishTask.getKey()); + autoLearnEstablishState.getTaskReferences().put(autoLearnEstablishTask.getKey(), + new AxStateTaskReference(autoLearnEstablishState.getKey(), autoLearnEstablishTask.getKey(), + AxStateTaskOutputType.DIRECT, alEst2Dec.getKey())); + + final AxState autoLearnMatchState = new AxState(new AxReferenceKey(autoLearnPolicy.getKey(), "Match")); + autoLearnMatchState.setTrigger(autoLearnTriggerEvent.getKey()); + final AxStateOutput alMat2Est = new AxStateOutput(autoLearnMatchState.getKey(), + autoLearnEstablishState.getKey(), autoLearnMatchEvent.getKey()); + autoLearnMatchState.getStateOutputs().put(alMat2Est.getKey().getLocalName(), alMat2Est); + autoLearnMatchState.setTaskSelectionLogic( + new AxTaskSelectionLogic(autoLearnMatchState.getKey(), "TaskSelectionLogic", "MVEL", logicReader)); + autoLearnMatchState.setDefaultTask(autoLearnMatchTask.getKey()); + autoLearnMatchState.getTaskReferences().put(autoLearnMatchTask.getKey(), + new AxStateTaskReference(autoLearnMatchState.getKey(), autoLearnMatchTask.getKey(), + AxStateTaskOutputType.DIRECT, alMat2Est.getKey())); + + autoLearnPolicy.setFirstState(autoLearnMatchState.getKey().getLocalName()); + autoLearnPolicy.getStateMap().put(autoLearnMatchState.getKey().getLocalName(), autoLearnMatchState); + autoLearnPolicy.getStateMap().put(autoLearnEstablishState.getKey().getLocalName(), autoLearnEstablishState); + autoLearnPolicy.getStateMap().put(autoLearnDecideState.getKey().getLocalName(), autoLearnDecideState); + autoLearnPolicy.getStateMap().put(autoLearnActState.getKey().getLocalName(), autoLearnActState); + + final AxPolicies autoLearnPolicies = new AxPolicies(new AxArtifactKey("AutoLearnPolicies", "0.0.1")); + autoLearnPolicies.getPolicyMap().put(autoLearnPolicy.getKey(), autoLearnPolicy); + + final AxKeyInformation keyInformation = + new AxKeyInformation(new AxArtifactKey("AutoLearnKeyInformation", "0.0.1")); + final AxPolicyModel autoLearnPolicyModel = + new AxPolicyModel(new AxArtifactKey("AutoLearnPolicyModel", "0.0.1")); + autoLearnPolicyModel.setPolicies(autoLearnPolicies); + autoLearnPolicyModel.setEvents(autoLearnEvents); + autoLearnPolicyModel.setTasks(autoLearnTasks); + autoLearnPolicyModel.setAlbums(autoLearnAlbums); + autoLearnPolicyModel.setSchemas(alContextSchemas); + autoLearnPolicyModel.setKeyInformation(keyInformation); + autoLearnPolicyModel.getKeyInformation().generateKeyInfo(autoLearnPolicyModel); + + final AxValidationResult result = autoLearnPolicyModel.validate(new AxValidationResult()); + if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.VALID)) { + throw new ApexRuntimeException("model " + autoLearnPolicyModel.getID() + " is not valid" + result); + } + return autoLearnPolicyModel; + } + +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelSaver.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelSaver.java new file mode 100644 index 000000000..0cc9bd3a2 --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/AdaptiveDomainModelSaver.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.model; + +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.onap.policy.apex.model.basicmodel.handling.ApexModelSaver; +import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel; + +/** + * This class saves sample domain models to disk in XML and JSON format. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ +public final class AdaptiveDomainModelSaver { + /** + * Private default constructor to prevent subclassing. + */ + private AdaptiveDomainModelSaver() {} + + /** + * Write the AADM model to args[0]. + * + * @param args Not used + * @throws ApexException the apex exception + */ + public static void main(final String[] args) throws ApexException { + if (args.length != 1) { + System.err.println("usage: " + AdaptiveDomainModelSaver.class.getCanonicalName() + " modelDirectory"); + return; + } + + // Save Anomaly Detection model + final AxPolicyModel adPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel(); + final ApexModelSaver<AxPolicyModel> adModelSaver = + new ApexModelSaver<>(AxPolicyModel.class, adPolicyModel, args[0]); + adModelSaver.apexModelWriteJSON(); + adModelSaver.apexModelWriteXML(); + + // Save Auto Learn model + final AxPolicyModel alPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel(); + final ApexModelSaver<AxPolicyModel> alModelSaver = + new ApexModelSaver<>(AxPolicyModel.class, alPolicyModel, args[0]); + alModelSaver.apexModelWriteJSON(); + alModelSaver.apexModelWriteXML(); + } +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java new file mode 100644 index 000000000..a0b2a8f40 --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicy_Decide_TaskSelectionLogic.java @@ -0,0 +1,414 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.model.java; + +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.math3.distribution.TDistribution; +import org.apache.commons.math3.util.FastMath; +import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; +import org.onap.policy.apex.examples.adaptive.concepts.AnomalyDetection; +import org.onap.policy.apex.model.basicmodel.concepts.ApexException; +import org.slf4j.Logger; + +/** + * The Class AnomalyDetectionPolicy_Decide_TaskSelectionLogic. + */ +// CHECKSTYLE:OFF: checkstyle:className +public class AnomalyDetectionPolicy_Decide_TaskSelectionLogic { + // CHECKSTYLE:ON: checkstyle:className + + private Logger logger; + // configuration + private static final double ANOMALY_SENSITIVITY = 0.05; + private static final int FREQUENCY = 360; + + /** + * A map to hold the Anomaly degree/levels/probabilities required for each task.<br> + * If there is no task defined for a calculated anomaly-degree, then the default task is used.<br> + * The map use (LinkedHashMap) is an insertion-ordered map, so the first interval matching a query is used. + */ + // CHECKSTYLE:OFF: checkstyle:magicNumber + private static final Map<double[], String> TASK_INTERVALS = new LinkedHashMap<>(); + static { + TASK_INTERVALS.put(new double[] { 0.0, 0.1 }, null); // null will mean default task + TASK_INTERVALS.put(new double[] { 0.25, 0.5 }, "AnomalyDetectionDecideTask1"); + TASK_INTERVALS.put(new double[] { 0.5, 1.01 }, "AnomalyDetectionDecideTask2"); + } + // CHECKSTYLE:ON: checkstyle:magicNumber + + private volatile TaskSelectionExecutionContext executionContext; + + /** + * Gets the task. + * + * @param executor the executor + * @return the task + */ + public boolean getTask(final TaskSelectionExecutionContext executor) { + executionContext = executor; + logger = executionContext.logger; + logger.debug(executor.subject.getId()); + logger.debug(executor.inFields.toString()); + final double now = (Double) (executor.inFields.get("MonitoredValue")); + final Integer iteration = (Integer) (executor.inFields.get("Iteration")); + final double[] vals = this.forecastingAndAnomaly(now); // double[forecastedValue, AnomalyScore, + // AnomalyProbability] + final double anomalyness = vals[2]; + String task = null; + for (final Map.Entry<double[], String> i : TASK_INTERVALS.entrySet()) { + if (checkInterval(anomalyness, i.getKey())) { + task = i.getValue(); + break; + } + } + if (task == null) { + executionContext.subject.getDefaultTaskKey().copyTo(executionContext.selectedTask); + } else { + executionContext.subject.getTaskKey(task).copyTo(executionContext.selectedTask); + } + if (logger.isDebugEnabled()) { + logger.debug( + "TestAnomalyDetectionTSLPolicy0000DecideStateTaskSelectionLogic.getTask():\t************\t\t\t\t" + + "Iteration:\t" + iteration + "\tValue:\t" + now + "\tForecast:\t" + vals[0] + + "\tAnomalyScore:\t" + vals[1] + "\tAnomalyProbability:\t" + vals[2] + "\tInvoking Task:\t" + + executionContext.selectedTask); + } + return true; + } + + /** + * Anomaly detection and forecast. + * + * @param value The current value + * @return Null if the function can not be executed correctly, otherwise double[forecastedValue, AnomalyScore, + * AnomalyProbability] + */ + public double[] forecastingAndAnomaly(final double value) { + try { + executionContext.getContextAlbum("AnomalyDetectionAlbum").lockForWriting("AnomalyDetection"); + } catch (final ApexException e) { + logger.error("Failed to acquire write lock on \"AnomalyDetection\" context", e); + return null; + } + + // Get the context object + AnomalyDetection anomalyDetection = + (AnomalyDetection) executionContext.getContextAlbum("AnomalyDetectionAlbum").get("AnomalyDetection"); + if (anomalyDetection == null) { + anomalyDetection = new AnomalyDetection(); + executionContext.getContextAlbum("AnomalyDetectionAlbum").put("AnomalyDetection", anomalyDetection); + } + + // Check the lists are initialized + if (!anomalyDetection.isInitialized()) { + anomalyDetection.init(FREQUENCY); + } + + boolean unsetfirstround = false; + + int frequency = anomalyDetection.getFrequency(); + frequency = frequency + 1; + + // reset frequency counter + if (frequency >= FREQUENCY) { + unsetfirstround = true; + frequency = 0; + } + anomalyDetection.setFrequency(frequency); + + if (unsetfirstround && anomalyDetection.getFirstRound()) { + anomalyDetection.setFirstRound(false); + } + + // --------- calculate the forecasted value - simple version + final Double lastForecast = anomalyDetection.getFrequencyForecasted().get(frequency); + + // get forecast for current value + final double forecastedValue = lastForecast == null ? value : expMovingAverage(value, lastForecast); + + // --------- calculate the anomalyScore + final double anomalyScore = lastForecast == null ? 0.0 : FastMath.abs(lastForecast - value); + + anomalyDetection.getFrequencyForecasted().set(frequency, forecastedValue); + + // anomaly score is ignored in the first frequency period + if (!anomalyDetection.getFirstRound()) { + ((LinkedList<Double>) anomalyDetection.getAnomalyScores()).addLast(anomalyScore); + } + + // CHECKSTYLE:OFF: checkstyle:magicNumber + // max FREQUENCY*4 anomaly scores history + listSizeControl(anomalyDetection.getAnomalyScores(), FREQUENCY * 4); + + // ---------- calculate the anomaly probability + double anomalyProbability = 0.0; + if (anomalyDetection.getAnomalyScores().size() > 30) { + // 0.5 + anomalyProbability = gStatsTest(anomalyDetection.getAnomalyScores(), ANOMALY_SENSITIVITY); + } + // CHECKSTYLE:ON: checkstyle:magicNumber + + try { + executionContext.getContextAlbum("AnomalyDetectionAlbum").unlockForWriting("AnomalyDetection"); + } catch (final ApexException e) { + logger.error("Failed to release write lock on \"AnomalyDetection\" context", e); + return null; + } + + return new double[] { forecastedValue, anomalyScore, anomalyProbability }; + } + + /** + * Is the passed value inside the interval, i.e. (value<interval[1] && value>=interval[0]) + * + * @param value The value to check + * @param interval A 2 element double array describing an interval + * @return true if the value is between interval[0] (inclusive) and interval[1] (exclusive), i.e. (value<interval[1] + * && value>=interval[0]). Otherwise false; + */ + private static boolean checkInterval(final double value, final double[] interval) { + if (interval == null || interval.length != 2) { + throw new IllegalArgumentException("something other than an interval passed to checkInterval"); + } + final double min = interval[0]; + final double max = interval[1]; + return (value < max && value >= min); + } + + /** + * calculate the anomaly probability using statistical test. + * + * @param values the values + * @param significanceLevel the significance level + * @return the double + */ + private static double gStatsTest(final List<Double> values, final double significanceLevel) { + if (isAllEqual(values)) { + return 0.0; + } + // the targeted value or the last value + final double currentV = values.get(values.size() - 1); + Double[] lValuesCopy = values.toArray(new Double[values.size()]); + Arrays.sort(lValuesCopy); // takes ~40% of method time + // if(logger.isDebugEnabled()){ + // logger.debug("values:" + Arrays.toString(lValuesCopy)); + // } + // get mean + double mean = getMean(lValuesCopy); + // get the test value: v + double v = getV(lValuesCopy, mean, true); + // get the p value for the test value + double pValue = getPValue(lValuesCopy, v, mean); // takes approx 25% of method time + // if(logger.isDebugEnabled()){ + // logger.debug("pValue:" + pValue); + // } + + // check the critical level + while (pValue < significanceLevel) { // takes approx 20% of method time + // the score value as the anomaly probability + final double score = (significanceLevel - pValue) / significanceLevel; + if (v == currentV) { + return score; + } + // do the critical check again for the left values + lValuesCopy = removevalue(lValuesCopy, v); + if (isAllEqual(lValuesCopy)) { + return 0.0; + } + // if(logger.isDebugEnabled()){ + // logger.debug("left values:" + Arrays.toString(lValuesCopy)); + // } + mean = getMean(lValuesCopy); + v = getV(lValuesCopy, mean, true); + pValue = getPValue(lValuesCopy, v, mean); + } + return 0.0; + } + + /** + * get the test value based on mean from sorted values. + * + * @param lValues the l values + * @param mean the mean + * @param maxValueOnly : only the max extreme value will be tested + * @return the value to be tested + */ + private static double getV(final Double[] lValues, final double mean, final boolean maxValueOnly) { + double v = lValues[lValues.length - 1]; + // max value as the extreme value + if (maxValueOnly) { + return v; + } + // check the extreme side + if ((v - mean) < (mean - lValues[0])) { + v = lValues[0]; + } + return v; + } + + /** + * calculate the P value for the t distribution. + * + * @param lValues the l values + * @param v the v + * @param mean the mean + * @return the p value + */ + private static double getPValue(final Double[] lValues, final double v, final double mean) { + // calculate z value + final double z = FastMath.abs(v - mean) / getStdDev(lValues, mean); + // logger.debug("z: " + z); + // calculate T + final double n = lValues.length; + final double s = (z * z * n * (2.0 - n)) / (z * z * n - (n - 1.0) * (n - 1.0)); + final double t = FastMath.sqrt(s); + // logger.debug("t:" + t); + // default p value = 0 + double pValue = 0.0; + if (!Double.isNaN(t)) { + // t distribution with n-2 degrees of freedom + final TDistribution tDist = new TDistribution(n - 2); + pValue = n * (1.0 - tDist.cumulativeProbability(t)); + // set max pValue = 1 + pValue = pValue > 1.0 ? 1.0 : pValue; + } + // logger.debug("value: "+ v + " , pValue: " + pValue); + return pValue; + } + + /* + * Some utility methods + */ + // exponential = 2(n+1) + private static final double EMA_EXPONENT = 2.0 / (7.0 + 1.0); + private static final double EMA_EXPONENT_1 = (1.0 - EMA_EXPONENT); + + /** + * exponential moving average. + * + * @param value the value + * @param lastForecast the last forecast + * @return the double + */ + private static double expMovingAverage(final double value, final double lastForecast) { + return (value * EMA_EXPONENT) + (lastForecast * EMA_EXPONENT_1); + } + + /** + * Remove the first occurence of the value v from the array. + * + * @param lValues the l values + * @param v the v + * @return the double[] + */ + private static Double[] removevalue(final Double[] lValues, final double v) { + for (int i = 0; i < lValues.length; i++) { + if (lValues[i] == v) { + final Double[] ret = new Double[lValues.length - 1]; + System.arraycopy(lValues, 0, ret, 0, i); + System.arraycopy(lValues, i + 1, ret, i, lValues.length - i - 1); + return ret; + } + } + return lValues; + } + + /** + * get mean value of double list. + * + * @param lValues the l values + * @return the mean + */ + private static double getMean(final Double[] lValues) { + double sum = 0.0; + for (final double d : lValues) { + + sum += d; + } + return sum / lValues.length; + } + + /** + * get standard deviation of double list. + * + * @param lValues the l values + * @param mean the mean + * @return stddev + */ + private static double getStdDev(final Double[] lValues, final double mean) { + double temp = 0.0; + for (final double d : lValues) { + temp += (mean - d) * (mean - d); + } + return FastMath.sqrt(temp / lValues.length); + } + + /** + * Chop head off list to make it length max . + * + * @param list the list to chop + * @param max the max size + */ + private static void listSizeControl(final List<?> list, final int max) { + final int k = list.size(); + if (k > max) { + // Chop the head off the list. + list.subList(0, k - max).clear(); + } + } + + /** + * return true if all values are equal. + * + * @param lValues the l values + * @return true, if checks if is all equal + */ + private static boolean isAllEqual(final List<Double> lValues) { + final double first = lValues.get(0); + for (final Double d : lValues) { + if (d != first) { + return false; + } + } + return true; + } + + /** + * return true if all values are equal. + * + * @param lValues the l values + * @return true, if checks if is all equal + */ + private static boolean isAllEqual(final Double[] lValues) { + final double first = lValues[0]; + for (final Double d : lValues) { + if (d != first) { + return false; + } + } + return true; + } +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicy_Decide_TaskSelectionLogic.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicy_Decide_TaskSelectionLogic.java new file mode 100644 index 000000000..23d4e2486 --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AutoLearnPolicy_Decide_TaskSelectionLogic.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.apex.examples.adaptive.model.java; + +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.onap.policy.apex.context.ContextException; +import org.onap.policy.apex.core.engine.executor.context.TaskSelectionExecutionContext; +import org.onap.policy.apex.examples.adaptive.concepts.AutoLearn; + +/** + * The Class AutoLearnPolicy_Decide_TaskSelectionLogic. + */ +// CHECKSTYLE:OFF: checkstyle:typeName +public class AutoLearnPolicy_Decide_TaskSelectionLogic { + // CHECKSTYLE:ON: checkstyle:typeName + private static final Random RAND = new Random(System.currentTimeMillis()); + private static final double WANT = 50.0; + private int size; + + /** + * Gets the task. + * + * @param executor the executor + * @return the task + */ + public boolean getTask(final TaskSelectionExecutionContext executor) { + executor.logger.debug(executor.subject.getId()); + executor.logger.debug(executor.inFields.toString()); + final List<String> tasks = executor.subject.getTaskNames(); + size = tasks.size(); + + try { + executor.getContextAlbum("AutoLearnAlbum").lockForWriting("AutoLearn"); + } catch (final ContextException e) { + executor.logger.error("Failed to acquire write lock on \"autoLearn\" context", e); + return false; + } + + // Get the context object + AutoLearn autoLearn = (AutoLearn) executor.getContextAlbum("AutoLearnAlbum").get("AutoLearn"); + if (autoLearn == null) { + autoLearn = new AutoLearn(); + } + + // Check the lists are initialized + if (!autoLearn.isInitialized()) { + autoLearn.init(size); + } + + final double now = (Double) (executor.inFields.get("MonitoredValue")); + final double diff = now - WANT; + final int option = getOption(diff, autoLearn); + learn(option, diff, autoLearn); + + executor.getContextAlbum("AutoLearnAlbum").put("AutoLearnAlbum", autoLearn); + + try { + executor.getContextAlbum("AutoLearnAlbum").unlockForWriting("AutoLearn"); + } catch (final ContextException e) { + executor.logger.error("Failed to acquire write lock on \"autoLearn\" context", e); + return false; + } + + executor.subject.getTaskKey(tasks.get(option)).copyTo(executor.selectedTask); + return true; + } + + /** + * Gets the option. + * + * @param diff the diff + * @param autoLearn the auto learn + * @return the option + */ + private int getOption(final double diff, final AutoLearn autoLearn) { + final Double[] avdiffs = autoLearn.getAvDiffs().toArray(new Double[autoLearn.getAvDiffs().size()]); + final int r = RAND.nextInt(size); + int closestupi = -1; + int closestdowni = -1; + double closestup = Double.MAX_VALUE; + double closestdown = Double.MIN_VALUE; + for (int i = 0; i < size; i++) { + if (Double.isNaN(avdiffs[i])) { + return r; + } + if (avdiffs[i] >= diff && avdiffs[i] <= closestup) { + closestup = avdiffs[i]; + closestupi = i; + } + if (avdiffs[i] <= diff && avdiffs[i] >= closestdown) { + closestdown = avdiffs[i]; + closestdowni = i; + } + } + if (closestupi == -1 || closestdowni == -1) { + return r; + } + if (closestupi == closestdowni) { + return closestupi; + } + if (Math.abs(closestdown - diff) > Math.abs(closestup - diff)) { + return closestupi; + } else { + return closestdowni; + } + } + + /** + * Learn. + * + * @param option the option + * @param diff the diff + * @param autoLearn the auto learn + */ + private void learn(final int option, final double diff, final AutoLearn autoLearn) { + final Double[] avdiffs = autoLearn.getAvDiffs().toArray(new Double[autoLearn.getAvDiffs().size()]); + final Long[] counts = autoLearn.getCounts().toArray(new Long[autoLearn.getCounts().size()]); + if (option < 0 || option >= avdiffs.length) { + throw new IllegalArgumentException("Error: option" + option); + } + counts[option]++; + if (Double.isNaN(avdiffs[option])) { + avdiffs[option] = diff; + } else { + avdiffs[option] = (avdiffs[option] * (counts[option] - 1) + diff) / counts[option]; + } + autoLearn.setAvDiffs(Arrays.asList(avdiffs)); + autoLearn.setCounts(Arrays.asList(counts)); + } +} diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/package-info.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/package-info.java new file mode 100644 index 000000000..172be5ada --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Pprovides task selection logic for the adaptive domain in Java. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +package org.onap.policy.apex.examples.adaptive.model.java; diff --git a/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/package-info.java b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/package-info.java new file mode 100644 index 000000000..d38333ba8 --- /dev/null +++ b/examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2016-2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +/** + * Provides Java generation of the Adaptive model as well as Java task selection logic for the domain. + * + * @author Liam Fallon (liam.fallon@ericsson.com) + */ + +package org.onap.policy.apex.examples.adaptive.model; |