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