Search in sources :

Example 26 with NamedEntryPoint

use of org.drools.core.common.NamedEntryPoint in project drools by kiegroup.

the class StatefulKnowledgeSessionImpl method updateEntryPointsCache.

// ------------------------------------------------------------
// Instance methods
// ------------------------------------------------------------
public void updateEntryPointsCache() {
    if (kBase.getAddedEntryNodeCache() != null) {
        for (EntryPointNode addedNode : kBase.getAddedEntryNodeCache()) {
            EntryPointId id = addedNode.getEntryPoint();
            if (EntryPointId.DEFAULT.equals(id))
                continue;
            WorkingMemoryEntryPoint wmEntryPoint = new NamedEntryPoint(id, addedNode, this);
            entryPoints.put(id.getEntryPointId(), wmEntryPoint);
        }
    }
    if (kBase.getRemovedEntryNodeCache() != null) {
        for (EntryPointNode removedNode : kBase.getRemovedEntryNodeCache()) {
            entryPoints.remove(removedNode.getEntryPoint().getEntryPointId());
        }
    }
}
Also used : EntryPointNode(org.drools.core.reteoo.EntryPointNode) EntryPointId(org.drools.core.rule.EntryPointId) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) WorkingMemoryEntryPoint(org.drools.core.WorkingMemoryEntryPoint) InternalWorkingMemoryEntryPoint(org.drools.core.common.InternalWorkingMemoryEntryPoint)

Example 27 with NamedEntryPoint

use of org.drools.core.common.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, ep.getTruthMaintenanceSystem());
    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.core.impl.StatefulKnowledgeSessionImpl) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) BayesModeFactoryImpl(org.drools.beliefs.bayes.BayesModeFactoryImpl) BayesRuntime(org.drools.beliefs.bayes.runtime.BayesRuntime) Test(org.junit.Test)

Example 28 with NamedEntryPoint

use of org.drools.core.common.NamedEntryPoint in project drools by kiegroup.

the class ProtobufOutputMarshaller method serializeSession.

private static ProtobufMessages.KnowledgeSession serializeSession(MarshallerWriteContext context) throws IOException {
    StatefulKnowledgeSessionImpl wm = (StatefulKnowledgeSessionImpl) context.wm;
    try {
        wm.getLock().lock();
        for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
            if (ep instanceof NamedEntryPoint) {
                ((NamedEntryPoint) ep).lock();
            }
        }
        evaluateRuleActivations(wm);
        ProtobufMessages.RuleData.Builder _ruleData = ProtobufMessages.RuleData.newBuilder();
        long time = 0;
        if (context.wm.getTimerService() instanceof PseudoClockScheduler) {
            time = context.clockTime;
        }
        _ruleData.setLastId(wm.getFactHandleFactory().getId());
        _ruleData.setLastRecency(wm.getFactHandleFactory().getRecency());
        InternalFactHandle handle = context.wm.getInitialFactHandle();
        if (handle != null) {
            // can be null for RETE, if fireAllRules has not yet been called
            ProtobufMessages.FactHandle _ifh = ProtobufMessages.FactHandle.newBuilder().setType(ProtobufMessages.FactHandle.HandleType.INITIAL_FACT).setId(handle.getId()).setRecency(handle.getRecency()).build();
            _ruleData.setInitialFact(_ifh);
        }
        writeAgenda(context, _ruleData);
        writeNodeMemories(context, _ruleData);
        for (EntryPoint wmep : wm.getWorkingMemoryEntryPoints().values()) {
            org.drools.core.marshalling.impl.ProtobufMessages.EntryPoint.Builder _epb = ProtobufMessages.EntryPoint.newBuilder();
            _epb.setEntryPointId(wmep.getEntryPointId());
            writeObjectTypeConfiguration(context, ((WorkingMemoryEntryPoint) wmep).getObjectTypeConfigurationRegistry(), _epb);
            writeFactHandles(context, _epb, ((NamedEntryPoint) wmep).getObjectStore());
            writeTruthMaintenanceSystem(context, wmep, _epb);
            _ruleData.addEntryPoint(_epb.build());
        }
        writeActionQueue(context, _ruleData);
        ProtobufMessages.KnowledgeSession.Builder _session = ProtobufMessages.KnowledgeSession.newBuilder().setMultithread(false).setTime(time).setRuleData(_ruleData.build());
        if (processMarshaller != null) {
            Builder _pdata = ProtobufMessages.ProcessData.newBuilder();
            if (context.marshalProcessInstances) {
                context.parameterObject = _pdata;
                processMarshaller.writeProcessInstances(context);
            }
            if (context.marshalWorkItems) {
                context.parameterObject = _pdata;
                processMarshaller.writeWorkItems(context);
            }
            // this now just assigns the writer, it will not write out any timer information
            context.parameterObject = _pdata;
            processMarshaller.writeProcessTimers(context);
            _session.setProcessData(_pdata.build());
        }
        Timers _timers = writeTimers(context.wm.getTimerService().getTimerJobInstances(context.wm.getIdentifier()), context);
        if (_timers != null) {
            _session.setTimers(_timers);
        }
        return _session.build();
    } finally {
        for (WorkingMemoryEntryPoint ep : wm.getWorkingMemoryEntryPoints().values()) {
            if (ep instanceof NamedEntryPoint) {
                ((NamedEntryPoint) ep).unlock();
            }
        }
        wm.getLock().unlock();
    }
}
Also used : NamedEntryPoint(org.drools.core.common.NamedEntryPoint) Builder(org.drools.core.marshalling.impl.ProtobufMessages.ProcessData.Builder) FactHandle(org.drools.core.marshalling.impl.ProtobufMessages.FactHandle) WorkingMemoryEntryPoint(org.drools.core.WorkingMemoryEntryPoint) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) WorkingMemoryEntryPoint(org.drools.core.WorkingMemoryEntryPoint) PseudoClockScheduler(org.drools.core.time.impl.PseudoClockScheduler) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) InternalFactHandle(org.drools.core.common.InternalFactHandle) Timers(org.drools.core.marshalling.impl.ProtobufMessages.Timers)

