Search in sources :

Example 66 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class FieldConstraintTest method testPredicateConstraint.

/**
 * <pre>
 *
 *                (Cheese (price ?price1 )
 *                (Cheese (price ?price2&amp;:(= ?price2 (* 2 ?price1) )
 *
 * </pre>
 */
@Test
public void testPredicateConstraint() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final InternalReadAccessor priceExtractor = store.getReader(Cheese.class, "price");
    Pattern pattern = new Pattern(0, new ClassObjectType(Cheese.class));
    // Bind the extractor to a decleration
    // Declarations know the pattern they derive their value form
    final Declaration price1Declaration = new Declaration("price1", priceExtractor, pattern);
    pattern = new Pattern(1, new ClassObjectType(Cheese.class));
    // Bind the extractor to a decleration
    // Declarations know the pattern they derive their value form
    final Declaration price2Declaration = new Declaration("price2", priceExtractor, pattern);
    final PredicateExpression evaluator = new PredicateExpression() {

        private static final long serialVersionUID = 510l;

        public boolean evaluate(InternalFactHandle handle, Tuple tuple, Declaration[] previousDeclarations, Declaration[] localDeclarations, WorkingMemory workingMemory, Object context) {
            int price1 = previousDeclarations[0].getIntValue((InternalWorkingMemory) workingMemory, tuple.getObject(previousDeclarations[0]));
            int price2 = localDeclarations[0].getIntValue((InternalWorkingMemory) workingMemory, handle.getObject());
            return (price2 == (price1 * 2));
        }

        public Object createContext() {
            return null;
        }

        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        }

        public void writeExternal(ObjectOutput out) throws IOException {
        }
    };
    final PredicateConstraint constraint1 = new PredicateConstraint(evaluator, new Declaration[] { price1Declaration }, new Declaration[] { price2Declaration });
    final Cheese cheddar0 = new Cheese("cheddar", 5);
    final InternalFactHandle f0 = (InternalFactHandle) ksession.insert(cheddar0);
    LeftTupleImpl tuple = new LeftTupleImpl(f0, null, true);
    final Cheese cheddar1 = new Cheese("cheddar", 10);
    final InternalFactHandle f1 = (InternalFactHandle) ksession.insert(cheddar1);
    tuple = new LeftTupleImpl(tuple, new RightTupleImpl(f1, null), null, true);
    final PredicateContextEntry context = (PredicateContextEntry) constraint1.createContextEntry();
    context.updateFromTuple(ksession, tuple);
    assertTrue(constraint1.isAllowedCachedLeft(context, f1));
}
Also used : ClassObjectType(org.drools.core.base.ClassObjectType) ObjectOutput(java.io.ObjectOutput) WorkingMemory(org.drools.core.WorkingMemory) InternalWorkingMemory(org.drools.core.common.InternalWorkingMemory) Cheese(org.drools.core.test.model.Cheese) PredicateExpression(org.drools.core.spi.PredicateExpression) RightTupleImpl(org.drools.core.reteoo.RightTupleImpl) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) PredicateContextEntry(org.drools.core.rule.PredicateConstraint.PredicateContextEntry) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) InternalReadAccessor(org.drools.core.spi.InternalReadAccessor) LeftTupleImpl(org.drools.core.reteoo.LeftTupleImpl) ObjectInput(java.io.ObjectInput) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Tuple(org.drools.core.spi.Tuple) Test(org.junit.Test)

Example 67 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class FieldConstraintTest method testPrimitiveLiteralConstraint.

/**
 * <pre>
 *
 *                Cheese( price == 5 )
 *
 * </pre>
 */
@Test
public void testPrimitiveLiteralConstraint() {
    InternalKnowledgeBase kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kBase.newKieSession();
    final ClassFieldReader extractor = store.getReader(Cheese.class, "price");
    final MvelConstraint constraint = new MvelConstraintTestUtil("price == 5", FieldFactory.getInstance().getFieldValue(5), extractor);
    final Cheese cheddar = new Cheese("cheddar", 5);
    final InternalFactHandle cheddarHandle = (InternalFactHandle) ksession.insert(cheddar);
    // check constraint
    assertTrue(constraint.isAllowed(cheddarHandle, ksession));
    final Cheese stilton = new Cheese("stilton", 10);
    final InternalFactHandle stiltonHandle = (InternalFactHandle) ksession.insert(stilton);
    // check constraint
    assertFalse(constraint.isAllowed(stiltonHandle, ksession));
}
Also used : ClassFieldReader(org.drools.core.base.ClassFieldReader) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) MvelConstraint(org.drools.core.rule.constraint.MvelConstraint) Cheese(org.drools.core.test.model.Cheese) InternalFactHandle(org.drools.core.common.InternalFactHandle) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 68 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl 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 69 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl in project drools by kiegroup.

the class BayesRuntimeTest method testBayesRuntimeManager.

@Test
public void testBayesRuntimeManager() throws Exception {
    KnowledgeBuilderImpl kbuilder = new KnowledgeBuilderImpl();
    kbuilder.add(ResourceFactory.newClassPathResource("Garden.xmlbif", AssemblerTest.class), ResourceType.BAYES);
    InternalKnowledgeBase kbase = getKnowledgeBase();
    kbase.addPackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSessionImpl ksession = (StatefulKnowledgeSessionImpl) kbase.newKieSession();
    BayesRuntime bayesRuntime = ksession.getKieRuntime(BayesRuntime.class);
    BayesInstance<Garden> instance = bayesRuntime.createInstance(Garden.class);
    assertNotNull(instance);
}
Also used : KnowledgeBuilderImpl(org.drools.compiler.builder.impl.KnowledgeBuilderImpl) StatefulKnowledgeSessionImpl(org.drools.core.impl.StatefulKnowledgeSessionImpl) BayesRuntime(org.drools.beliefs.bayes.runtime.BayesRuntime) InternalKnowledgeBase(org.drools.core.impl.InternalKnowledgeBase) Test(org.junit.Test)

Example 70 with StatefulKnowledgeSessionImpl

use of org.drools.core.impl.StatefulKnowledgeSessionImpl 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)

Aggregations

StatefulKnowledgeSessionImpl (org.drools.core.impl.StatefulKnowledgeSessionImpl)84 Test (org.junit.Test)63 InternalKnowledgeBase (org.drools.core.impl.InternalKnowledgeBase)41 KieSession (org.kie.api.runtime.KieSession)24 ArrayList (java.util.ArrayList)22 InternalFactHandle (org.drools.core.common.InternalFactHandle)22 List (java.util.List)20 DefaultFactHandle (org.drools.core.common.DefaultFactHandle)17 KieBaseConfiguration (org.kie.api.KieBaseConfiguration)17 ClassObjectType (org.drools.core.base.ClassObjectType)14 FactHandle (org.kie.api.runtime.rule.FactHandle)14 KieBase (org.kie.api.KieBase)13 HashMap (java.util.HashMap)9 InternalWorkingMemory (org.drools.core.common.InternalWorkingMemory)8 LeftTupleImpl (org.drools.core.reteoo.LeftTupleImpl)8 BuildContext (org.drools.core.reteoo.builder.BuildContext)8 Cheese (org.drools.core.test.model.Cheese)8 KnowledgeBuilder (org.kie.internal.builder.KnowledgeBuilder)7 RuleDescr (org.drools.compiler.lang.descr.RuleDescr)6 TruthMaintenanceSystem (org.drools.core.common.TruthMaintenanceSystem)6