Search in sources :

Example 11 with NamedEntryPoint

use of org.drools.kiesession.entrypoints.NamedEntryPoint in project drools by kiegroup.

the class JTMSTest method testRetractHandleWhenOnlyNeg.

@Test(timeout = 10000)
@Ignore("Currently cannot support updates")
public void testRetractHandleWhenOnlyNeg() {
    String s = "package org.drools.core.beliefsystem.jtms;\n" + "\n" + "import java.util.List \n" + "import org.drools.core.common.AgendaItem;" + "global java.util.List list;\n" + "\n" + "rule \"go1_1\"\n" + "when\n" + "    String( this == 'go1' )\n" + "then\n" + "    insertLogical( new String( 'neg' ), 'neg' );\n" + "end\n" + "rule \"go1_2\"\n" + "when\n" + "    String( this == 'go1' )\n" + "then\n" + "    insertLogical( new String( 'neg' ), 'neg' );\n" + "end\n" + "rule \"go1_3\"\n" + "when\n" + "    String( this == 'go1' )\n" + "then\n" + "    insertLogical( new String( 'neg' ), 'neg' );\n" + "end\n" + "\n" + "rule \"Negative\"\n" + "when\n" + "    $n : String(  _.neg, this != 'go1' || == 'go2' ) \n" + "then\n" + "    final String s = '-' + $n; \n" + "    final List l = list; \n" + "    l.add( s ); \n" + "end\n";
    KieSession kSession = getSessionFromString(s);
    List list = new ArrayList();
    kSession.setGlobal("list", list);
    ((RuleEventManager) kSession).addEventListener(new RuleEventListener() {

        @Override
        public void onDeleteMatch(Match match) {
            String rule = match.getRule().getName();
            if (rule.equals("Negative")) {
                list.remove("-" + match.getDeclarationValue("$n"));
            }
        }
    });
    FactHandle fhGo1 = kSession.insert("go1");
    kSession.fireAllRules();
    assertTrue(list.contains("-neg"));
    // just go1
    assertEquals(1, kSession.getEntryPoint("DEFAULT").getObjects().size());
    assertEquals(1, getNegativeObjects(kSession).size());
    NamedEntryPoint ep = (NamedEntryPoint) ((StatefulKnowledgeSessionImpl) kSession).getEntryPoint("DEFAULT");
    TruthMaintenanceSystem tms = TruthMaintenanceSystemFactory.get().getOrCreateTruthMaintenanceSystem(ep);
    ObjectHashMap equalityMap = tms.getEqualityKeyMap();
    // go1, neg are two different strings.
    assertEquals(2, equalityMap.size());
    org.drools.core.util.Iterator it = equalityMap.iterator();
    TruthMaintenanceSystemEqualityKey key = (TruthMaintenanceSystemEqualityKey) ((ObjectEntry) it.next()).getValue();
    while (!key.getFactHandle().getObject().equals("neg")) {
        key = (TruthMaintenanceSystemEqualityKey) ((ObjectEntry) it.next()).getValue();
    }
    assertEquals(3, key.getBeliefSet().size());
    tms.delete(key.getLogicalFactHandle());
    assertEquals(0, key.getBeliefSet().size());
    // just go1
    assertEquals(1, kSession.getEntryPoint("DEFAULT").getObjects().size());
    assertEquals(0, getNegativeObjects(kSession).size());
    assertEquals(0, key.getBeliefSet().size());
    assertEquals(1, tms.getEqualityKeyMap().size());
}
Also used : TruthMaintenanceSystem(org.drools.core.common.TruthMaintenanceSystem) FactHandle(org.kie.api.runtime.rule.FactHandle) NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) ArrayList(java.util.ArrayList) RuleEventListener(org.kie.internal.event.rule.RuleEventListener) ObjectHashMap(org.drools.core.util.ObjectHashMap) ObjectEntry(org.drools.core.util.ObjectHashMap.ObjectEntry) Match(org.kie.api.runtime.rule.Match) TruthMaintenanceSystemEqualityKey(org.drools.tms.TruthMaintenanceSystemEqualityKey) RuleEventManager(org.kie.internal.event.rule.RuleEventManager) KieSession(org.kie.api.runtime.KieSession) ArrayList(java.util.ArrayList) List(java.util.List) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 12 with NamedEntryPoint

