Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

PMML : disable, enable and remove models from a session

PMML : fixed questionnaire generation
  • Loading branch information...
commit 2349bbb5b608e70c81fc9591fddb2810d929538b 1 parent 5fb4331
@sotty sotty authored
Showing with 1,785 additions and 703 deletions.
  1. +22 −12 drools-pmml/src/main/java/org/drools/pmml_4_0/ModelMarker.java
  2. +43 −8 drools-pmml/src/main/java/org/drools/pmml_4_0/PMML4Compiler.java
  3. +10 −6 drools-pmml/src/main/resources/org/drools/pmml_4_0/pmml_compiler.drl
  4. +144 −32 drools-pmml/src/main/resources/org/drools/pmml_4_0/pmml_informer.drl
  5. +34 −0 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/global/commonQueries.drlt
  6. +5 −5 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/global/dataDefinition/inputFromEP.drlt
  7. +14 −5 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/global/modelMark.drlt
  8. +7 −6 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelAddQuestionsToQuestionnaire.drlt
  9. +6 −6 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelCreateByBinding.drlt
  10. +0 −2  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelInvalidAnswer.drlt
  11. +23 −8 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelMultiQuestion.drlt
  12. +6 −6 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelOutputBinding.drlt
  13. +19 −6 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestion.drlt
  14. +17 −11 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestionBinding.drlt
  15. +7 −4 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestionRebinding.drlt
  16. +29 −9 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestionnaire.drlt
  17. +7 −6 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelRevalidate.drlt
  18. +2 −2 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/clustering/clusteringInit.drlt
  19. +2 −1  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/clustering/clusteringMatrixCompare.drlt
  20. +1 −1  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/neural/neuralBuildSynapses.drlt
  21. +5 −5 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/regression/regDeclare.drlt
  22. +10 −10 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/regression/regParams.drlt
  23. +1 −1  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/svm/svmBuild.drlt
  24. +3 −1 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/svm/svmInitSupportVector.drlt
  25. +1 −1  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/svm/svmParams.drlt
  26. +1 −1  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/tree/treeInit.drlt
  27. +181 −55 drools-pmml/src/test/java/org/drools/pmml_4_0/informer/QuestionnaireTest.java
  28. +445 −0 drools-pmml/src/test/java/org/drools/pmml_4_0/predictive/models/CleanupTest.java
  29. +238 −5 drools-pmml/src/test/java/org/drools/pmml_4_0/predictive/models/MultipleModelTest.java
  30. +7 −4 drools-pmml/src/test/java/org/drools/pmml_4_0/predictive/models/NeuralNetworkTest.java
  31. +3 −1 drools-pmml/src/test/java/org/drools/pmml_4_0/predictive/models/SimpleRegressionTest.java
  32. +134 −132 drools-pmml/src/test/resources/org/drools/pmml_4_0/mock_breastcancer.pmml
  33. +42 −42 drools-pmml/src/test/resources/org/drools/pmml_4_0/mock_cold.pmml
  34. +122 −120 drools-pmml/src/test/resources/org/drools/pmml_4_0/mock_ptsd.pmml
  35. +114 −113 drools-pmml/src/test/resources/org/drools/pmml_4_0/test_ann_iris_prediction.xml
  36. +4 −2 drools-pmml/src/test/resources/org/drools/pmml_4_0/test_ann_mixed_inputs.xml
  37. +76 −74 drools-pmml/src/test/resources/org/drools/pmml_4_0/test_miningSchema.xml