Example 29 with NamedEntryPoint

use of org.drools.core.common.NamedEntryPoint in project drools by kiegroup.

the class ProtobufOutputMarshaller method writeTruthMaintenanceSystem.

public static void writeTruthMaintenanceSystem(MarshallerWriteContext context, EntryPoint wmep, ProtobufMessages.EntryPoint.Builder _epb) throws IOException {
    TruthMaintenanceSystem tms = ((NamedEntryPoint) wmep).getTruthMaintenanceSystem();
    ObjectHashMap justifiedMap = tms.getEqualityKeyMap();
    if (!justifiedMap.isEmpty()) {
        EqualityKey[] keys = new EqualityKey[justifiedMap.size()];
        org.drools.core.util.Iterator it = justifiedMap.iterator();
        int i = 0;
        for (org.drools.core.util.ObjectHashMap.ObjectEntry entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next(); entry != null; entry = (org.drools.core.util.ObjectHashMap.ObjectEntry) it.next()) {
            EqualityKey key = (EqualityKey) entry.getKey();
            keys[i++] = key;
        }
        Arrays.sort(keys, EqualityKeySorter.instance);
        ProtobufMessages.TruthMaintenanceSystem.Builder _tms = ProtobufMessages.TruthMaintenanceSystem.newBuilder();
        // write the assert map of Equality keys
        for (EqualityKey key : keys) {
            ProtobufMessages.EqualityKey.Builder _key = ProtobufMessages.EqualityKey.newBuilder();
            _key.setStatus(key.getStatus());
            _key.setHandleId(key.getFactHandle().getId());
            if (key.size() > 1) {
                // add all the other key's if they exist
                FastIterator keyIter = key.fastIterator();
                for (DefaultFactHandle handle = key.getFirst().getNext(); handle != null; handle = (DefaultFactHandle) keyIter.next(handle)) {
                    _key.addOtherHandle(handle.getId());
                }
            }
            if (key.getBeliefSet() != null) {
                writeBeliefSet(context, key.getBeliefSet(), _key);
            }
            _tms.addKey(_key.build());
        }
        _epb.setTms(_tms.build());
    }
}
Also used : TruthMaintenanceSystem(org.drools.core.common.TruthMaintenanceSystem) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) ObjectHashMap(org.drools.core.util.ObjectHashMap) WorkingMemoryEntryPoint(org.drools.core.WorkingMemoryEntryPoint) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) EntryPoint(org.kie.api.runtime.rule.EntryPoint) DefaultFactHandle(org.drools.core.common.DefaultFactHandle) EqualityKey(org.drools.core.common.EqualityKey) FastIterator(org.drools.core.util.FastIterator)