use of org.drools.kiesession.entrypoints.NamedEntryPoint in project drools by kiegroup.

the class BayesBeliefSystemTest method testBayes.

@Test
public void testBayes() {
    String drl = "package org.drools.defeasible; " + "import " + Garden.class.getCanonicalName() + "; \n" + "import " + PropertyReference.class.getCanonicalName() + "; \n" + "global " + BayesModeFactory.class.getCanonicalName() + " bsFactory; \n" + "dialect 'mvel'; \n" + " " + "rule rule1 when " + "        String( this == 'rule1') \n" + "    g : Garden()" + "then " + "    System.out.println(\"rule 1\"); \n" + "    insertLogical( new PropertyReference(g, 'cloudy'), bsFactory.create( new double[] {1.0,0.0} ) ); \n " + "end " + "rule rule2 when " + "        String( this == 'rule2') \n" + "    g : Garden()" + "then " + "    System.out.println(\"rule2\"); \n" + "    insertLogical( new PropertyReference(g, 'sprinkler'), bsFactory.create( new double[] {1.0,0.0} ) ); \n " + "end " + "rule rule3 when " + "        String( this == 'rule3') \n" + "    g : Garden()" + "then " + "    System.out.println(\"rule3\"); \n" + "    insertLogical( new PropertyReference(g, 'sprinkler'), bsFactory.create( new double[] {1.0,0.0} ) ); \n " + "end " + "rule rule4 when " + "        String( this == 'rule4') \n" + "    g : Garden()" + "then " + "    System.out.println(\"rule4\"); \n" + "    insertLogical( new PropertyReference(g, 'sprinkler'), bsFactory.create( new double[] {0.0,1.0} ) ); \n " + "end " + "\n";
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) getSessionFromString(drl);
    NamedEntryPoint ep = (NamedEntryPoint) ksession.getEntryPoint(EntryPointId.DEFAULT.getEntryPointId());
    BayesBeliefSystem bayesBeliefSystem = new BayesBeliefSystem(ep, TruthMaintenanceSystemFactory.get().getOrCreateTruthMaintenanceSystem(ep));
    BayesModeFactoryImpl bayesModeFactory = new BayesModeFactoryImpl(bayesBeliefSystem);
    ksession.setGlobal("bsFactory", bayesModeFactory);
    BayesRuntime bayesRuntime = ksession.getKieRuntime(BayesRuntime.class);
    BayesInstance<Garden> instance = bayesRuntime.createInstance(Garden.class);
    assertNotNull(instance);
    assertTrue(instance.isDecided());
    instance.globalUpdate();
    Garden garden = instance.marginalize();
    assertTrue(garden.isWetGrass());
    FactHandle fh = ksession.insert(garden);
    FactHandle fh1 = ksession.insert("rule1");
    ksession.fireAllRules();
    assertTrue(instance.isDecided());
    // rule1 has added evidence, update the bayes network
    instance.globalUpdate();
    garden = instance.marginalize();
    // grass was wet before rule1 and continues to be wet
    assertTrue(garden.isWetGrass());
    // applies 2 logical insertions
    FactHandle fh2 = ksession.insert("rule2");
    ksession.fireAllRules();
    assertTrue(instance.isDecided());
    instance.globalUpdate();
    garden = instance.marginalize();
    // new evidence means grass is no longer wet
    assertFalse(garden.isWetGrass());
    // adds an additional support for the sprinkler, belief set of 2
    FactHandle fh3 = ksession.insert("rule3");
    ksession.fireAllRules();
    assertTrue(instance.isDecided());
    instance.globalUpdate();
    garden = instance.marginalize();
    // nothing has changed
    assertFalse(garden.isWetGrass());
    // rule4 introduces a conflict, and the BayesFact becomes undecided
    FactHandle fh4 = ksession.insert("rule4");
    ksession.fireAllRules();
    assertFalse(instance.isDecided());
    try {
        instance.globalUpdate();
        fail("The BayesFact is undecided, it should throw an exception, as it cannot be updated.");
    } catch (Exception e) {
    // this should fail
    }
    // the conflict is resolved, so it should be decided again
    ksession.delete(fh4);
    ksession.fireAllRules();
    assertTrue(instance.isDecided());
    instance.globalUpdate();
    garden = instance.marginalize();
    // back to grass is not wet
    assertFalse(garden.isWetGrass());
    // takes the sprinkler belief set back to 1
    ksession.delete(fh2);
    ksession.fireAllRules();
    instance.globalUpdate();
    garden = instance.marginalize();
    // still grass is not wet
    assertFalse(garden.isWetGrass());
    // no sprinkler support now
    ksession.delete(fh3);
    ksession.fireAllRules();
    instance.globalUpdate();
    garden = instance.marginalize();
    // grass is wet again
    assertTrue(garden.isWetGrass());
}
Also used : BayesBeliefSystem(org.drools.beliefs.bayes.BayesBeliefSystem) FactHandle(org.kie.api.runtime.rule.FactHandle) BayesModeFactory(org.drools.beliefs.bayes.BayesModeFactory) StatefulKnowledgeSessionImpl(org.drools.kiesession.session.StatefulKnowledgeSessionImpl) NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) BayesModeFactoryImpl(org.drools.beliefs.bayes.BayesModeFactoryImpl) BayesRuntime(org.drools.beliefs.bayes.runtime.BayesRuntime) Test(org.junit.Test)