View
34 drools-pmml/src/main/java/org/drools/pmml_4_0/ModelMarker.java
@@ -28,8 +28,10 @@
private String modelClass;
@Position(2)
- private String modelUrl;
+ private boolean enabled = true;
+ @Position(3)
+ private String modelUrl;
public ModelMarker() { }
@@ -63,6 +65,24 @@ public void setModelUrl(String modelUrl) {
this.modelUrl = modelUrl;
}
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ @Override
+ public String toString() {
+ return "ModelMarker{" +
+ "modelName='" + modelName + '\'' +
+ ", modelClass='" + modelClass + '\'' +
+ ", enabled=" + enabled +
+ ", modelUrl='" + modelUrl + '\'' +
+ '}';
+ }
+
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -70,7 +90,6 @@ public boolean equals(Object o) {
ModelMarker that = (ModelMarker) o;
- if (modelClass != null ? !modelClass.equals(that.modelClass) : that.modelClass != null) return false;
if (modelName != null ? !modelName.equals(that.modelName) : that.modelName != null) return false;
return true;
@@ -78,16 +97,7 @@ public boolean equals(Object o) {
@Override
public int hashCode() {
- int result = modelName != null ? modelName.hashCode() : 0;
- result = 31 * result + (modelClass != null ? modelClass.hashCode() : 0);
- return result;
+ return modelName != null ? modelName.hashCode() : 0;
}
- public String toString() {
- return "ModelMarker{" +
- ", modelName=" + modelName +
- ", modelClass='" + modelClass + '\'' +
- ", modelUrl='" + modelUrl + '\'' +
- '}';
- }
}
View
51 drools-pmml/src/main/java/org/drools/pmml_4_0/PMML4Compiler.java
@@ -62,6 +62,7 @@
protected static final String[] GLOBAL_TEMPLATES = new String[] {
"global/pmml_header.drlt",
"global/modelMark.drlt",
+ "global/commonQueries.drlt",
"global/dataDefinition/common.drlt",
"global/dataDefinition/rootDataField.drlt",
@@ -356,15 +357,49 @@ private static void checkBuildingResources( PMML pmml ) {
}
}
-
- for ( Extension x : pmml.getExtensions() ) {
- for ( Object c : x.getContent() ) {
- if ( ! informerLoaded && c instanceof Element && ((Element) c).getTagName().equals( "Surveyable" ) ) {
- for ( String ntempl : INFORMER_TEMPLATES ) {
- prepareTemplate( ntempl );
+ for ( Object o : pmml.getAssociationModelsAndClusteringModelsAndGeneralRegressionModels() ) {
+ List inner;
+ if ( o instanceof NeuralNetwork ) {
+ inner = ((NeuralNetwork) o).getExtensionsAndNeuralLayersAndNeuralInputs();
+ } else if ( o instanceof MiningModel ) {
+ inner = ((MiningModel) o).getExtensionsAndMiningSchemasAndOutputs();
+ } else if ( o instanceof ClusteringModel ) {
+ inner = ((ClusteringModel) o).getExtensionsAndClustersAndComparisonMeasures();
+ } else if ( o instanceof AssociationModel ) {
+ inner = ((AssociationModel) o).getExtensionsAndMiningSchemasAndOutputs();
+ } else if ( o instanceof SupportVectorMachineModel ) {
+ inner = ((SupportVectorMachineModel) o).getExtensionsAndSupportVectorMachinesAndVectorDictionaries();
+ } else if ( o instanceof RegressionModel ) {
+ inner = ((RegressionModel) o).getExtensionsAndRegressionTablesAndMiningSchemas();
+ } else if ( o instanceof NaiveBayesModel ) {
+ inner = ((NaiveBayesModel) o).getExtensionsAndBayesOutputsAndBayesInputs();
+ } else if ( o instanceof TextModel ) {
+ inner = ((TextModel) o).getExtensionsAndDocumentTermMatrixesAndTextCorpuses();
+ } else if ( o instanceof SequenceModel ) {
+ inner = ((SequenceModel) o).getExtensionsAndSequencesAndMiningSchemas();
+ } else if ( o instanceof GeneralRegressionModel ) {
+ inner = ((GeneralRegressionModel) o).getExtensionsAndParamMatrixesAndPPMatrixes();
+ } else if ( o instanceof RuleSetModel ) {
+ inner = ((RuleSetModel) o).getExtensionsAndRuleSetsAndMiningSchemas();
+ } else if ( o instanceof TimeSeriesModel ) {
+ inner = ((TimeSeriesModel) o).getExtensionsAndMiningSchemasAndOutputs();
+ } else if ( o instanceof TreeModel ) {
+ inner = ((TreeModel) o).getExtensionsAndNodesAndMiningSchemas();
+ } else {
+ //should not happen
+ inner = Collections.emptyList();
+ }
+ for ( Object p : inner ) {
+ if ( p instanceof Extension ) {
+ Extension x = (Extension) p;
+ for ( Object c : x.getContent() ) {
+ if ( ! informerLoaded && c instanceof Element && ((Element) c).getTagName().equals( "Surveyable" ) ) {
+ for ( String ntempl : INFORMER_TEMPLATES ) {
+ prepareTemplate( ntempl );
+ }
+ informerLoaded = true;
+ }
}
- informerLoaded = true;
-
}
}
}
View
16 drools-pmml/src/main/resources/org/drools/pmml_4_0/pmml_compiler.drl
@@ -18,6 +18,7 @@ package org.drools.pmml_4_0.compiler;
import org.drools.pmml_4_0.descr.*;
import org.drools.pmml_4_0.ModelMarker;
import org.mvel2.templates.*;
+import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
@@ -96,10 +97,13 @@ salience 9999
when
$h : Header()
then
- HashMap map = new HashMap(7);
- map.put("pack",utils.getPack());
- applyTemplate("pmml_header.drlt", $h, registry, map, theory);
- retract($h);
+ HashMap map = new HashMap( 3 );
+ map.put( "pack", utils.getPack() );
+ applyTemplate( "pmml_header.drlt", $h, registry, map, theory );
+
+ applyTemplate( "commonQueries.drlt", $h, registry, map, theory );
+
+ retract( $h );
end
@@ -133,7 +137,7 @@ when
eval( ! utils.isModelBeanDefined("DataField") )
then
utils.addModelBeanDefinition("DataField");
- applyTemplate("rootDataField.drlt", utils, registry, new HashMap(), theory);
+ applyTemplate("rootDataField.drlt", utils, registry, Collections.emptyMap(), theory);
end
@@ -183,7 +187,7 @@ when
Value( property != "invalid", property != "missing" ) from $vals
)
then
- HashMap map = new HashMap( 7 );
+ HashMap map = new HashMap( 11 );
map.put( "context", utils.context );
map.put( "fullName", $fld.displayName );
map.put( "name", utils.compactUpperCase( $fld.name ) );
View
176 drools-pmml/src/main/resources/org/drools/pmml_4_0/pmml_informer.drl
@@ -30,41 +30,153 @@ global Map fld2var;
global org.drools.pmml_4_0.PMML4Wrapper utils;
-declare EnableSurvey end
+declare EnableSurvey
+ modelName : String @key
+end
+
+
+rule "Enable Survey in Neural Networks"
+when
+ NeuralNetwork( $name : modelName, $exts : extensionsAndNeuralLayersAndNeuralInputs )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Mining Models"
+when
+ MiningModel( $name : modelName, $exts : extensionsAndMiningSchemasAndOutputs )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Clustering Models"
+when
+ ClusteringModel( $name : modelName, $exts : extensionsAndClustersAndComparisonMeasures )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Association Models"
+when
+ AssociationModel( $name : modelName, $exts : extensionsAndMiningSchemasAndOutputs )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in SVM"
+when
+ SupportVectorMachineModel( $name : modelName, $exts : extensionsAndSupportVectorMachinesAndVectorDictionaries )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Regression Models"
+when
+ RegressionModel( $name : modelName, $exts : extensionsAndRegressionTablesAndMiningSchemas )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Naive Bayes Models"
+when
+ NaiveBayesModel( $name : modelName, $exts : extensionsAndBayesOutputsAndBayesInputs )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Text Models"
+when
+ TextModel( $name : modelName, $exts : extensionsAndDocumentTermMatrixesAndTextCorpuses )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
-rule "Enable Survey"
+rule "Enable Survey in Sequence Models"
when
- PMML( $exts : extensions )
+ SequenceModel( $name : modelName, $exts : extensionsAndSequencesAndMiningSchemas )
$ext : Extension( $x : content ) from $exts
$o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
then
- insertLogical( new EnableSurvey() );
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
end
+rule "Enable Survey in Generalized Regression Models"
+when
+ GeneralRegressionModel( $name : modelName, $exts : extensionsAndParamMatrixesAndPPMatrixes )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in RuleSet Models"
+when
+ RuleSetModel( $name : modelName, $exts : extensionsAndRuleSetsAndMiningSchemas )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Time Series Models"
+when
+ TimeSeriesModel( $name : modelName, $exts : extensionsAndMiningSchemasAndOutputs )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+rule "Enable Survey in Tree Models"
+when
+ TreeModel( $name : modelName, $exts : extensionsAndNodesAndMiningSchemas )
+ $ext : Extension( $x : content ) from $exts
+ $o : org.w3c.dom.Element( tagName == "Surveyable" ) from $x
+then
+ insertLogical( new EnableSurvey( utils.compactUpperCase( $name ) ) );
+end
+
+
+
+
rule "Invalid_meta"
-salience -999
dialect "mvel"
when
- EnableSurvey()
+ exists EnableSurvey()
then
//System.err.println("Found Mined Field " + $fld.name );
- HashMap map = new HashMap();
- applyTemplate( "modelInvalidAnswer.drlt", utils, registry, map, theory );
- applyTemplate( "modelRevalidate.drlt", utils, registry, map, theory );
+ applyTemplate( "modelInvalidAnswer.drlt", utils, registry, java.util.Collections.emptyMap(), theory );
+ applyTemplate( "modelRevalidate.drlt", utils, registry, java.util.Collections.emptyMap(), theory );
end
rule "Questionnaire"
dialect "mvel"
when
- EnableSurvey()
+ EnableSurvey( $model : modelName )
MiningSchema( $inputs : miningFields )
then
//System.err.println("Found Mined Field " + $fld.name );
- HashMap map = new HashMap();
- map.put("fields",$inputs);
- map.put("model",utils.context);
+ HashMap map = new HashMap( 3 );
+ map.put( "fields", $inputs );
+ map.put( "model", $model );
applyTemplate( "modelQuestionnaire.drlt", utils, registry, map, theory );
applyTemplate( "modelAddQuestionsToQuestionnaire.drlt", utils, registry, map, theory );
@@ -78,19 +190,19 @@ end
rule "Question"
dialect "java"
when
- EnableSurvey()
+ EnableSurvey( $model : modelName )
MiningSchema( $inputs : miningFields )
$fld : MiningField( this memberOf $inputs, $name : name, usageType == null || usageType == FIELDUSAGETYPE.ACTIVE )
TypeOfField( name == $name, $type : dataType )
$dfld : DataField( $vsize : values.size() == 0, name == $name, $full : displayName )
then
- String fullS = ""+$full; //avoiding obscure MVEL problem in choosing between overloaded versions of format() in PMML4Wrapper
- HashMap map = new HashMap();
+// String fullS = ""+$full; //avoiding obscure MVEL problem in choosing between overloaded versions of format() in PMML4Wrapper
+ HashMap map = new HashMap( 5 );
map.put( "name", utils.compactUpperCase( $name ) );
- map.put( "displayName", fullS );
- map.put( "model", utils.context );
+ map.put( "displayName", $full );
+ map.put( "model", $model );
map.put( "dataType", $type );
- System.out.println( map );
+// System.out.println( map );
applyTemplate( "modelQuestion.drlt", utils, registry, map, theory );
applyTemplate( "modelQuestionBinding.drlt", utils, registry, map, theory );
applyTemplate( "modelQuestionRebinding.drlt", utils, registry, map, theory );
@@ -101,7 +213,7 @@ end
rule "Question_Multi"
dialect "java"
when
- EnableSurvey()
+ EnableSurvey( $model : modelName )
MiningSchema( $inputs : miningFields )
$fld : MiningField( this memberOf $inputs, $name : name, usageType == null || usageType == FIELDUSAGETYPE.ACTIVE )
TypeOfField( name == $name, $type : dataType )
@@ -113,10 +225,10 @@ when
)
then
- HashMap map = new HashMap();
+ HashMap map = new HashMap( 7 );
map.put( "name", utils.compactUpperCase( $name ) );
- map.put( "fullName", $full );
- map.put( "model", utils.context );
+ map.put( "displayName", $full );
+ map.put( "model", $model );
map.put( "dataType", $type );
map.put( "valid", $validz );
map.put( "invalid", new java.util.ArrayList() );
@@ -135,16 +247,16 @@ end
rule "Output_Predicted_AsNotes"
when
- EnableSurvey()
+ EnableSurvey( $model : modelName )
MiningSchema( $inputs : miningFields )
$fld : MiningField( this memberOf $inputs, $name : name, usageType == FIELDUSAGETYPE.PREDICTED )
// TypeOfField( name == $name, $type : dataType )
$dfld : DataField( name == $name, $full : displayName )
then
- HashMap map = new HashMap();
+ HashMap map = new HashMap( 5 );
map.put( "name", utils.compactUpperCase( $name ) );
map.put( "fullName", $full );
- map.put( "model", utils.context );
+ map.put( "model", $model );
map.put( "outType"," Predicted" );
// map.put("dataType",$type);
applyTemplate( "modelOutputBinding.drlt", utils, registry, map, theory );
@@ -154,14 +266,14 @@ end
rule "Outputs_AsNotes_Data"
when
- EnableSurvey()
+ EnableSurvey( $model : modelName )
OutputField( $name : name, $tgt : targetField )
$dfld : DataField( name == $tgt, $full : displayName )
then
- HashMap map = new HashMap();
+ HashMap map = new HashMap( 5 );
map.put( "name", utils.compactUpperCase( $name ) );
map.put( "fullName", $full );
- map.put( "model", utils.context );
+ map.put( "model", $model );
map.put( "outType", "Out" );
// map.put("dataType",$type);
applyTemplate( "modelOutputBinding.drlt", utils, registry, map, theory );
@@ -171,15 +283,15 @@ end
rule "Outputs_AsNotes_Derived"
when
- EnableSurvey()
+ EnableSurvey( $model : modelName )
OutputField( $name : name, $tgt : targetField )
$dfld : DerivedField( name == $tgt, $full : displayName )
not DataField( name == $tgt )
then
- HashMap map = new HashMap();
+ HashMap map = new HashMap( 5 );
map.put( "name",utils.compactUpperCase( $name ) );
map.put( "fullName", $full );
- map.put( "model", utils.context );
+ map.put( "model", $model );
map.put( "outType", "Out" );
// map.put("dataType",$type);
applyTemplate( "modelOutputBinding.drlt", utils, registry, map, theory );
View
34 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/global/commonQueries.drlt
@@ -0,0 +1,34 @@
+@comment{
+
+ Copyright 2011 JBoss Inc
+
+ 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.
+}
+
+
+@comment{
+
+}
+
+@declare{'commonQueries'}
+
+
+query modelMarker( String $model, ModelMarker $mm )
+ $mm := ModelMarker( $model ; )
+end
+
+
+@end{}
+
+
+@includeNamed{'commonQueries'}
View
10 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/global/dataDefinition/inputFromEP.drlt
@@ -44,9 +44,9 @@ then
input.setMissing(false);
input.setValid(@{notRestricted});
input.setContext(null);
- System.err.println("Rule " + drools.getRule().getName() + " for input " + $in + " : will insert " + input.toString());
- retract($in);
- insert(input);
+ //System.out.println("Rule " + drools.getRule().getName() + " for input " + $in + " : will insert " + input.toString());
+ retract( $in );
+ insert( input );
end
@@ -56,8 +56,8 @@ when
$new: @{box(type)}() from entry-point "in_@{name}"
$old: @{name}( value != $new )
then
- System.err.println(" Overriding previous values " + $old );
- retract($old);
+ //System.out.println(" Overriding previous values " + $old + " because of " + $new );
+ retract( $old );
end
@end{}
View
19 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/global/modelMark.drlt
@@ -18,16 +18,25 @@
@declare{'modelMarkRule'}
rule "Mark_@{name}"
-salience -9999
+salience 9999
+no-loop
when
- not ModelMarker( "@{name}" ; )
+// not ModelMarker( "@{name}" ; )
then
+// System.out.println( "Marking @{name}" );
ModelMarker mark = new ModelMarker( "@{name}", "@{type}" );
- insert( mark );
+ insertLogical( mark );
end
-query modelMarker( String $model, ModelMarker $mm )
- $mm := ModelMarker( $model ; )
+rule "Enable/Disable Model"
+when
+ $flag : Boolean() from entry-point "enable_@{name}"
+ $mark : ModelMarker( modelName == "@{name}", enabled != $flag )
+then
+ retract( $flag );
+ modify ( $mark ) {
+ setEnabled( $flag );
+ }
end
@end{}
View
13 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelAddQuestionsToQuestionnaire.drlt
@@ -17,15 +17,16 @@
@declare{'modelAddQuestionsToQuestionnaireRule'}
-rule "Assignment"
-no-loop
-salience -100
+rule "Assignment - @{model}"
when
- $questionnaire : Questionnaire( $ctx : context == @{format("string",model)},
- $items : itemList )
- $question : Question( $id : id not memberOf $items, context == $ctx )
+ $questionnaire : Questionnaire( $type : type == @{ format( "string", model ) },
+ $items : itemList,
+ $ctx : context
+ ) @watch( items )
+ $question : Question( $id : id, id not memberOf $items, context == $ctx )
then
modify ( $questionnaire ) {
+ addAvailableItem( $id ),
addItem( $id );
}
end
View
12 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelCreateByBinding.drlt
@@ -32,18 +32,18 @@ rule "Model_Create_ReBinding_@{model}_@{name}"
no-loop
salience 200
when
- $quest: Question( $id : id, type == "@{model+"_"+name}", context == @{ctx} )
+ $quest: Question( $id : id, type == "@{ model + "_" + name }" ) @watch(*)
$ans : Answer( questionId == $id, $val : value != "null" && != "" && != null )
not @{name}( context == @{ctx} )
then
@{name} x = new @{name}();
- x.setMissing(false);
- x.setValid(false);
+ x.setMissing( false );
+ x.setValid( false );
x.setContext( @{ctx} );
- x.setName(@{format("string",name)});
+ x.setName( @{ format( "string", name ) } );
- BeanUtils.setProperty(x, "value", $val);
- System.out.println(" REBINDING OF " + x + " from " + $ans );
+ BeanUtils.setProperty( x, "value", $val );
+// System.out.println(" REBINDING OF " + x + " from " + $ans );
insert(x);
end
View
2  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelInvalidAnswer.drlt
@@ -29,12 +29,10 @@
rule "Invalid_Answer_for_Question"
no-loop
when
-
$bean : DataField( valid == false, $ct : context )
$assoc : DomainModelAssociation( $id : questionId, object == $bean )
$quest : Question( id == $id )
then
- System.out.println("MOdel-driven invalid answer " + $bean);
insertLogical( new InvalidAnswer($id, "invalid", " Value of " + $bean.getClass().getSimpleName() + " not valid in model " + $ct + " >>> " + $bean) );
end
@end{}
View
31 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelMultiQuestion.drlt
@@ -25,19 +25,21 @@
}
@declare{'modelMultiQuestionRule'}
+
rule "Model_Multi_Question_@{model}_@{name}"
dialect "mvel"
no-loop
salience 99
when
- ModelMarker( "@{model}" ; )
- not Question( type == @{ format( "string", model + "_" + name ) } )
+ ModelMarker( "@{model}" ; enabled == true )
+ Questionnaire( type == "@{model}", $qid : id )
+ not MultipleChoiceQuestion( type == @{ format( "string", model + "_" + name ) } )
then
- MultipleChoiceQuestion quest = new MultipleChoiceQuestion(@{format("string",model)}+"_"+@{format("string",name)});
- quest.setContext(@{format("string",model)});
- quest.setAnswerType(@{mapDatatypeToQuestion(dataType)});
- quest.setPreLabel("Please insert " + @{format("string",name)});
- quest.setSingleAnswer(true);
+ MultipleChoiceQuestion quest = new MultipleChoiceQuestion( @{ format( "string", model + "_" + name ) } );
+ quest.setContext( $qid );
+ quest.setAnswerType( @{ mapDatatypeToQuestion( dataType ) } );
+ quest.setPreLabel( "Please insert " + @{ format( "string", displayName != null ? displayName : name ) } );
+ quest.setSingleAnswer( true );
quest.setPossibleAnswers({
@foreach{ val : valid }
@@ -57,7 +59,20 @@ then
insert(quest);
end
-@end{}
+
+
+//rule "Model_Multi_Question_@{model}_@{name} Clear"
+//dialect "mvel"
+//no-loop
+//salience 99
+//when
+// $mm : ModelMarker( "@{model}" ; enabled == false )
+// $qt : MultipleChoiceQuestion( type == @{ format( "string", model + "_" + name ) } )
+//then
+// retract( $qt );
+//end
+//
+//@end{}
View
12 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelOutputBinding.drlt
@@ -31,13 +31,13 @@ dialect "mvel"
no-loop
salience 99
when
- $bean : @{name}( $ctx : context == @{format("string",context)} , $val : value )
- $quest : Questionnaire( context == @{format("string",context)} )
+ $bean : @{name}( $ctx : context == @{ format( "string", context ) } , $val : value )
+ $quest : Questionnaire( type == @{ format( "string", context ) } )
then
- Note outNote = new Note(@{noteId});
- outNote.setContext(@{format("string",context)});
- outNote.setLabel(" @{fullName} [@{outType}] : " + $val);
- insertLogical(outNote);
+ Note outNote = new Note( @{noteId} );
+ outNote.setContext( @{format( "string", context ) } );
+ outNote.setLabel( "@{fullName} [@{outType}] : " + $val );
+ insertLogical( outNote );
end
@end{}
View
25 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestion.drlt
@@ -25,20 +25,33 @@
}
@declare{'modelQuestionRule'}
+
rule "Model_Question_@{model}_@{name}_@{context}"
no-loop
salience 99
when
- ModelMarker( "@{model}" ; )
+ ModelMarker( "@{model}" ; enabled == true )
+ Questionnaire( type == "@{model}", $qid : id )
not Question( type == @{ format( "string", model + "_" + name ) } )
then
- Question quest = new Question(@{format("string",model)}+"_"+@{format("string",name)});
- quest.setContext(@{format("string",model)});
- quest.setAnswerType(@{mapDatatypeToQuestion(dataType)});
- quest.setPreLabel("Please insert " + @{format("string",displayName)});
+ Question quest = new Question( @{ format( "string", model + "_" + name ) } );
+ quest.setContext( $qid );
+ quest.setAnswerType( @{ mapDatatypeToQuestion( dataType ) } );
+ quest.setPreLabel( "Please insert " + @{ format( "string", displayName != null ? displayName : name ) } );
insert(quest);
end
-@end{}
+
+//rule "Model_Question_@{model}_@{name}_@{context} Clear"
+//no-loop
+//salience 99
+//when
+// $mm : ModelMarker( "@{model}" ; enabled == false )
+// $qt : Question( type == @{ format( "string", model + "_" + name ) } )
+//then
+// retract( $qt );
+//end
+//
+//@end{}
View
28 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestionBinding.drlt
@@ -31,19 +31,25 @@ no-loop
salience 99
when
$quest: Question( $id : id, $type : type == "@{model+"_"+name}" )
- $bean : @{name}( $ctx : context == @{format("string",context)} , $val : value )
- not DomainModelAssociation( questionId == $id, object == $bean, context == @{format("string",context)} )
+ $bean : @{name}( $ctx : context == @{ format( "string", context ) } , $val : value )
+ not DomainModelAssociation( questionId == $id, object == $bean, context == @{ format( "string", context ) } )
then
+ modify ( $quest ) {
+ setAnswer( null );
+ }
+
+ System.out.println( drools.getRule().getName() );
DomainModelAssociation assoc = new DomainModelAssociation();
- assoc.setQuestionId($id);
- assoc.setContext($ctx);
- assoc.setObject($bean);
- assoc.setProperty("value");
- assoc.setLastAnswer($val);
-
- System.out.println("Binding " + $bean + " using " + assoc );
- System.out.println("Insert @ssociation " + assoc);
- insert(assoc);
+ assoc.setQuestionId( $id );
+ assoc.setContext( $ctx );
+ assoc.setObject( $bean );
+ assoc.setProperty( "value" );
+ assoc.setLastAnswer( null );
+
+// System.out.println( "Binding " + $bean );
+// System.out.println( "Insert @ssociation " + assoc );
+// System.out.println( "TGT question is " + $quest );
+ insert( assoc );
end
@end{}
View
11 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestionRebinding.drlt
@@ -12,13 +12,16 @@ rule "Model_Question_ReBinding_@{model}_@{name}"
dialect "mvel"
no-loop
when
- $quest: Question( $id : id, $type : type == "@{model+"_"+name}", lastAnswer != null )
+ $quest: Question( $id : id, $type : type == "@{model+"_"+name}", lastAnswer != null ) @watch(*)
$bean : @{name}( context == @{format("string",context)} )
$assoc : DomainModelAssociation( questionId == $id, object != $bean )
then
- System.out.println("Rebinding " + $bean + " using " + $assoc );
- $assoc.setObject($bean);
- //update($assoc);
+// System.out.println("Rebinding " + $bean + " using " + $assoc );
+
+ modify ( $assoc ) {
+ setObject( $bean );
+ }
+
end
@end{}
View
38 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelQuestionnaire.drlt
@@ -25,22 +25,42 @@
}
@declare{'modelQuestionnaireRule'}
+
+
rule "Model_Questionnaire_@{model}"
-dialect "mvel"
-no-loop
salience 1000
when
- ModelMarker( "@{model}" ; )
- not Questionnaire( type == @{ format( "string", model + "_Questionnaire" ) } )
+ $mm : ModelMarker( "@{model}" ; enabled == true )
+ not Questionnaire( type == @{ format( "string", model ) } )
then
- Questionnaire questionnaire = new Questionnaire(@{format("string",model)}+"_Questionnaire");
- questionnaire.setContext(@{format("string",model)});
- questionnaire.setLabel(@{format("string",model)} + " form");
+ System.out.println( "Creating questionnaire @{model}" );
+ Questionnaire questionnaire = new Questionnaire( @{ format( "string", model) } );
+ questionnaire.setContext( questionnaire.getId() );
+ questionnaire.setLabel( @{ format( "string", model ) } + " Input Form" );
+
+// questionnaire.setItems( new String[] { @foreach{fld : fields} @{format("string",model)}+"_"+@{format("string",compactUpperCase(fld.name))} @end{","} } );
+
+ insert(questionnaire);
+end
- questionnaire.setItems({ @foreach{fld : fields} @{format("string",model)}+"_"+@{format("string",compactUpperCase(fld.name))} @end{","} });
+//rule "Model_Questionnaire_@{model} Clear"
- insert(questionnaire);
+rule "Model_Questionnaire_@{model} Trait"
+no-loop
+when
+ $mm : ModelMarker( "@{model}" ; enabled == true )
+ Questionnaire( $id : id, type == "@{model}" ) @watch( !* )
+then
+// System.out.println( "Traiting questionnaire @{model}" );
+ org.drools.informer.ISurveyableTrait surv;
+ surv = don( $mm, org.drools.informer.ISurveyableTrait.class, true );
+ modify ( surv ) {
+ setQuestionnaireId( $id ),
+ setStateful( false ),
+ setSurveyEnabled( true );
+ }
end
+
@end{}
View
13 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/informer/modelRevalidate.drlt
@@ -30,22 +30,23 @@ rule "Model_Revalidate"
no-loop
salience 50
when
- question : Question(questionId : id, answerType != null, answer : answer != null )
+ question : Question(questionId : id, answerType != null, answer : answer != null ) @watch(*)
association : DomainModelAssociation(questionId == questionId, object : object, property : property, lastAnswer == answer )
$bean : DataField( this == object, valid == false )
then
// System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>> REVAL : " + $bean + " on " + association + " sue to " + question );
- $bean.setValid(false);
Class propertyClass = PropertyUtils.getPropertyType(object, property);
Object propertyValue = DomainModelSupport.answerToObject(question.getBasicAnswerType(), answer, propertyClass);
Object oldPropertyValue = PropertyUtils.getProperty(object, property);
PropertyUtils.setProperty(object, property, propertyValue);
- association.setLastAnswer(answer);
-
- modify( $bean ) {}
- modify( association ) {}
+ modify( $bean ) {
+ setValid(false);
+ }
+ modify( association ) {
+ setLastAnswer(answer)
+ }
end
View
4 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/clustering/clusteringInit.drlt
@@ -26,7 +26,7 @@
rule "Init Clusters @{context}"
when
- ModelMarker( "@{context}" ; )
+ ModelMarker( "@{context}" ; enabled == true )
then
java.util.List clusters = new java.util.ArrayList();
ClusterSet model = new ClusterSet(
@@ -57,7 +57,7 @@ then
insertLogical( cluster@{j} );
@end{}
- insert( model );
+ insertLogical( model );
end
View
3  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/clustering/clusteringMatrixCompare.drlt
@@ -26,9 +26,10 @@
rule "Init @{ context } @{ compactUpperCase( fieldName ) } Table"
when
+ ModelMarker( "@{context}" ; enabled == true )
then
double[][] mat = new double[][] { @foreach{ j : matrix.rows } { @foreach{ k : matrix.cols } @{matrix.data[j][k]} @end{','} } @end{','} };
- insert( new DoubleTable( "@{ context }", "@{ compactUpperCase( fieldName ) }", @{matrix.rows}, @{matrix.cols}, mat ) );
+ insertLogical( new DoubleTable( "@{ context }", "@{ compactUpperCase( fieldName ) }", @{matrix.rows}, @{matrix.cols}, mat ) );
end
query compare@{ context }@{ compactUpperCase( fieldName ) }( Double $x, Double $y, double[][] $val )
View
2  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/neural/neuralBuildSynapses.drlt
@@ -25,7 +25,7 @@
rule "BuildSynapses_@{model}_Neuron@{index}"
no-loop
when
- ModelMarker( "@{model}" ; )
+ ModelMarker( "@{model}" ; enabled == true )
then
Synapse syn;
@foreach{ con : links }
View
10 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/regression/regDeclare.drlt
@@ -26,24 +26,24 @@
declare RegTable
context : String @key
- target : String @key
+ target : String
category : String
numCoeffs : double[]
numExps : double[]
catCoeffs : double[]
trmCoeffs : double[]
intercept : double
- index : int
+ index : int @key
end
declare RegTargetBit
context : String @key
- target : String @key
- value : String @key
+ target : String
+ value : String
weight : double
normalized : boolean = false
cumulative : boolean = false
- index : int
+ index : int @key
end
declare RegNormalizationFactor
View
20 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/regression/regParams.drlt
@@ -26,17 +26,17 @@
rule "Init Regression Model @{context} : @{target} - @{category}"
when
- ModelMarker( "@{context}" ; )
+ ModelMarker( "@{context}" ; enabled == true )
then
- insert( new RegTable( "@{context}",
- @if{ target != null } "@{target}" @else{} null @end{},
- @if{ category != null } "@{category}" @else{} null @end{},
- new double[] { @foreach{ numC : numCoeffs } @{numC} @end{','} },
- new double[] { @foreach{ numE : numExps } @{numE} @end{','} },
- new double[] { @foreach{ catC : catCoeffs } @{catC} @end{','} },
- new double[] { @foreach{ trmC : trmCoeffs } @{trmC} @end{','} },
- @{c0},
- @{index}
+ insertLogical( new RegTable( "@{context}",
+ @if{ target != null } "@{target}" @else{} null @end{},
+ @if{ category != null } "@{category}" @else{} null @end{},
+ new double[] { @foreach{ numC : numCoeffs } @{numC} @end{','} },
+ new double[] { @foreach{ numE : numExps } @{numE} @end{','} },
+ new double[] { @foreach{ catC : catCoeffs } @{catC} @end{','} },
+ new double[] { @foreach{ trmC : trmCoeffs } @{trmC} @end{','} },
+ @{c0},
+ @{index}
) );
end
View
2  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/svm/svmBuild.drlt
@@ -26,7 +26,7 @@
rule "Init Svm @{svmId}"
when
- ModelMarker( "@{context}" ; )
+ ModelMarker( "@{context}" ; enabled == true )
then
insertLogical( new SVM ( "@{svmId}",
"@{modelName}",
View
4 drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/svm/svmInitSupportVector.drlt
@@ -26,9 +26,11 @@
@code{ int ctr = 0; }
rule "Init SupportVector @{modelName}"
when
+ ModelMarker( "@{context}" ; enabled == true )
then
@foreach{ sv : vectors }
- insert( new SupportVector ( "@{modelName}",
+ insertLogical( new SupportVector (
+ "@{modelName}",
"@{sv.supportVector.vectorId}",
@{sv.index},
@if{ sv.sparse }
View
2  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/svm/svmParams.drlt
@@ -20,7 +20,7 @@
rule "Init SvmParams @{modelName}"
when
- ModelMarker( "@{context}" ; )
+ ModelMarker( "@{context}" ; enabled == true )
then
insertLogical( new SvmParams ( "@{modelName}",
"@{kernelType}",
View
2  drools-pmml/src/main/resources/org/drools/pmml_4_0/templates/models/tree/treeInit.drlt
@@ -26,7 +26,7 @@
rule " Create tree @{context}"
when
- ModelMarker( "@{context}" ; )
+ ModelMarker( "@{context}" ; enabled == true )
then
TreeNode node;
java.util.Map count;
View
236 drools-pmml/src/test/java/org/drools/pmml_4_0/informer/QuestionnaireTest.java
@@ -19,10 +19,7 @@
import org.drools.ClassObjectFilter;
import org.drools.definition.type.FactType;
-import org.drools.informer.Answer;
-import org.drools.informer.DomainModelAssociation;
-import org.drools.informer.InvalidAnswer;
-import org.drools.informer.Note;
+import org.drools.informer.*;
import org.drools.pmml_4_0.DroolsAbstractPMMLTest;
import org.drools.runtime.rule.Variable;
import org.junit.Test;
@@ -41,12 +38,43 @@
private static final String source = "org/drools/pmml_4_0/test_miningSchema.xml";
private static final String source2 = "org/drools/pmml_4_0/test_ann_iris_prediction.xml";
private static final String sourceMix = "org/drools/pmml_4_0/test_ann_mixed_inputs.xml";
+ private static final String source99 = "org/drools/pmml_4_0/test_ann_iris.xml";
private static final String packageName = "org.drools.pmml_4_0.test";
+ @Test
+ public void testUnquestionable() {
+ setKSession( getModelSession( source99, VERBOSE ) );
+ setKbase( getKSession().getKnowledgeBase() );
+
+ getKSession().fireAllRules();
+
+ System.err.println( reportWMObjects( getKSession() ) );
+
+ assertEquals( 0, getKSession().getObjects( new ClassObjectFilter( Questionnaire.class ) ).size() );
+ }
+
+ @Test
+ public void testQuestionable() {
+ setKSession( getModelSession( source, VERBOSE ) );
+ setKbase( getKSession().getKnowledgeBase() );
+
+ getKSession().fireAllRules();
+
+ System.err.println( reportWMObjects( getKSession() ) );
+
+ Collection questionnaires = getKSession().getObjects( new ClassObjectFilter( Questionnaire.class ) );
+ assertEquals( 1, questionnaires.size() );
+ Questionnaire quest = (Questionnaire) questionnaires.iterator().next();
+ assertEquals( "Test_MLP", quest.getType() );
+ assertEquals( 2, quest.getNumAvailableItems() );
+ assertEquals( 2, quest.getItemList().size() );
+ assertEquals( quest.getId(), quest.getContext() );
+ }
+
@Test
public void testOverride() throws Exception {
@@ -87,6 +115,10 @@ public void testOverride() throws Exception {
getKSession().getWorkingMemoryEntryPoint("in_Feat1").insert(2.5);
+ getKSession().fireAllRules();
+
+ System.out.println( "--------------------------------------------------------------------");
+
getKSession().getWorkingMemoryEntryPoint("in_Feat2").insert(6);
getKSession().fireAllRules();
@@ -130,7 +162,7 @@ public void testMixModel() throws Exception {
- Answer ans1 = new Answer(getQId("Mixed","Gender"),"male");
+ Answer ans1 = new Answer( getQId( "Mixed", "Gender" ), "male" );
getKSession().insert(ans1);
getKSession().getWorkingMemoryEntryPoint("in_Domicile").insert("rural");
@@ -191,49 +223,50 @@ public void testMixModel() throws Exception {
@Test
public void testGenerateInputsByAnswer() throws Exception {
- setKSession(getModelSession(source,VERBOSE));
- setKbase(getKSession().getKnowledgeBase());
+ setKSession(getModelSession( source, VERBOSE ) );
+ setKbase( getKSession().getKnowledgeBase() );
getKSession().fireAllRules();
+ System.err.println( reportWMObjects( getKSession() ) );
- String qid1 = getQId("Test_MLP","Feat1");
- String qid2 = getQId("Test_MLP","Feat2");
+ String qid1 = getQId( "Test_MLP", "Feat1" );
+ String qid2 = getQId( "Test_MLP", "Feat2" );
- Answer ans1 = new Answer(qid1,"2.5");
- Answer ans2 = new Answer(qid2,"5");
+ Answer ans1 = new Answer( qid1, "2.5" );
+ Answer ans2 = new Answer( qid2, "5" );
- getKSession().insert(ans1);
- getKSession().insert(ans2);
+ getKSession().insert( ans1 );
+ getKSession().insert( ans2 );
getKSession().fireAllRules();
- FactType feat1 = getKbase().getFactType("org.drools.pmml_4_0.test", "Feat1");
- FactType feat2 = getKbase().getFactType("org.drools.pmml_4_0.test", "Feat2");
+ FactType feat1 = getKbase().getFactType( "org.drools.pmml_4_0.test", "Feat1" );
+ FactType feat2 = getKbase().getFactType( "org.drools.pmml_4_0.test", "Feat2" );
- Collection c = getKSession().getObjects(new ClassObjectFilter(feat2.getFactClass()));
- assertEquals(1,c.size());
+ Collection c = getKSession().getObjects( new ClassObjectFilter( feat2.getFactClass() ) );
+ assertEquals( 1, c.size() );
Iterator i2 = c.iterator();
- while (i2.hasNext()) {
+ while ( i2.hasNext() ) {
Object o = i2.next();
- if (feat2.get(o,"context") != null)
- assertEquals(5, feat2.get(o,"value"));
+ if ( feat2.get( o, "context" ) != null )
+ assertEquals( 5, feat2.get( o, "value" ) );
}
- Collection d = getKSession().getObjects(new ClassObjectFilter(feat1.getFactClass()));
- assertEquals(1, d.size());
+ Collection d = getKSession().getObjects(new ClassObjectFilter( feat1.getFactClass() ) );
+ assertEquals( 1, d.size( ) );
Iterator i1 = d.iterator();
- while (i1.hasNext()) {
+ while ( i1.hasNext() ) {
Object o = i1.next();
- if (feat1.get(o,"context") != null)
- assertEquals(2.5, feat1.get(o,"value"));
+ if ( feat1.get( o,"context" ) != null )
+ assertEquals( 2.5, feat1.get( o, "value" ) );
}
- System.err.println(reportWMObjects(getKSession()));
+ System.err.println( reportWMObjects( getKSession() ) );
}
@@ -310,32 +343,35 @@ public void testAnswerUpdate() throws Exception {
@Test
public void testInvalidValues() throws Exception {
- setKSession(getModelSession(new String[] {source2},VERBOSE));
- setKbase(getKSession().getKnowledgeBase());
+ setKSession( getModelSession( new String[] { source2 }, VERBOSE ) );
+ setKbase( getKSession().getKnowledgeBase() );
getKSession().fireAllRules();
- getKSession().getWorkingMemoryEntryPoint("in_Feat2").insert(5);
+ getKSession().getWorkingMemoryEntryPoint( "in_Feat2" ).insert( 5 );
getKSession().fireAllRules();
- System.err.println(reportWMObjects(getKSession()));
+ System.err.println( reportWMObjects( getKSession() ) );
- FactType type = getKbase().getFactType(packageName,"Feat2");
- checkFirstDataFieldOfTypeStatus(type,false,false,"Neuiris",5);
+ FactType type = getKbase().getFactType( packageName, "Feat2" );
+ checkFirstDataFieldOfTypeStatus( type, false, false, "Neuiris", 5 );
- assertEquals(4, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
+ assertEquals( 4, getKSession().getObjects(new ClassObjectFilter( InvalidAnswer.class ) ).size() );
- assertEquals(0,getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
+ assertEquals( 0, getKSession().getObjects( new ClassObjectFilter( Note.class ) ).size() );
}
- private String getQId(String model, String field) {
- return (String) getKSession().getQueryResults( "getItemId", model+"_"+field, model, Variable.v ).iterator().next().get("$id");
+ private String getQId( String model, String field ) {
+ // ref : getItemId( String $type, String $context, String $id )
+
+ String questId = (String) getKSession().getQueryResults( "getItemId", model, Variable.v, Variable.v ).iterator().next().get( "$id" );
+ return (String) getKSession().getQueryResults( "getItemId", model+"_"+field, questId, Variable.v ).iterator().next().get( "$id" );
}
@@ -354,32 +390,32 @@ private String getQId(String model, String field) {
@Test
public void testMultipleModels() throws Exception {
- setKSession(getModelSession(new String[] {source,source2},VERBOSE));
+ setKSession( getModelSession( new String[] { source, source2 }, true ) );
setKbase(getKSession().getKnowledgeBase());
- FactType petalNumType = getKbase().getFactType(packageName,"Feat2");
- FactType out = getKbase().getFactType(packageName,"OutSepLen");
- FactType sepalType = getKbase().getFactType(packageName,"SepalLen");
+ FactType petalNumType = getKbase().getFactType( packageName, "Feat2" );
+ FactType out = getKbase().getFactType( packageName, "OutSepLen" );
+ FactType sepalType = getKbase().getFactType( packageName, "SepalLen" );
getKSession().fireAllRules();
- getKSession().getWorkingMemoryEntryPoint("in_Feat2").insert(4);
-
- getKSession().getWorkingMemoryEntryPoint("in_PetalWid").insert(1);
- getKSession().getWorkingMemoryEntryPoint("in_SepalWid").insert(30);
- getKSession().getWorkingMemoryEntryPoint("in_Species").insert("virginica");
+ getKSession().getWorkingMemoryEntryPoint( "in_Feat2" ).insert( 4 );
+ getKSession().getWorkingMemoryEntryPoint( "in_PetalWid" ).insert( 1 );
+ getKSession().getWorkingMemoryEntryPoint( "in_SepalWid" ).insert( 30 );
+ getKSession().getWorkingMemoryEntryPoint( "in_Species" ).insert( "virginica" );
+ // one question for each model is not answered
getKSession().fireAllRules();
-// System.err.println(reportWMObjects(getKSession()));
+ System.err.println(reportWMObjects(getKSession()));
- checkFirstDataFieldOfTypeStatus(petalNumType,false,false,"Neuiris",4);
- assertEquals(6, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
- assertEquals(2, getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
+ checkFirstDataFieldOfTypeStatus( petalNumType, false, false, "Neuiris", 4 );
+ assertEquals( 2, getKSession().getObjects( new ClassObjectFilter( InvalidAnswer.class ) ).size() );
+ assertEquals( 2, getKSession().getObjects( new ClassObjectFilter( Note.class ) ).size() );
@@ -397,8 +433,8 @@ public void testMultipleModels() throws Exception {
checkFirstDataFieldOfTypeStatus(petalNumType,true,false,"Neuiris",40);
- assertEquals(5, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
- assertEquals(4,getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
+ assertEquals( 1, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
+ assertEquals( 4,getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
checkFirstDataFieldOfTypeStatus(out,true,false,"Neuris",42);
checkFirstDataFieldOfTypeStatus(sepalType,true,false,"Neuiris",42);
@@ -420,8 +456,8 @@ public void testMultipleModels() throws Exception {
checkFirstDataFieldOfTypeStatus(petalNumType,true,false,"Neuiris",40);
- assertEquals(6, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
- assertEquals(4,getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
+ assertEquals( 2, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
+ assertEquals( 4,getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
checkFirstDataFieldOfTypeStatus(out,true,false,"Neuiris",42);
assertEquals(1, getKSession().getObjects(new ClassObjectFilter(sepalType.getFactClass())).size());
@@ -443,8 +479,8 @@ public void testMultipleModels() throws Exception {
checkFirstDataFieldOfTypeStatus(petalNumType,true,false,"Neuiris",101);
- assertEquals(5, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
- assertEquals(4,getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
+ assertEquals( 1, getKSession().getObjects(new ClassObjectFilter(InvalidAnswer.class)).size());
+ assertEquals( 4,getKSession().getObjects(new ClassObjectFilter(Note.class)).size());
checkFirstDataFieldOfTypeStatus(out,true,false,"Neuiris",23);
checkFirstDataFieldOfTypeStatus(sepalType,true,false,"Neuiris",23);
@@ -459,6 +495,96 @@ public void testMultipleModels() throws Exception {
+ @Test
+ public void testModelProgress() throws Exception {
+
+
+ setKSession(getModelSession(new String[] {sourceMix},true));
+ setKbase(getKSession().getKnowledgeBase());
+
+ getKSession().fireAllRules();
+
+ FactType progressType = getKbase().getFactType( "org.drools.informer", "ProgressStatus" );
+
+
+ Answer ans1 = new Answer( getQId( "Mixed", "Gender" ), "male" );
+
+ getKSession().insert(ans1);
+ getKSession().fireAllRules();
+
+ Object progress = getKSession().getObjects( new ClassObjectFilter( progressType.getFactClass()) ).iterator().next();
+ Integer progressNum = (Integer) progressType.get( progress, "percentage" );
+
+ System.out.println( progressNum );
+ assertEquals( 20, progressNum.intValue() );
+
+
+ System.out.println("---------------------------------------------------------------------------------------");
+
+ getKSession().getWorkingMemoryEntryPoint("in_Domicile").insert("rural");
+
+ getKSession().fireAllRules();
+
+
+ progress = getKSession().getObjects( new ClassObjectFilter( progressType.getFactClass()) ).iterator().next();
+ progressNum = (Integer) progressType.get( progress, "percentage" );
+
+ assertEquals( 40, progressNum.intValue() );
+
+ System.out.println("---------------------------------------------------------------------------------------");
+
+
+ Answer ans2 = new Answer(getQId("Mixed","Scrambled"),"7");
+ getKSession().insert(ans2);
+
+
+ Answer ans3 = new Answer(getQId("Mixed","NoOfClaims"),"1");
+ getKSession().insert(ans3);
+
+ getKSession().fireAllRules();
+
+
+ progress = getKSession().getObjects( new ClassObjectFilter( progressType.getFactClass()) ).iterator().next();
+ progressNum = (Integer) progressType.get( progress, "percentage" );
+
+ assertEquals( 80, progressNum.intValue() );
+
+
+ Answer ans4 = new Answer(getQId("Mixed","AgeOfCar"),"-3");
+ getKSession().insert(ans4);
+
+ getKSession().fireAllRules();
+
+
+ progress = getKSession().getObjects( new ClassObjectFilter( progressType.getFactClass()) ).iterator().next();
+ progressNum = (Integer) progressType.get( progress, "percentage" );
+
+ System.err.println(reportWMObjects(getKSession()));
+
+ assertEquals( 80, progressNum.intValue() );
+
+
+
+ Answer ans5 = new Answer(getQId("Mixed","AgeOfCar"),"4.0");
+ getKSession().insert(ans5);
+
+ getKSession().fireAllRules();
+
+
+ progress = getKSession().getObjects( new ClassObjectFilter( progressType.getFactClass()) ).iterator().next();
+ progressNum = (Integer) progressType.get( progress, "percentage" );
+
+ assertEquals( 100, progressNum.intValue() );
+
+
+ System.err.println(reportWMObjects(getKSession()));
+
+
+
+ }
+
+
+
}
View
445 drools-pmml/src/test/java/org/drools/pmml_4_0/predictive/models/CleanupTest.java
@@ -0,0 +1,445 @@
+/*
+ * Copyright 2011 JBoss Inc
+ *
+ * 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.
+ */
+
+package org.drools.pmml_4_0.predictive.models;
+
+
+import junit.framework.Assert;
+import org.drools.KnowledgeBase;
+import org.drools.KnowledgeBaseFactory;
+import org.drools.agent.ChangeSetHelperImpl;
+import org.drools.agent.KnowledgeAgent;
+import org.drools.agent.KnowledgeAgentConfiguration;
+import org.drools.agent.KnowledgeAgentFactory;
+import org.drools.agent.conf.NewInstanceOption;
+import org.drools.agent.conf.UseKnowledgeBaseClassloaderOption;
+import org.drools.agent.impl.PrintStreamSystemEventListener;
+import org.drools.builder.KnowledgeBuilder;
+import org.drools.builder.KnowledgeBuilderFactory;
+import org.drools.builder.ResourceType;
+import org.drools.event.knowledgebase.KnowledgeBaseEvent;
+import org.drools.io.ResourceFactory;
+import org.drools.io.impl.ClassPathResource;
+import org.drools.pmml_4_0.DroolsAbstractPMMLTest;
+import org.drools.runtime.StatefulKnowledgeSession;
+import org.drools.runtime.rule.QueryResults;
+import org.drools.runtime.rule.Variable;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+public class CleanupTest extends DroolsAbstractPMMLTest {
+
+
+ private static final String source1 = "org/drools/pmml_4_0/test_ann_iris_prediction.xml";
+ private static final String source2 = "org/drools/pmml_4_0/test_tree_simple.xml";
+ private static final String source3 = "org/drools/pmml_4_0/test_regression.xml";
+ private static final String source4 = "org/drools/pmml_4_0/test_clustering.xml";
+ private static final String source5 = "org/drools/pmml_4_0/test_svm.xml";
+
+ private static final String source9 = "org/drools/pmml_4_0/mock_cold.pmml";
+
+ private static final String packageName = "org.drools.pmml_4_0.test";
+
+
+
+
+ @Test
+ public void testCleanupANN() {
+ StatefulKnowledgeSession kSession = loadModel( source1 );
+ assertTrue( kSession.getObjects().size() > 0 );
+
+ QueryResults qres = kSession.getQueryResults( "modelMarker", "Neuiris", Variable.v );
+ assertEquals( 1, qres.size() );
+
+ Object marker = qres.iterator().next().get( "$mm" );
+ assertNotNull( marker );
+
+ kSession.getWorkingMemoryEntryPoint( "enable_Neuiris" ).insert( Boolean.FALSE );
+ kSession.fireAllRules();
+
+ System.err.println(reportWMObjects(kSession));
+
+ assertEquals( 1, kSession.getObjects().size() );
+ }
+
+
+ @Test
+ public void testReenableANN() {
+ setKSession( loadModel( source1 ) );
+ assertTrue( getKSession().getObjects().size() > 0 );
+
+ QueryResults qres = getKSession().getQueryResults( "modelMarker", "Neuiris", Variable.v );
+ assertEquals( 1, qres.size() );
+
+ Object marker = qres.iterator().next().get( "$mm" );
+ assertNotNull( marker );
+
+ getKSession().getWorkingMemoryEntryPoint( "enable_Neuiris" ).insert( Boolean.FALSE );
+
+ getKSession().fireAllRules();
+
+ System.err.println(reportWMObjects(getKSession()));
+
+ assertEquals( 1, getKSession().getObjects().size() );
+
+ getKSession().getWorkingMemoryEntryPoint( "enable_Neuiris" ).insert( Boolean.TRUE );
+ getKSession().fireAllRules();
+
+ System.err.println( reportWMObjects(getKSession()) );
+
+ getKSession().getWorkingMemoryEntryPoint("in_Feat2").insert(101);
+ getKSession().getWorkingMemoryEntryPoint("in_PetalWid").insert(2);
+ getKSession().getWorkingMemoryEntryPoint("in_Species").insert("virginica");
+ getKSession().getWorkingMemoryEntryPoint("in_SepalWid").insert(30);
+ getKSession().fireAllRules();
+
+
+ System.err.println(reportWMObjects(getKSession()));
+
+ Assert.assertEquals(24.0, queryIntegerField("OutSepLen", "Neuiris"));
+
+ assertEquals( 60, getKSession().getObjects().size() );
+
+ }
+
+
+
+ @Test
+ public void testCleanupDT() {
+ StatefulKnowledgeSession kSession = loadModel( source2 );
+ assertTrue( kSession.getObjects().size() > 0 );
+
+ QueryResults qres = kSession.getQueryResults( "modelMarker", "TreeTest", Variable.v );
+ assertEquals( 1, qres.size() );
+
+ Object marker = qres.iterator().next().get( "$mm" );
+ assertNotNull( marker );
+
+ kSession.getWorkingMemoryEntryPoint( "enable_TreeTest" ).insert(Boolean.FALSE);
+ kSession.fireAllRules();
+
+ System.err.println(reportWMObjects(kSession));
+
+ assertEquals( 1, kSession.getObjects().size() );
+
+ }
+
+ @Test
+ public void testCleanupRegression() {
+ StatefulKnowledgeSession kSession = loadModel( source3 );
+ assertTrue( kSession.getObjects().size() > 0 );
+
+ QueryResults qres = kSession.getQueryResults( "modelMarker", "LinReg", Variable.v );
+ assertEquals( 1, qres.size() );
+
+ Object marker = qres.iterator().next().get( "$mm" );
+ assertNotNull( marker );
+
+ kSession.getWorkingMemoryEntryPoint( "enable_LinReg" ).insert(Boolean.FALSE);
+ kSession.fireAllRules();
+
+ System.err.println(reportWMObjects(kSession));
+
+ assertEquals( 1, kSession.getObjects().size() );
+
+ }
+
+ @Test
+ public void testCleanupClustering() {
+ StatefulKnowledgeSession kSession = loadModel( source4 );
+ assertTrue( kSession.getObjects().size() > 0 );
+
+ QueryResults qres = kSession.getQueryResults( "modelMarker", "CenterClustering", Variable.v );
+ assertEquals( 1, qres.size() );
+
+ Object marker = qres.iterator().next().get( "$mm" );
+ assertNotNull( marker );
+
+ kSession.getWorkingMemoryEntryPoint( "enable_CenterClustering" ).insert(Boolean.FALSE);
+ kSession.fireAllRules();
+
+ System.err.println(reportWMObjects(kSession));
+
+ assertEquals( 1, kSession.getObjects().size() );
+
+ }
+
+ @Test
+ public void testCleanupSVM() {
+ StatefulKnowledgeSession kSession = loadModel( source5 );
+ assertTrue( kSession.getObjects().size() > 0 );
+
+ QueryResults qres = kSession.getQueryResults( "modelMarker", "SVMXORModel", Variable.v );
+ assertEquals( 1, qres.size() );
+
+ Object marker = qres.iterator().next().get( "$mm" );
+ assertNotNull( marker );
+
+ kSession.getWorkingMemoryEntryPoint( "enable_SVMXORModel" ).insert(Boolean.FALSE);
+ kSession.fireAllRules();
+
+ System.err.println(reportWMObjects(kSession));
+
+ assertEquals( 1, kSession.getObjects().size() );
+
+ }
+
+
+
+ @Test
+ public void testCleanupANNRulesWithIncrementalKA() {
+
+ KnowledgeAgent kAgent = initIncrementalKA();
+// kAgent.setSystemEventListener( new PrintStreamSystemEventListener() );
+
+ KnowledgeBase kBase = kAgent.getKnowledgeBase();
+ StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession();
+
+ ChangeSetHelperImpl csAdd = new ChangeSetHelperImpl();
+ ClassPathResource res = (ClassPathResource) ResourceFactory.newClassPathResource( source1 );
+ res.setResourceType( ResourceType.PMML );
+ ClassPathResource res2 = (ClassPathResource) ResourceFactory.newClassPathResource( source9 );
+ res2.setResourceType( ResourceType.PMML );
+ csAdd.addNewResource(res);
+ csAdd.addNewResource( res2 );
+
+ System.out.println( "************************ ADDING resources ");
+
+ kAgent.applyChangeSet( csAdd.getChangeSet() );
+
+ assertTrue( kBase.getKnowledgePackage( packageName ).getRules().size() > 0 );
+ kSession.fireAllRules();
+ assertTrue( kSession.getObjects().size() > 0 );
+
+
+ System.out.println( "************************ REMOVING resource 1 ");
+
+ ChangeSetHelperImpl csRem = new ChangeSetHelperImpl();
+ csRem.addRemovedResource( res );
+ kAgent.applyChangeSet( csRem .getChangeSet() );
+
+ kSession.fireAllRules();
+
+ assertEquals( 37, kBase.getKnowledgePackage( packageName ).getRules().size() );
+
+ System.out.println( "************************ REMOVING resource 2 ");
+
+ ChangeSetHelperImpl csRem2 = new ChangeSetHelperImpl();
+ csRem2.addRemovedResource( res2 );
+ kAgent.applyChangeSet( csRem2.getChangeSet() );
+
+ kSession.fireAllRules();
+
+
+ System.out.println(reportWMObjects(kSession));
+
+ assertEquals( 0, kBase.getKnowledgePackage( packageName ).getRules().size() );
+
+ System.err.println( reportWMObjects( kSession ) );
+ assertEquals( 0, kSession.getObjects().size() );
+
+
+ }
+
+
+ @Test
+ public void testCleanupDTRulesWithIncrementalKA() {
+ KnowledgeAgent kAgent = initIncrementalKA();
+ // kAgent.setSystemEventListener( new PrintStreamSystemEventListener() );
+
+ KnowledgeBase kBase = kAgent.getKnowledgeBase();
+ StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession();
+
+ ChangeSetHelperImpl csAdd = new ChangeSetHelperImpl();
+ ClassPathResource res = (ClassPathResource) ResourceFactory.newClassPathResource( source2 );
+ res.setResourceType( ResourceType.PMML );
+ csAdd.addNewResource(res);
+
+ System.out.println( "************************ ADDING resources ");
+
+ kAgent.applyChangeSet( csAdd.getChangeSet() );
+
+ assertTrue( kBase.getKnowledgePackage( packageName ).getRules().size() > 0 );
+ kSession.fireAllRules();
+ assertTrue( kSession.getObjects().size() > 0 );
+
+
+ System.out.println( "************************ REMOVING resource 1 ");
+
+ ChangeSetHelperImpl csRem = new ChangeSetHelperImpl();
+ csRem.addRemovedResource( res );
+ kAgent.applyChangeSet( csRem .getChangeSet() );
+
+ kSession.fireAllRules();
+
+ assertEquals( 0, kBase.getKnowledgePackage( packageName ).getRules().size() );
+
+ System.err.println( reportWMObjects( kSession ) );
+ assertEquals( 0, kSession.getObjects().size() );
+
+ }
+
+ @Test
+ public void testCleanupClusteringRulesWithIncrementalKA() {
+ KnowledgeAgent kAgent = initIncrementalKA();
+ // kAgent.setSystemEventListener( new PrintStreamSystemEventListener() );
+
+ KnowledgeBase kBase = kAgent.getKnowledgeBase();
+ StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession();
+
+ ChangeSetHelperImpl csAdd = new ChangeSetHelperImpl();
+ ClassPathResource res = (ClassPathResource) ResourceFactory.newClassPathResource( source3 );
+ res.setResourceType( ResourceType.PMML );
+ csAdd.addNewResource(res);
+
+ System.out.println( "************************ ADDING resources ");
+
+ kAgent.applyChangeSet( csAdd.getChangeSet() );
+
+ assertTrue( kBase.getKnowledgePackage( packageName ).getRules().size() > 0 );
+ kSession.fireAllRules();
+ assertTrue( kSession.getObjects().size() > 0 );
+
+
+ System.out.println( "************************ REMOVING resource 1 ");
+
+ ChangeSetHelperImpl csRem = new ChangeSetHelperImpl();
+ csRem.addRemovedResource( res );
+ kAgent.applyChangeSet( csRem .getChangeSet() );
+
+ kSession.fireAllRules();
+
+ assertEquals( 0, kBase.getKnowledgePackage( packageName ).getRules().size() );
+
+ System.err.println( reportWMObjects( kSession ) );
+ assertEquals( 0, kSession.getObjects().size() );
+ }
+
+ @Test
+ public void testCleanupRegressionRulesWithIncrementalKA() {
+ KnowledgeAgent kAgent = initIncrementalKA();
+ // kAgent.setSystemEventListener( new PrintStreamSystemEventListener() );
+
+ KnowledgeBase kBase = kAgent.getKnowledgeBase();
+ StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession();
+
+ ChangeSetHelperImpl csAdd = new ChangeSetHelperImpl();
+ ClassPathResource res = (ClassPathResource) ResourceFactory.newClassPathResource( source4 );
+ res.setResourceType( ResourceType.PMML );
+ csAdd.addNewResource(res);
+
+ System.out.println( "************************ ADDING resources ");
+
+ kAgent.applyChangeSet( csAdd.getChangeSet() );
+
+ assertTrue( kBase.getKnowledgePackage( packageName ).getRules().size() > 0 );
+ kSession.fireAllRules();
+ assertTrue( kSession.getObjects().size() > 0 );
+
+
+ System.out.println( "************************ REMOVING resource 1 ");
+
+ ChangeSetHelperImpl csRem = new ChangeSetHelperImpl();
+ csRem.addRemovedResource( res );
+ kAgent.applyChangeSet( csRem .getChangeSet() );
+
+ kSession.fireAllRules();
+
+ assertEquals( 0, kBase.getKnowledgePackage( packageName ).getRules().size() );
+
+ System.err.println( reportWMObjects( kSession ) );
+ assertEquals( 0, kSession.getObjects().size() );
+ }
+
+ @Test
+ public void testCleanupSVMRulesWithIncrementalKA() {
+ KnowledgeAgent kAgent = initIncrementalKA();
+ // kAgent.setSystemEventListener( new PrintStreamSystemEventListener() );
+
+ KnowledgeBase kBase = kAgent.getKnowledgeBase();
+ StatefulKnowledgeSession kSession = kBase.newStatefulKnowledgeSession();
+
+ ChangeSetHelperImpl csAdd = new ChangeSetHelperImpl();
+ ClassPathResource res = (ClassPathResource) ResourceFactory.newClassPathResource( source5 );
+ res.setResourceType( ResourceType.PMML );
+ csAdd.addNewResource(res);
+
+ System.out.println( "************************ ADDING resources ");
+
+ kAgent.applyChangeSet( csAdd.getChangeSet() );
+
+ assertTrue( kBase.getKnowledgePackage( packageName ).getRules().size() > 0 );
+ kSession.fireAllRules();
+ assertTrue( kSession.getObjects().size() > 0 );
+
+
+ System.out.println( "************************ REMOVING resource 1 ");
+
+ ChangeSetHelperImpl csRem = new ChangeSetHelperImpl();
+ csRem.addRemovedResource( res );
+ kAgent.applyChangeSet( csRem .getChangeSet() );
+
+ kSession.fireAllRules();
+
+ assertEquals( 0, kBase.getKnowledgePackage( packageName ).getRules().size() );
+
+ System.err.println( reportWMObjects( kSession ) );
+ assertEquals( 0, kSession.getObjects().size() );
+ }
+
+
+
+
+
+ private StatefulKnowledgeSession loadModel( String source ) {
+ KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+ knowledgeBuilder.add( ResourceFactory.newClassPathResource( "org/drools/informer/informer-changeset.xml" ), ResourceType.CHANGE_SET );
+
+ knowledgeBuilder.add( ResourceFactory.newClassPathResource( source ), ResourceType.PMML );
+ if ( knowledgeBuilder.hasErrors() ) {
+ fail( knowledgeBuilder.getErrors().toString() );
+ }
+
+ KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
+
+ knowledgeBase.addKnowledgePackages( knowledgeBuilder.getKnowledgePackages() );
+ StatefulKnowledgeSession kSession = knowledgeBase.newStatefulKnowledgeSession();
+
+ kSession.fireAllRules();
+ return kSession;
+ }
+
+ private KnowledgeAgent initIncrementalKA() {
+ KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+ kbuilder.add( ResourceFactory.newClassPathResource( "org/drools/informer/informer-changeset.xml" ), ResourceType.CHANGE_SET );
+ if ( kbuilder.hasErrors() ) {
+ fail( kbuilder.getErrors().toString() );
+ }
+ KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+ kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
+
+ KnowledgeAgentConfiguration kaConfig = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
+ kaConfig.setProperty( NewInstanceOption.PROPERTY_NAME, "false" );
+ kaConfig.setProperty( UseKnowledgeBaseClassloaderOption.PROPERTY_NAME, "true" );
+ KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent( "testPmml", kbase, kaConfig );
+ return kagent;
+ }
+
+
+
+}
View
243 drools-pmml/src/test/java/org/drools/pmml_4_0/predictive/models/MultipleModelTest.java
@@ -21,36 +21,41 @@
import org.drools.ClassObjectFilter;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
+import org.drools.QueryResult;
import org.drools.agent.ChangeSetHelperImpl;
import org.drools.agent.KnowledgeAgent;
import org.drools.agent.KnowledgeAgentConfiguration;
import org.drools.agent.KnowledgeAgentFactory;
import org.drools.agent.conf.NewInstanceOption;
import org.drools.agent.conf.UseKnowledgeBaseClassloaderOption;
+import org.drools.agent.impl.PrintStreamSystemEventListener;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.definition.type.FactType;
import org.drools.event.rule.DebugAgendaEventListener;
import org.drools.event.rule.DebugWorkingMemoryEventListener;
+import org.drools.factmodel.traits.Thing;
import org.drools.informer.Answer;
import org.drools.informer.Questionnaire;
import org.drools.io.Resource;
import org.drools.io.ResourceFactory;
+import org.drools.io.impl.ByteArrayResource;
import org.drools.io.impl.ChangeSetImpl;
import org.drools.io.impl.ClassPathResource;
import org.drools.pmml_4_0.DroolsAbstractPMMLTest;
import org.drools.pmml_4_0.ModelMarker;
import org.drools.runtime.StatefulKnowledgeSession;
+import org.drools.runtime.rule.FactHandle;
+import org.drools.runtime.rule.QueryResults;
import org.drools.runtime.rule.Variable;
import org.junit.Ignore;
import org.junit.Test;
+import java.util.Arrays;
import java.util.Collection;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.*;
public class MultipleModelTest extends DroolsAbstractPMMLTest {
@@ -59,21 +64,181 @@
private static final String source1 = "org/drools/pmml_4_0/mock_ptsd.pmml";
private static final String source2 = "org/drools/pmml_4_0/mock_cold.pmml";
private static final String source3 = "org/drools/pmml_4_0/mock_breastcancer.pmml";
+ private static final String source4 = "org/drools/pmml_4_0/test_svm.xml";
private static final String packageName = "org.drools.pmml_4_0.test";
-
+
+
+
+
+ @Test
+ public void testInsertLogicalOnInitialFact() {
+
+ String s1 = "package org.drools.test.agent;\n" +
+ "import org.drools.pmml_4_0.ModelMarker; \n" +
+ "rule \"Init 1\"\n" +
+ "when\n" +
+ "then\n" +
+ " insertLogical( new ModelMarker( \"x\", \"xx\" ) );\n" +
+ "end\n" +
+ "" +
+ "rule MarkerLog\n" +
+ "when\n" +
+ " $m : ModelMarker()\n" +
+ "then\n" +
+ "System.out.println( $m );\n" +
+ "end\n";
+
+
+ String s2 = "package org.drools.test.agent;\n" +
+ "import org.drools.pmml_4_0.ModelMarker; \n" +
+ "rule \"Init 2\"\n" +
+ "when\n" +
+ "then\n" +
+ " insertLogical( new ModelMarker( \"y\", \"yy\" ) );\n" +
+ "end";
+
+
+ String s3 = "package org.drools.test.agent; \n" +
+ "import org.drools.pmml_4_0.ModelMarker; \n" +
+ "rule \"TraitX\"\n" +
+ "salience 1000\n" +
+ "when\n" +
+ " $mm : ModelMarker( modelName == \"x\" ; enabled == true )\n" +
+ "then\n" +
+ " System.out.println( \"Traiting questionnaire X\" );\n" +
+ " org.drools.informer.ISurveyableTrait surv;\n" +
+ " surv = don( $mm, org.drools.informer.ISurveyableTrait.class, true );\n" +
+ " modify ( surv ) {\n" +
+ " setQuestionnaireId( \"xid\" ),\n" +
+ " setStateful( false ),\n" +
+ " setSurveyEnabled( true );\n" +
+ " }\n" +
+ "end\n";
+
+
+
+ KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+ kbuilder.add( ResourceFactory.newClassPathResource( "org/drools/informer/informer-changeset.xml" ), ResourceType.CHANGE_SET );
+ kbuilder.add( new ByteArrayResource( s3.getBytes() ), ResourceType.DRL );
+ if ( kbuilder.hasErrors() ) {
+ fail( kbuilder.getErrors().toString() );
+ }
+ KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+ kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
+
+ KnowledgeAgentConfiguration kaConfig = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
+ kaConfig.setProperty( NewInstanceOption.PROPERTY_NAME, "false" );
+ kaConfig.setProperty( UseKnowledgeBaseClassloaderOption.PROPERTY_NAME, "true" );
+ KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent( "testPmml", kbase, kaConfig );
+
+ StatefulKnowledgeSession ksession = kagent.getKnowledgeBase().newStatefulKnowledgeSession();
+
+ System.out.println("---------------------------------------------------------------------");
+
+ ByteArrayResource bres = (ByteArrayResource) ResourceFactory.newByteArrayResource( s1.getBytes() );
+ bres.setResourceType( ResourceType.DRL );
+
+ ChangeSetImpl cs = new ChangeSetImpl();
+ cs.setResourcesAdded(Arrays.<Resource>asList(bres));
+ kagent.applyChangeSet(cs);
+
+ ksession.fireAllRules();
+
+ System.out.println("---------------------------------------------------------------------");
+
+
+ ByteArrayResource bres2 = (ByteArrayResource) ResourceFactory.newByteArrayResource( s2.getBytes() );
+ bres2.setResourceType( ResourceType.DRL );
+
+ ChangeSetImpl cs2 = new ChangeSetImpl();
+ cs2.setResourcesAdded( Arrays.<Resource> asList( bres2 ) );
+ kagent.applyChangeSet( cs2 );
+ ksession.fireAllRules();
+
+
+ System.out.println("---------------------------------------------------------------------");
+
+ ksession.fireAllRules();
+
+ System.out.println("---------------------------------------------------------------------");
+
+
+ for ( Object o : ksession.getObjects() ) {
+ System.out.println( "**" + o );
+ }
+
+ assertEquals( 4, ksession.getObjects().size() );
+ assertEquals( 2, ksession.getObjects(new ClassObjectFilter( ModelMarker.class )).size() );
+ assertEquals( 1, ksession.getObjects(new ClassObjectFilter( Thing.class )).size() );
+
+ ksession.dispose();
+ kagent.dispose();
+ }
+
+
+
+
+ @Test
+ public void testIncrementalBuilding() throws Exception {
+ KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+ kbuilder.add( ResourceFactory.newClassPathResource( "org/drools/informer/informer-changeset.xml" ), ResourceType.CHANGE_SET );
+ if ( kbuilder.hasErrors() ) {
+ fail( kbuilder.getErrors().toString() );
+ }
+ KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+ kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
+
+
+ KnowledgeBuilder kb1 = KnowledgeBuilderFactory.newKnowledgeBuilder( kbase );
+ kb1.add( ResourceFactory.newClassPathResource( source1 ), ResourceType.PMML );
+ if ( kb1.hasErrors() ) { fail( kb1.getErrors().toString() ); }
+
+ kbase.addKnowledgePackages( kb1.getKnowledgePackages() );
+
+
+ KnowledgeBuilder kb2 = KnowledgeBuilderFactory.newKnowledgeBuilder( kbase );
+ kb2.add( ResourceFactory.newClassPathResource( source2 ), ResourceType.PMML );
+ if ( kb2.hasErrors() ) { fail( kb2.getErrors().toString() ); }
+
+ kbase.addKnowledgePackages( kb2.getKnowledgePackages() );
+
+ StatefulKnowledgeSession kSession = kbase.newStatefulKnowledgeSession();
+ kSession.fireAllRules();
+
+ System.err.println(reportWMObjects(kSession));
+
+ assertEquals( 2, kSession.getObjects( new ClassObjectFilter( ModelMarker.class ) ).size() );
+ assertEquals( 2, kSession.getObjects( new ClassObjectFilter( Questionnaire.class ) ).size() );
+ assertEquals( 11, kSession.getObjects( new ClassObjectFilter( kSession.getKnowledgeBase().getFactType( packageName, "Synapse" ).getFactClass() ) ).size() );
+
+ }
+
+
+
+
+
+
+
@Test
public void testKnowledgeAgentLoadingMultipleANN() throws Exception {
-
+ KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
+ kbuilder.add( ResourceFactory.newClassPathResource( "org/drools/informer/informer-changeset.xml" ), ResourceType.CHANGE_SET );
+ if ( kbuilder.hasErrors() ) {
+ fail( kbuilder.getErrors().toString() );
+ }
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
+ kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
+
KnowledgeAgentConfiguration kaConfig = KnowledgeAgentFactory.newKnowledgeAgentConfiguration();
kaConfig.setProperty( NewInstanceOption.PROPERTY_NAME, "false" );
kaConfig.setProperty( UseKnowledgeBaseClassloaderOption.PROPERTY_NAME, "true" );
KnowledgeAgent kagent = KnowledgeAgentFactory.newKnowledgeAgent( "testPmml", kbase, kaConfig );
+
StatefulKnowledgeSession kSession = kagent.getKnowledgeBase().newStatefulKnowledgeSession();
assertNotNull(kSession);
@@ -90,6 +255,10 @@ public void testKnowledgeAgentLoadingMultipleANN() throws Exception {
System.out.println( " \n\n\n DONE LOADING " + source1 + " \n\n\n " );
+ QueryResults q1 = kSession.getQueryResults( "getQuestionnaireByType", "MockPTSD", Variable.v );
+ assertEquals( 1, q1.size() );
+ Questionnaire ptsdQ = (Questionnaire) q1.iterator().next().get( "$quest" );
+
cs = new ChangeSetHelperImpl();
res = (ClassPathResource) ResourceFactory.newClassPathResource( source2 );
res.setResourceType( ResourceType.PMML );
@@ -110,6 +279,12 @@ public void testKnowledgeAgentLoadingMultipleANN() throws Exception {
kSession.fireAllRules();
+ QueryResults q2 = kSession.getQueryResults( "getQuestionnaireByType", "MockPTSD", Variable.v );
+ assertEquals( 1, q2.size() );
+ Questionnaire ptsdQ2 = (Questionnaire) q2.iterator().next().get( "$quest" );
+
+ assertSame( ptsdQ, ptsdQ2 );
+
System.err.println(reportWMObjects(kSession));
assertEquals( 3, kSession.getObjects( new ClassObjectFilter( ModelMarker.class ) ).size() );
@@ -121,4 +296,62 @@ public void testKnowledgeAgentLoadingMultipleANN() throws Exception {