Example 30 with NamedEntryPoint

use of org.drools.core.common.NamedEntryPoint in project drools by kiegroup.

the class DefaultKnowledgeHelper method bolster.

public InternalFactHandle bolster(final Object object, final Object value) {
    if (object == null || !activation.isMatched()) {
        return null;
    }
    InternalFactHandle handle = getFactHandleFromWM(object);
    NamedEntryPoint ep = (NamedEntryPoint) workingMemory.getEntryPoint(EntryPointId.DEFAULT.getEntryPointId());
    ObjectTypeConf otc = ep.getObjectTypeConfigurationRegistry().getObjectTypeConf(ep.getEntryPoint(), object);
    BeliefSystem beliefSystem;
    if (value == null) {
        beliefSystem = workingMemory.getTruthMaintenanceSystem().getBeliefSystem();
    } else {
        if (value instanceof Mode) {
            Mode m = (Mode) value;
            beliefSystem = (BeliefSystem) m.getBeliefSystem();
        } else {
            beliefSystem = workingMemory.getTruthMaintenanceSystem().getBeliefSystem();
        }
    }
    BeliefSet beliefSet = null;
    if (handle == null) {
        handle = workingMemory.getKnowledgeBase().getConfiguration().getComponentFactory().getFactHandleFactoryService().newFactHandle(object, otc, workingMemory, ep);
    }
    if (handle.getEqualityKey() == null) {
        handle.setEqualityKey(new EqualityKey(handle, EqualityKey.STATED));
    } else {
        beliefSet = handle.getEqualityKey().getBeliefSet();
    }
    if (beliefSet == null) {
        beliefSet = beliefSystem.newBeliefSet(handle);
        handle.getEqualityKey().setBeliefSet(beliefSet);
    }
    return beliefSystem.insert(beliefSystem.asMode(value), activation.getRule(), activation, object, beliefSet, activation.getPropagationContext(), otc).getFactHandle();
}
Also used : ObjectTypeConf(org.drools.core.reteoo.ObjectTypeConf) EqualityKey(org.drools.core.common.EqualityKey) NamedEntryPoint(org.drools.core.common.NamedEntryPoint) SimpleMode(org.drools.core.beliefsystem.simple.SimpleMode) Mode(org.kie.api.internal.runtime.beliefs.Mode) BeliefSystem(org.drools.core.beliefsystem.BeliefSystem) BeliefSet(org.drools.core.beliefsystem.BeliefSet) InternalFactHandle(org.drools.core.common.InternalFactHandle)

Aggregations

NamedEntryPoint (org.drools.core.common.NamedEntryPoint)32 Test (org.junit.Test)21 KieSession (org.kie.api.runtime.KieSession)19 EqualityKey (org.drools.core.common.EqualityKey)17 TruthMaintenanceSystem (org.drools.core.common.TruthMaintenanceSystem)17 ObjectHashMap (org.drools.core.util.ObjectHashMap)16 InternalFactHandle (org.drools.core.common.InternalFactHandle)13 FactHandle (org.kie.api.runtime.rule.FactHandle)12 Iterator (org.drools.core.util.Iterator)10 FactType (org.kie.api.definition.type.FactType)10 ArrayList (java.util.ArrayList)9 Person (org.drools.compiler.Person)6 WorkingMemoryEntryPoint (org.drools.core.WorkingMemoryEntryPoint)5 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)5 Ignore (org.junit.Ignore)5 List (java.util.List)4 ObjectTypeConf (org.drools.core.reteoo.ObjectTypeConf)4 KieBase (org.kie.api.KieBase)4 Collection (java.util.Collection)3 StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)3