Example 13 with NamedEntryPoint

use of org.drools.kiesession.entrypoints.NamedEntryPoint in project drools by kiegroup.

the class IncrementalCompilationCepTest method testObjectTypeNodeExpirationOffset.

@Test
public void testObjectTypeNodeExpirationOffset() {
    // DROOLS-6296
    final String drl1 = "package org.drools.test;\n" + "import " + ParentEvent.class.getCanonicalName() + "\n" + "import " + ChildEventA.class.getCanonicalName() + "\n" + "import " + ChildEventB.class.getCanonicalName() + "\n" + "\n" + "declare ChildEventA\n" + "   @role( event )\n" + "   @timestamp( eventTimestamp )\n" + "   @expires(3d)\n" + "end;\n" + "declare ChildEventB\n" + "   @role( event )\n" + "   @timestamp( eventTimestamp )\n" + "   @expires(30d)\n" + "end;" + "\n" + "rule \"detect ChildEventA\"\n" + "when $e: ChildEventA()\n" + "then\n" + "    System.out.println(\"detect ChildEventA\");\n" + "end\n" + "\n" + "rule \"detect ParentEvent\"\n" + "when $e: ParentEvent()\n" + "then\n" + "   System.out.println(\"detect ParentEvent\");\n" + "end\n" + "rule \"detect ChildEventB\"\n" + "when $e: ChildEventB()\n" + "then\n" + "   System.out.println(\"detect ChildEventB\");\n" + "end";
    // just adding a new fact
    final String drl2 = "package org.drools.test;\n" + "import " + ParentEvent.class.getCanonicalName() + "\n" + "import " + ChildEventA.class.getCanonicalName() + "\n" + "import " + ChildEventB.class.getCanonicalName() + "\n" + "import " + Person.class.getCanonicalName() + "\n" + "\n" + "declare ChildEventA\n" + "   @role( event )\n" + "   @timestamp( eventTimestamp )\n" + "   @expires(3d)\n" + "end;\n" + "declare ChildEventB\n" + "   @role( event )\n" + "   @timestamp( eventTimestamp )\n" + "   @expires(30d)\n" + "end;" + "\n" + "rule \"detect ChildEventA\"\n" + "when $e: ChildEventA()\n" + "then\n" + "    System.out.println(\"detect ChildEventA\");\n" + "end\n" + "\n" + "rule \"detect ParentEvent\"\n" + "when $e: ParentEvent()\n" + "then\n" + "   System.out.println(\"detect ParentEvent\");\n" + "end\n" + "rule \"detect ChildEventB\"\n" + "when $e: ChildEventB()\n" + "then\n" + "   System.out.println(\"detect ChildEventB\");\n" + "end\n" + "rule \"detect a Person\"\n" + "when $p: Person()\n" + "then\n" + "  System.out.println(\"detect a Person\");\n" + "end";
    final KieServices ks = KieServices.Factory.get();
    final ReleaseId releaseId1 = ks.newReleaseId("org.kie", "test-upgrade", "1.0.0");
    KieUtil.getKieModuleFromDrls(releaseId1, kieBaseTestConfiguration, KieSessionTestConfiguration.STATEFUL_PSEUDO, new HashMap<>(), drl1);
    final KieContainer kc = ks.newKieContainer(releaseId1);
    final KieSession kieSession = kc.newKieSession();
    NamedEntryPoint entryPoint = (NamedEntryPoint) kieSession.getEntryPoints().stream().findFirst().get();
    Map<ObjectType, ObjectTypeNode> objectTypeNodes = entryPoint.getEntryPointNode().getObjectTypeNodes();
    // ParentEvent
    ObjectTypeNode parentEventOTN = objectTypeNodes.get(new ClassObjectType(ParentEvent.class));
    assertEquals(-1L, parentEventOTN.getExpirationOffset());
    // ChildEventA
    ObjectTypeNode childEventAOTN = objectTypeNodes.get(new ClassObjectType(ChildEventA.class));
    assertEquals(Duration.of(3, ChronoUnit.DAYS).toMillis() + 1, childEventAOTN.getExpirationOffset());
    // ChildEventB
    ObjectTypeNode childEventBOTN = objectTypeNodes.get(new ClassObjectType(ChildEventB.class));
    assertEquals(Duration.of(30, ChronoUnit.DAYS).toMillis() + 1, childEventBOTN.getExpirationOffset());
    // pseudo clock initialization
    long now = System.currentTimeMillis();
    SessionPseudoClock sessionClock = kieSession.getSessionClock();
    sessionClock.advanceTime(now, TimeUnit.MILLISECONDS);
    ChildEventA childEventA = new ChildEventA(new Date(now), "A");
    kieSession.insert(childEventA);
    kieSession.fireAllRules();
    // ChildEventA expires
    sessionClock.advanceTime(Duration.of(4, ChronoUnit.DAYS).toMillis(), TimeUnit.MILLISECONDS);
    kieSession.fireAllRules();
    // ChildEventA is no longer in WM
    assertEquals(0, kieSession.getFactCount());
    kieSession.dispose();
    final ReleaseId releaseId2 = ks.newReleaseId("org.kie", "test-upgrade", "2.0.0");
    KieUtil.getKieModuleFromDrls(releaseId2, kieBaseTestConfiguration, KieSessionTestConfiguration.STATEFUL_PSEUDO, new HashMap<>(), drl2);
    kc.updateToVersion(releaseId2);
    final KieSession kieSession2 = kc.newKieSession();
    NamedEntryPoint entryPoint2 = (NamedEntryPoint) kieSession2.getEntryPoints().stream().findFirst().get();
    Map<ObjectType, ObjectTypeNode> objectTypeNodes2 = entryPoint2.getEntryPointNode().getObjectTypeNodes();
    // ParentEvent
    ObjectTypeNode parentEventOTN2 = objectTypeNodes2.get(new ClassObjectType(ParentEvent.class));
    assertEquals(-1L, parentEventOTN2.getExpirationOffset());
    // ChildEventA
    ObjectTypeNode childEventAOTN2 = objectTypeNodes2.get(new ClassObjectType(ChildEventA.class));
    assertEquals(Duration.of(3, ChronoUnit.DAYS).toMillis() + 1, childEventAOTN2.getExpirationOffset());
    // ChildEventB
    ObjectTypeNode childEventBOTN2 = objectTypeNodes2.get(new ClassObjectType(ChildEventB.class));
    assertEquals(Duration.of(30, ChronoUnit.DAYS).toMillis() + 1, childEventBOTN2.getExpirationOffset());
    now = System.currentTimeMillis();
    SessionPseudoClock sessionClock2 = kieSession2.getSessionClock();
    sessionClock2.advanceTime(now, TimeUnit.MILLISECONDS);
    ChildEventA childEventA2 = new ChildEventA(new Date(now), "A");
    kieSession2.insert(childEventA2);
    kieSession2.fireAllRules();
    // ChildEventA expires
    sessionClock2.advanceTime(Duration.of(4, ChronoUnit.DAYS).toMillis(), TimeUnit.MILLISECONDS);
    kieSession2.fireAllRules();
    assertEquals(0, kieSession2.getFactCount());
    kieSession2.dispose();
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) SessionPseudoClock(org.kie.api.time.SessionPseudoClock) NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) KieServices(org.kie.api.KieServices) ReleaseId(org.kie.api.builder.ReleaseId) ParentEvent(org.drools.testcoverage.common.model.ParentEvent) Date(java.util.Date) ClassObjectType(org.drools.core.base.ClassObjectType) ObjectType(org.drools.core.spi.ObjectType) ChildEventB(org.drools.testcoverage.common.model.ChildEventB) KieSession(org.kie.api.runtime.KieSession) Person(org.drools.testcoverage.common.model.Person) ChildEventA(org.drools.testcoverage.common.model.ChildEventA) KieContainer(org.kie.api.runtime.KieContainer) Test(org.junit.Test)

