Adding examples module to apex-pdp
[policy/apex-pdp.git] / examples / adaptive / src / test / java / org / onap / policy / apex / examples / adaptive / TestAutoLearnTSLUseCase.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.examples.adaptive;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26
27 import java.io.IOException;
28 import java.util.Random;
29
30 import org.junit.Test;
31 import org.onap.policy.apex.core.engine.EngineParameters;
32 import org.onap.policy.apex.core.engine.engine.ApexEngine;
33 import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory;
34 import org.onap.policy.apex.core.engine.event.EnEvent;
35 import org.onap.policy.apex.examples.adaptive.model.AdaptiveDomainModelFactory;
36 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
37 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
38 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
39 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
40 import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters;
41 import org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters;
42 import org.slf4j.ext.XLogger;
43 import org.slf4j.ext.XLoggerFactory;
44
45 /**
46  * Test Auto learning in TSL.
47  *
48  * @author John Keeney (John.Keeney@ericsson.com)
49  */
50 public class TestAutoLearnTSLUseCase {
51     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestAutoLearnTSLUseCase.class);
52
53     private static final int MAXITERATIONS = 1000;
54     private static final Random rand = new Random(System.currentTimeMillis());
55
56     @Test
57     // once through the long running test below
58     public void TestAutoLearnTSL() throws ApexException, InterruptedException, IOException {
59         final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel();
60         assertNotNull(apexPolicyModel);
61
62         final AxValidationResult validationResult = new AxValidationResult();
63         apexPolicyModel.validate(validationResult);
64         assertTrue(validationResult.isValid());
65
66         final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1");
67         final EngineParameters parameters = new EngineParameters();
68         parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters());
69         parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters());
70
71         final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key);
72
73         final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
74         apexEngine1.addEventListener("listener", listener1);
75         apexEngine1.updateModel(apexPolicyModel);
76         apexEngine1.start();
77         final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"));
78         final double rval = rand.nextGaussian();
79         triggerEvent.put("MonitoredValue", rval);
80         triggerEvent.put("LastMonitoredValue", 0D);
81         LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent);
82         apexEngine1.handleEvent(triggerEvent);
83         final EnEvent result = listener1.getResult();
84         LOGGER.info("Receiving action event {} ", result);
85         assertEquals("ExecutionIDs are different", triggerEvent.getExecutionID(), result.getExecutionID());
86         triggerEvent.clear();
87         result.clear();
88         Thread.sleep(1);
89         apexEngine1.stop();
90     }
91
92     /**
93      * This policy passes, and receives a Double event context filed called "EVCDouble"<br>
94      * The policy tries to keep the value at 50, with a Min -100, Max 100 (These should probably be set using
95      * TaskParameters!)<br>
96      * The policy has 7 Decide Tasks that manipulate the value of this field in unknown ways.<br>
97      * The Decide TSL learns the effect of each task, and then selects the appropriate task to get the value back to
98      * 50<br>
99      * After the value settles close to 50 for a while, the test Rests the value to to random number and then
100      * continues<br>
101      * To plot the results grep stdout debug results for the string "*******", paste into excel and delete non-relevant
102      * columns<br>
103      *
104      * @throws ApexException the apex exception
105      * @throws InterruptedException the interrupted exception
106      * @throws IOException Signals that an I/O exception has occurred.
107      */
108     // @Test
109     public void TestAutoLearnTSL_main() throws ApexException, InterruptedException, IOException {
110
111         final double WANT = 50.0;
112         final double toleranceTileJump = 3.0;
113
114         final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel();
115         assertNotNull(apexPolicyModel);
116
117         final AxValidationResult validationResult = new AxValidationResult();
118         apexPolicyModel.validate(validationResult);
119         assertTrue(validationResult.isValid());
120
121         final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1");
122         final EngineParameters parameters = new EngineParameters();
123         parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters());
124         parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters());
125
126         final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key);
127
128         final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
129         apexEngine1.addEventListener("listener1", listener1);
130         apexEngine1.updateModel(apexPolicyModel);
131         apexEngine1.start();
132
133         final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"));
134         assertNotNull(triggerEvent);
135         final double MIN = -100;
136         final double MAX = 100;
137
138         double rval = (((rand.nextGaussian() + 1) / 2) * (MAX - MIN)) + MIN;
139         triggerEvent.put("MonitoredValue", rval);
140         triggerEvent.put("LastMonitoredValue", 0);
141
142         double avval = 0;
143         double distance;
144         double avcount = 0;
145
146         for (int iteration = 0; iteration < MAXITERATIONS; iteration++) {
147             // Trigger the policy in engine 1
148             LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent);
149             apexEngine1.handleEvent(triggerEvent);
150             final EnEvent result = listener1.getResult();
151             LOGGER.info("Receiving action event {} ", result);
152             triggerEvent.clear();
153
154             double val = (Double) result.get("MonitoredValue");
155             final double prevval = (Double) result.get("LastMonitoredValue");
156
157             triggerEvent.put("MonitoredValue", prevval);
158             triggerEvent.put("LastMonitoredValue", val);
159
160             avcount = Math.min((avcount + 1), 20); // maintain average of only the last 20 values
161             avval = ((avval * (avcount - 1)) + val) / (avcount);
162
163             distance = Math.abs(WANT - avval);
164             if (distance < toleranceTileJump) {
165                 rval = (((rand.nextGaussian() + 1) / 2) * (MAX - MIN)) + MIN;
166                 val = rval;
167                 triggerEvent.put("MonitoredValue", val);
168                 LOGGER.info("Iteration " + iteration + ": Average " + avval + " has become closer (" + distance
169                         + ") than " + toleranceTileJump + " to " + WANT + " so reseting val:\t\t\t\t\t\t\t\t" + val);
170                 avval = 0;
171                 avcount = 0;
172             }
173             LOGGER.info("Iteration " + iteration + ": \tpreval\t" + prevval + "\tval\t" + val + "\tavval\t" + avval);
174
175             result.clear();
176             Thread.sleep(1);
177         }
178
179         apexEngine1.stop();
180         Thread.sleep(1000);
181
182     }
183
184     public static void main(final String[] args) throws ApexException, InterruptedException, IOException {
185         new TestAutoLearnTSLUseCase().TestAutoLearnTSL_main();
186     }
187 }