Merge "Fix checkstyle issues in apex model basic"
[policy/apex-pdp.git] / examples / 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.After;
31 import org.junit.Before;
32 import org.junit.Test;
33 import org.onap.policy.apex.context.impl.schema.java.JavaSchemaHelperParameters;
34 import org.onap.policy.apex.context.parameters.ContextParameterConstants;
35 import org.onap.policy.apex.context.parameters.ContextParameters;
36 import org.onap.policy.apex.context.parameters.SchemaParameters;
37 import org.onap.policy.apex.core.engine.EngineParameters;
38 import org.onap.policy.apex.core.engine.engine.ApexEngine;
39 import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory;
40 import org.onap.policy.apex.core.engine.event.EnEvent;
41 import org.onap.policy.apex.examples.adaptive.model.AdaptiveDomainModelFactory;
42 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
43 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
44 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
45 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
46 import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters;
47 import org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters;
48 import org.onap.policy.common.parameters.ParameterService;
49 import org.slf4j.ext.XLogger;
50 import org.slf4j.ext.XLoggerFactory;
51
52 /**
53  * Test Auto learning in TSL.
54  *
55  * @author John Keeney (John.Keeney@ericsson.com)
56  */
57 public class TestAutoLearnTSLUseCase {
58     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestAutoLearnTSLUseCase.class);
59
60     private static final int MAXITERATIONS = 1000;
61     private static final Random rand = new Random(System.currentTimeMillis());
62
63     private SchemaParameters schemaParameters;
64     private ContextParameters contextParameters;
65     private EngineParameters engineParameters;
66
67     @Before
68     public void beforeTest() {
69         schemaParameters = new SchemaParameters();
70         
71         schemaParameters.setName(ContextParameterConstants.SCHEMA_GROUP_NAME);
72         schemaParameters.getSchemaHelperParameterMap().put("JAVA", new JavaSchemaHelperParameters());
73
74         ParameterService.register(schemaParameters);
75         
76         contextParameters = new ContextParameters();
77
78         contextParameters.setName(ContextParameterConstants.MAIN_GROUP_NAME);
79         contextParameters.getDistributorParameters().setName(ContextParameterConstants.DISTRIBUTOR_GROUP_NAME);
80         contextParameters.getLockManagerParameters().setName(ContextParameterConstants.LOCKING_GROUP_NAME);
81         contextParameters.getPersistorParameters().setName(ContextParameterConstants.PERSISTENCE_GROUP_NAME);
82
83         ParameterService.register(contextParameters);
84         ParameterService.register(contextParameters.getDistributorParameters());
85         ParameterService.register(contextParameters.getLockManagerParameters());
86         ParameterService.register(contextParameters.getPersistorParameters());
87         
88         engineParameters = new EngineParameters();
89         engineParameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters());
90         engineParameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters());
91         ParameterService.register(engineParameters);
92     }
93
94     @After
95     public void afterTest() {
96         ParameterService.deregister(engineParameters);
97         
98         ParameterService.deregister(contextParameters.getDistributorParameters());
99         ParameterService.deregister(contextParameters.getLockManagerParameters());
100         ParameterService.deregister(contextParameters.getPersistorParameters());
101         ParameterService.deregister(contextParameters);
102
103         ParameterService.deregister(schemaParameters);
104     }
105
106     @Test
107     // once through the long running test below
108     public void TestAutoLearnTSL() throws ApexException, InterruptedException, IOException {
109         final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel();
110         assertNotNull(apexPolicyModel);
111
112         final AxValidationResult validationResult = new AxValidationResult();
113         apexPolicyModel.validate(validationResult);
114         assertTrue(validationResult.isValid());
115
116         final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1");
117
118         final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key);
119
120         final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
121         apexEngine1.addEventListener("listener", listener1);
122         apexEngine1.updateModel(apexPolicyModel);
123         apexEngine1.start();
124         final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"));
125         final double rval = rand.nextGaussian();
126         triggerEvent.put("MonitoredValue", rval);
127         triggerEvent.put("LastMonitoredValue", 0D);
128         LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent);
129         apexEngine1.handleEvent(triggerEvent);
130         final EnEvent result = listener1.getResult();
131         LOGGER.info("Receiving action event {} ", result);
132         assertEquals("ExecutionIDs are different", triggerEvent.getExecutionID(), result.getExecutionID());
133         triggerEvent.clear();
134         result.clear();
135         Thread.sleep(1);
136         apexEngine1.stop();
137     }
138
139     /**
140      * This policy passes, and receives a Double event context filed called "EVCDouble"<br>
141      * The policy tries to keep the value at 50, with a Min -100, Max 100 (These should probably be set using
142      * TaskParameters!)<br>
143      * The policy has 7 Decide Tasks that manipulate the value of this field in unknown ways.<br>
144      * The Decide TSL learns the effect of each task, and then selects the appropriate task to get the value back to
145      * 50<br>
146      * After the value settles close to 50 for a while, the test Rests the value to to random number and then
147      * continues<br>
148      * To plot the results grep stdout debug results for the string "*******", paste into excel and delete non-relevant
149      * columns<br>
150      *
151      * @throws ApexException the apex exception
152      * @throws InterruptedException the interrupted exception
153      * @throws IOException Signals that an I/O exception has occurred.
154      */
155     // @Test
156     public void TestAutoLearnTSL_main() throws ApexException, InterruptedException, IOException {
157
158         final double WANT = 50.0;
159         final double toleranceTileJump = 3.0;
160
161         final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAutoLearnPolicyModel();
162         assertNotNull(apexPolicyModel);
163
164         final AxValidationResult validationResult = new AxValidationResult();
165         apexPolicyModel.validate(validationResult);
166         assertTrue(validationResult.isValid());
167
168         final AxArtifactKey key = new AxArtifactKey("AADMApexEngine", "0.0.1");
169         final EngineParameters parameters = new EngineParameters();
170         parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters());
171         parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters());
172
173         final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key);
174
175         final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
176         apexEngine1.addEventListener("listener1", listener1);
177         apexEngine1.updateModel(apexPolicyModel);
178         apexEngine1.start();
179
180         final EnEvent triggerEvent = apexEngine1.createEvent(new AxArtifactKey("AutoLearnTriggerEvent", "0.0.1"));
181         assertNotNull(triggerEvent);
182         final double MIN = -100;
183         final double MAX = 100;
184
185         double rval = (((rand.nextGaussian() + 1) / 2) * (MAX - MIN)) + MIN;
186         triggerEvent.put("MonitoredValue", rval);
187         triggerEvent.put("LastMonitoredValue", 0);
188
189         double avval = 0;
190         double distance;
191         double avcount = 0;
192
193         for (int iteration = 0; iteration < MAXITERATIONS; iteration++) {
194             // Trigger the policy in engine 1
195             LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent);
196             apexEngine1.handleEvent(triggerEvent);
197             final EnEvent result = listener1.getResult();
198             LOGGER.info("Receiving action event {} ", result);
199             triggerEvent.clear();
200
201             double val = (Double) result.get("MonitoredValue");
202             final double prevval = (Double) result.get("LastMonitoredValue");
203
204             triggerEvent.put("MonitoredValue", prevval);
205             triggerEvent.put("LastMonitoredValue", val);
206
207             avcount = Math.min((avcount + 1), 20); // maintain average of only the last 20 values
208             avval = ((avval * (avcount - 1)) + val) / (avcount);
209
210             distance = Math.abs(WANT - avval);
211             if (distance < toleranceTileJump) {
212                 rval = (((rand.nextGaussian() + 1) / 2) * (MAX - MIN)) + MIN;
213                 val = rval;
214                 triggerEvent.put("MonitoredValue", val);
215                 LOGGER.info("Iteration " + iteration + ": Average " + avval + " has become closer (" + distance
216                         + ") than " + toleranceTileJump + " to " + WANT + " so reseting val:\t\t\t\t\t\t\t\t" + val);
217                 avval = 0;
218                 avcount = 0;
219             }
220             LOGGER.info("Iteration " + iteration + ": \tpreval\t" + prevval + "\tval\t" + val + "\tavval\t" + avval);
221
222             result.clear();
223             Thread.sleep(1);
224         }
225
226         apexEngine1.stop();
227         Thread.sleep(1000);
228
229     }
230
231     public static void main(final String[] args) throws ApexException, InterruptedException, IOException {
232         new TestAutoLearnTSLUseCase().TestAutoLearnTSL_main();
233     }
234 }