Example 14 with NamedEntryPoint

use of org.drools.kiesession.entrypoints.NamedEntryPoint in project drools by kiegroup.

the class BeliefSystemLogicalCallback method execute.

public void execute(ReteEvaluator reteEvaluator) {
    NamedEntryPoint nep = (NamedEntryPoint) handle.getEntryPoint(reteEvaluator);
    BeliefSet bs = ((TruthMaintenanceSystemEqualityKey) handle.getEqualityKey()).getBeliefSet();
    bs.setWorkingMemoryAction(null);
    if (update) {
        if (!bs.isEmpty()) {
            // We need the isEmpty check, in case the BeliefSet was made empty (due to retract) after this was scheduled
            nep.update(handle, handle.getObject(), allSetButTraitBitMask(), Object.class, null);
        }
    } else {
        if (fullyRetract) {
            nep.delete(this.handle, context.getRuleOrigin(), this.activation.getTuple().getTupleSink());
        } else {
            ObjectTypeConf typeConf = nep.getObjectTypeConfigurationRegistry().getOrCreateObjectTypeConf(nep.getEntryPoint(), handle.getObject());
            nep.getEntryPointNode().retractObject(handle, context, typeConf, reteEvaluator);
        }
    }
}
Also used : TruthMaintenanceSystemEqualityKey(org.drools.tms.TruthMaintenanceSystemEqualityKey) ObjectTypeConf(org.drools.core.reteoo.ObjectTypeConf) NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) BeliefSet(org.drools.tms.beliefsystem.BeliefSet)

Example 15 with NamedEntryPoint

use of org.drools.kiesession.entrypoints.NamedEntryPoint in project drools by kiegroup.

the class AlphaNetworkCompilerTest method testNormalizationForAlphaIndexing.

@Test
public void testNormalizationForAlphaIndexing() {
    final String str = "package org.drools.test;\n" + "import " + Person.class.getCanonicalName() + ";\n" + "rule R1 when \n" + " $p : Person(\"Toshiya\" == name)\n" + "then\n" + "end\n" + "rule R2 when \n" + " $p : Person(\"Mario\" == name)\n" + "then\n" + "end\n" + "rule R3 when \n" + " $p : Person(\"Luca\" == name)\n" + "then\n" + "end\n";
    final KieSession ksession = getKieSession(str);
    ObjectTypeNode otn = ((NamedEntryPoint) ksession.getEntryPoint("DEFAULT")).getEntryPointNode().getObjectTypeNodes().entrySet().stream().filter(e -> e.getKey().getClassName().equals(Person.class.getCanonicalName())).map(e -> e.getValue()).findFirst().get();
    ObjectSinkPropagator objectSinkPropagator = otn.getObjectSinkPropagator();
    if (this.testRunType.isAlphaNetworkCompiler()) {
        objectSinkPropagator = ((CompiledNetwork) objectSinkPropagator).getOriginalSinkPropagator();
    }
    CompositeObjectSinkAdapter sinkAdaptor = (CompositeObjectSinkAdapter) objectSinkPropagator;
    assertNotNull(sinkAdaptor.getHashedSinkMap());
    assertEquals(3, sinkAdaptor.getHashedSinkMap().size());
    final Person p = new Person("Toshiya", 45);
    ksession.insert(p);
    assertEquals(1, ksession.fireAllRules());
}
Also used : ObjectSinkPropagator(org.drools.core.reteoo.ObjectSinkPropagator) Assert.assertNotNull(org.junit.Assert.assertNotNull) KieContainer(org.kie.api.runtime.KieContainer) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) AlphaNetworkCompilerOption(org.kie.internal.builder.conf.AlphaNetworkCompilerOption) CompositeObjectSinkAdapter(org.drools.core.reteoo.CompositeObjectSinkAdapter) Serializable(java.io.Serializable) ArrayList(java.util.ArrayList) ReleaseId(org.kie.api.builder.ReleaseId) BigDecimal(java.math.BigDecimal) List(java.util.List) KieModuleModel(org.kie.api.builder.model.KieModuleModel) KieServices(org.kie.api.KieServices) NamedEntryPoint(org.drools.kiesession.entrypoints.NamedEntryPoint) KieSession(org.kie.api.runtime.KieSession) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) Assert.assertEquals(org.junit.Assert.assertEquals) ObjectSinkPropagator(org.drools.core.reteoo.ObjectSinkPropagator) ObjectTypeNode(org.drools.core.reteoo.ObjectTypeNode) KieSession(org.kie.api.runtime.KieSession) CompositeObjectSinkAdapter(org.drools.core.reteoo.CompositeObjectSinkAdapter) Test(org.junit.Test)

Aggregations

NamedEntryPoint (org.drools.kiesession.entrypoints.NamedEntryPoint)18 Test (org.junit.Test)9 KieSession (org.kie.api.runtime.KieSession)8 ArrayList (java.util.ArrayList)6 InternalFactHandle (org.drools.core.common.InternalFactHandle)6 List (java.util.List)5 TruthMaintenanceSystemEqualityKey (org.drools.tms.TruthMaintenanceSystemEqualityKey)5 FactHandle (org.kie.api.runtime.rule.FactHandle)5 WorkingMemoryEntryPoint (org.drools.core.WorkingMemoryEntryPoint)4 ObjectTypeNode (org.drools.core.reteoo.ObjectTypeNode)4 ObjectHashMap (org.drools.core.util.ObjectHashMap)4 ObjectTypeConf (org.drools.core.reteoo.ObjectTypeConf)3 ObjectEntry (org.drools.core.util.ObjectHashMap.ObjectEntry)3 Person (org.drools.mvel.compiler.Person)3 BigDecimal (java.math.BigDecimal)2 Date (java.util.Date)2 ClassObjectType (org.drools.core.base.ClassObjectType)2 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)2 EventFactHandle (org.drools.core.common.EventFactHandle)2 TruthMaintenanceSystem (org.drools.core.common.TruthMaintenanceSystem)2