Package org.apache.marmotta.kiwi.reasoner.persistence

Examples of org.apache.marmotta.kiwi.reasoner.persistence.KiWiReasoningConnection


     * @throws Exception
     */
    @Test
    public void testIncrementalReasoningConjunction() throws Exception {
        RepositoryConnection con = repository.getConnection();
        KiWiReasoningConnection rcon = rpersistence.getConnection();
        try {
            con.begin();
            // create a triple (ex:a ex:symmetric ex:b); this should trigger rule 2 of the reasoner and add the
            // inverse relationship
            Resource a  = con.getValueFactory().createURI(NS+"a");
            URI      property = con.getValueFactory().createURI(NS+"transitive");
            Resource b   = con.getValueFactory().createURI(NS+"b");
            Resource c   = con.getValueFactory().createURI(NS+"c");
            Resource d   = con.getValueFactory().createURI(NS+"d");

            con.add(a,property,b);
            con.add(b,property,c);
            con.commit();

            // load the statement from the connection so we can add it to the reasoner
            List<Statement> statements = Iterations.asList(con.getStatements(null,property,null, false));
            Assert.assertEquals(2,statements.size());

            // add triples to engine
            TransactionData data = new TransactionData();
            data.getAddedTriples().addAll(statements);
            engine.afterCommit(data);

            // wait for reasoning to complete
            while(engine.isRunning()) {
                log.debug("sleeping for 100ms to let engine finish processing ... ");
                Thread.sleep(100);
            }
            con.begin();

            // after the engine completes, we check whether
            // 1) the expected inferred triple exists (must be (ex:a ex:transitive ex:c) )
            // 2) the inferred triple is properly justified (based on rule2 and on the triple contained in the transaction data)
            List<Statement> inferred = Iterations.asList(con.getStatements(a,property,c, true));
            Assert.assertEquals("number of inferred triples differs from expected result",1,inferred.size());

            KiWiTriple triple = (KiWiTriple)inferred.get(0);
            List<Justification> justifications = Iterations.asList(rcon.listJustificationsForTriple(triple));
            Assert.assertEquals("number of justifications for triple differs from expected result",1,justifications.size());

            Justification j = justifications.get(0);
            Assert.assertEquals("number of supporting triples differs from expected result",2,j.getSupportingTriples().size());
            Assert.assertEquals("number of supporting rules differs from expected result",1,j.getSupportingRules().size());

            Assert.assertThat("supporting triple does not match expectation", j.getSupportingTriples(), hasItem((KiWiTriple)statements.get(0)));
            Assert.assertThat("supporting triple does not match expectation", j.getSupportingTriples(), hasItem((KiWiTriple)statements.get(1)));

            con.commit();


            // add another triple and check if the incremental reasoning works
            con.add(c,property,d);
            con.commit();

            // load the statement from the connection so we can add it to the reasoner
            List<Statement> statements2 = Iterations.asList(con.getStatements(c,property,d, false));
            Assert.assertEquals(1, statements2.size());

            // add triples to engine
            TransactionData data2 = new TransactionData();
            data2.getAddedTriples().addAll(statements2);
            engine.afterCommit(data2);

            // wait for reasoning to complete
            while(engine.isRunning()) {
                log.debug("sleeping for 100ms to let engine finish processing ... ");
                Thread.sleep(100);
            }
            con.begin();


            // after the engine completes, we check whether the expected inferred triples exist
            // (must be (ex:a ex:transitive ex:d) and (ex:b ex:transitive ex:d) )
            List<Statement> inferred2 = Iterations.asList(con.getStatements(a,property,d, true));
            Assert.assertEquals("number of inferred triples differs from expected result", 1, inferred2.size());

            List<Statement> inferred3 = Iterations.asList(con.getStatements(b,property,d, true));
            Assert.assertEquals("number of inferred triples differs from expected result", 1, inferred3.size());


            // now remove again the base triple and inform the reasoner about it, as a consequence, the inferred
            // triple should also be removed
            con.remove(c, property, d);
            con.commit();
            TransactionData data3 = new TransactionData();
            data3.getRemovedTriples().add(statements2.get(0));
            engine.afterCommit(data3);

            // wait for reasoning to complete
            while(engine.isRunning()) {
                log.debug("sleeping for 100ms to let engine finish processing ... ");
                Thread.sleep(100);
            }

            log.debug("reasoning finished, running tests");

            con.begin();

            List<Statement> inferred4 = Iterations.asList(con.getStatements(a,property,d, true));
            Assert.assertEquals("number of inferred triples differs from expected result", 0, inferred4.size());

            List<Statement> inferred5 = Iterations.asList(con.getStatements(b,property,d, true));
            Assert.assertEquals("number of inferred triples differs from expected result", 0, inferred5.size());

            con.commit();
            rcon.commit();
        } finally {
            con.close();
            rcon.close();
        }
    }
View Full Code Here


     * @throws Exception
     */
    @Test
    public void testFullReasoning() throws Exception {
        RepositoryConnection con = repository.getConnection();
        KiWiReasoningConnection rcon = rpersistence.getConnection();
        try {
            // add some triples
            con.begin();

            Resource a   = con.getValueFactory().createURI(NS+"a");
            Resource b   = con.getValueFactory().createURI(NS+"b");
            Resource c   = con.getValueFactory().createURI(NS+"c");
            Resource d   = con.getValueFactory().createURI(NS+"d");
            URI      t   = con.getValueFactory().createURI(NS+"transitive");
            URI      s   = con.getValueFactory().createURI(NS+"symmetric");

            con.add(this.getClass().getResourceAsStream("simple.ttl"),"http://localhost/resource/", RDFFormat.TURTLE);
            con.commit();

            // run the full reasoner
            engine.reRunPrograms();

            // wait for reasoning to complete
            while(engine.isRunning()) {
                log.debug("sleeping for 100ms to let engine finish processing ... ");
                Thread.sleep(100);
            }
            con.begin();

            // after reasoning is finished, we expect to find the following triples:

            Assert.assertTrue("expected inferred triple not found", con.hasStatement(a,t,c,true));
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(b,t,d,true));
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(b,s,a,true));


            // we also expect that there are justifications for all inferred triples
            Resource[][] patterns = new Resource[][] {
                    new Resource[] { a, t, c },
                    new Resource[] { b, t, d },
                    new Resource[] { b, s, a }
            };


            RepositoryResult<Statement> result = con.getStatements(null,null,null,true, con.getValueFactory().createURI(store.getInferredContext()));
            if(result.hasNext()) {
                while (result.hasNext()) {
                    Statement stmt1 = result.next();

                    CloseableIteration<Justification, SQLException> justs1 = rcon.listJustificationsForTriple((KiWiTriple) stmt1);
                    Assert.assertTrue(justs1.hasNext());
                }
            } else {
                fail("no inferred statements found");
            }
            con.commit();
        } finally {
            con.close();
            rcon.close();
        }

    }
View Full Code Here

     * @throws Exception
     */
    //@Test
    public void testAddRemoveRule() throws Exception {
        RepositoryConnection con = repository.getConnection();
        KiWiReasoningConnection rcon = rpersistence.getConnection();
        try {
            // add some triples
            con.begin();

            Resource a   = con.getValueFactory().createURI(NS+"a");
            Resource b   = con.getValueFactory().createURI(NS+"b");
            Resource c   = con.getValueFactory().createURI(NS+"c");
            Resource d   = con.getValueFactory().createURI(NS+"d");
            URI      t   = con.getValueFactory().createURI(NS+"transitive");
            URI      s   = con.getValueFactory().createURI(NS+"symmetric");

            con.add(this.getClass().getResourceAsStream("simple.ttl"),"http://localhost/resource/", RDFFormat.TURTLE);
            con.commit();

            // run the full reasoner
            engine.reRunPrograms();

            // wait for reasoning to complete
            while(engine.isRunning()) {
                log.debug("sleeping for 100ms to let engine finish processing ... ");
                Thread.sleep(100);
            }
            con.begin();

            // after reasoning is finished, we expect to find the following triples:

            Assert.assertTrue("expected inferred triple not found", con.hasStatement(a,t,c,true));
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(b,t,d,true));
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(b,s,a,true));

            con.commit();


            // now we remove the rule2 (symmetric rule) from the program, update the program in the database and then
            // inform the reasoning engine about the removed rule
            Program p = rcon.loadProgram("simple");
            Rule removed = null;
            Iterator<Rule> it = p.getRules().iterator();
            while(it.hasNext()) {
                Rule r = it.next();
                if(r.getName().equals("rule2")) {
                    it.remove();
                    removed = r;
                }
            }
            Assert.assertNotNull("rule 2 not found in program", removed);
            rcon.updateProgram(p);
            rcon.commit();

            engine.notifyRemoveRules();

            // after removing, the inferred symmetric triple should be gone, but the others should still exist
            con.begin();
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(a,t,c,true));
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(b, t, d, true));
            Assert.assertFalse("unexpected inferred triple found", con.hasStatement(b, s, a, true));
            con.commit();


            // let's add the rule again to the program, update the database, and inform the engine
            p.getRules().add(removed);
            rcon.updateProgram(p);
            rcon.commit();

            engine.notifyAddRule(removed);

            // after adding, the inferred symmetric triple should again be present
            con.begin();
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(a,t,c,true));
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(b,t,d,true));
            Assert.assertTrue("expected inferred triple not found", con.hasStatement(b, s, a, true));
            con.commit();

        } finally {
            con.close();
            rcon.close();
        }

    }
View Full Code Here

     * @throws SailException  in case the program already exists
     */
    public void addProgram(Program program) throws SailException {
        // store program in the database
        try {
            KiWiReasoningConnection connection = persistence.getConnection();
            try {
                // should not throw an exception and the program should have a database ID afterwards
                connection.storeProgram(program);
                connection.commit();
            } finally {
                connection.close();
            }
        } catch (SQLException ex) {
            throw new SailException("cannot store program in database",ex);
        }

View Full Code Here

     */
    public void updateProgram(Program program) throws SailException {
        Set<Rule> added = new HashSet<Rule>();
        Set<Rule> removed = new HashSet<Rule>();
        try {
            KiWiReasoningConnection connection = persistence.getConnection();
            try {
                // load old version of program and calculate difference
                Program old = connection.loadProgram(program.getName());
                if(old != null) {
                    for(Rule r : old.getRules()) {
                        if(!program.getRules().contains(r)) {
                            removed.add(r);
                        }
                    }
                    for(Rule r : program.getRules()) {
                        if(!old.getRules().contains(r)) {
                            added.add(r);
                        }
                    }

                }

                // store program in the database
                connection.updateProgram(program);
                connection.commit();
            } finally {
                connection.close();
            }
        } catch (SQLException ex) {
            throw new SailException("cannot store program in database",ex);
        }

View Full Code Here

     *
     * @return
     */
    public CloseableIteration<Program,SailException> listPrograms() throws SailException {
        try {
            final KiWiReasoningConnection connection = persistence.getConnection();

            return new ExceptionConvertingIteration<Program, SailException>(connection.listPrograms()) {
                /**
                 * Converts an exception from the underlying iteration to an exception of
                 * type <tt>X</tt>.
                 */
                @Override
                protected SailException convert(Exception e) {
                    return new SailException(e);
                }

                @Override
                protected void handleClose() throws SailException {
                    super.handleClose();

                    try {
                        connection.commit();
                        connection.close();
                    } catch (SQLException ex) {
                        throw new SailException("database error while committing/closing connection");
                    }
                }
            };
View Full Code Here

     * @return the parsed program, or null in case a program with the given name does not exist
     * @throws SailException  in case an error occurs
     */
    public Program getProgram(String name) throws SailException {
        try {
            KiWiReasoningConnection connection = persistence.getConnection();
            try {
                // should not throw an exception and the program should have a database ID afterwards
                Program p = connection.loadProgram(name);
                connection.commit();
                return p;
            } finally {
                connection.close();
            }
        } catch (SQLException ex) {
            throw new SailException("cannot load program from database",ex);
        }
    }
View Full Code Here

     * @param name the unique name of the program to remove
     * @throws SailException
     */
    public void deleteProgram(String name) throws SailException {
        try {
            KiWiReasoningConnection connection = persistence.getConnection();
            try {
                Program p = connection.loadProgram(name);
                connection.deleteProgram(p);
                connection.commit();
            } finally {
                connection.close();
            }
        } catch (SQLException ex) {
            throw new SailException("cannot load program from database",ex);
        }
        engine.loadPrograms();
View Full Code Here

     * @return
     * @throws SailException
     */
    public CloseableIteration<Justification,SailException> justify(long tripleId) throws SailException {
        try {
            final KiWiReasoningConnection connection = persistence.getConnection();

            return new ExceptionConvertingIteration<Justification, SailException>(connection.listJustificationsForTriple(tripleId)) {
                /**
                 * Converts an exception from the underlying iteration to an exception of
                 * type <tt>X</tt>.
                 */
                @Override
                protected SailException convert(Exception e) {
                    return new SailException(e);
                }

                @Override
                protected void handleClose() throws SailException {
                    super.handleClose();

                    try {
                        connection.commit();
                        connection.close();
                    } catch (SQLException ex) {
                        throw new SailException("database error while committing/closing connection");
                    }
                }
            };
View Full Code Here

        // running the reasoner)
        KWRLProgramParserBase parser = new KWRLProgramParser(v, this.getClass().getResourceAsStream("test-001.kwrl"));
        Program p = parser.parseProgram();
        p.setName("test-001");

        KiWiReasoningConnection connection = rpersistence.getConnection();
        try {
            // should not throw an exception and the program should have a database ID afterwards
            connection.storeProgram(p);
            connection.commit();
        } finally {
            connection.close();
        }

        // then get a connection to the repository and create a number of triples, some inferred and some base
        RepositoryConnection con = repository.getConnection();
        try {
            con.add(s1,p1,o1);
            con.add(s2,p1,o2);
            con.add(s3,p1,o3);

            con.add(s1,p2,o1,ctxi);
            con.add(s2,p2,o2,ctxi);
            con.add(s3,p2,o3,ctxi);

            con.commit();
        } finally {
            con.close();
        }

        connection = rpersistence.getConnection();
        try {
            // retrieve the persisted triples and put them into two sets to build justifications
            List<Statement> baseTriples = asList(connection.listTriples(null,null,null,v.convert(ctxb),false, true));
            List<Statement> infTriples = asList(connection.listTriples(null,null,null,v.convert(ctxi),true, true));

            Assert.assertEquals("number of base triples was not 3", 3, baseTriples.size());
            Assert.assertEquals("number of inferred triples was not 3", 3, infTriples.size());

            // we manually update the "inferred" flag for all inferred triples, since this is not possible through the
            // repository API
            PreparedStatement updateInferred = connection.getJDBCConnection().prepareStatement("UPDATE triples SET inferred = true WHERE id = ?");
            for(Statement stmt : infTriples) {
                KiWiTriple triple = (KiWiTriple)stmt;
                updateInferred.setLong(1,triple.getId());
                updateInferred.addBatch();
            }
            updateInferred.executeBatch();
            updateInferred.close();

            // now we create some justifications for the inferred triples and store them
            Set<Justification> justifications = new HashSet<Justification>();
            Justification j1 = new Justification();
            j1.getSupportingRules().add(p.getRules().get(0));
            j1.getSupportingRules().add(p.getRules().get(1));
            j1.getSupportingTriples().add((KiWiTriple) baseTriples.get(0));
            j1.getSupportingTriples().add((KiWiTriple) baseTriples.get(1));
            j1.setTriple((KiWiTriple) infTriples.get(0));
            justifications.add(j1);

            Justification j2 = new Justification();
            j2.getSupportingRules().add(p.getRules().get(1));
            j2.getSupportingTriples().add((KiWiTriple) baseTriples.get(1));
            j2.getSupportingTriples().add((KiWiTriple) baseTriples.get(2));
            j2.setTriple((KiWiTriple) infTriples.get(1));
            justifications.add(j2);

            connection.storeJustifications(justifications);
            connection.commit();

            // we should now have two justifications in the database
            PreparedStatement listJustifications = connection.getJDBCConnection().prepareStatement("SELECT count(*) AS count FROM reasoner_justifications");
            ResultSet resultListJustifications = listJustifications.executeQuery();

            Assert.assertTrue(resultListJustifications.next());
            Assert.assertEquals(2, resultListJustifications.getInt("count"));
            resultListJustifications.close();
            connection.commit();

            PreparedStatement listSupportingTriples = connection.getJDBCConnection().prepareStatement("SELECT count(*) AS count FROM reasoner_just_supp_triples");
            ResultSet resultListSupportingTriples = listSupportingTriples.executeQuery();

            Assert.assertTrue(resultListSupportingTriples.next());
            Assert.assertEquals(4, resultListSupportingTriples.getInt("count"));
            resultListSupportingTriples.close();
            connection.commit();

            PreparedStatement listSupportingRules = connection.getJDBCConnection().prepareStatement("SELECT count(*) AS count FROM reasoner_just_supp_rules");
            ResultSet resultListSupportingRules = listSupportingRules.executeQuery();

            Assert.assertTrue(resultListSupportingRules.next());
            Assert.assertEquals(3, resultListSupportingRules.getInt("count"));
            resultListSupportingRules.close();
            connection.commit();



            // *** check listing justifications by base triple (supporting triple)

            // there should now be two justifications based on triple baseTriples.get(1))
            List<Justification> supported1 = asList(connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(1)));
            Assert.assertEquals("number of justifications is wrong",2,supported1.size());
            Assert.assertThat("justifications differ", supported1, hasItems(j1,j2));

            // only j1 should be supported by triple baseTriples.get(0))
            List<Justification> supported2 = asList(connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(0)));
            Assert.assertEquals("number of justifications is wrong", 1, supported2.size());
            Assert.assertThat("justifications differ", supported2, allOf(hasItem(j1), not(hasItem(j2))));

            // only j2 should be supported by triple baseTriples.get(2))
            List<Justification> supported3 = asList(connection.listJustificationsBySupporting((KiWiTriple) baseTriples.get(2)));
            Assert.assertEquals("number of justifications is wrong", 1, supported3.size());
            Assert.assertThat("justifications differ", supported3, allOf(hasItem(j2), not(hasItem(j1))));

            // *** check listing justificatoins by supporting rule

            // there should now be two justifications based on triple p.getRules().get(1)
            List<Justification> supported4 = asList(connection.listJustificationsBySupporting(p.getRules().get(1)));
            Assert.assertEquals("number of justifications is wrong", 2, supported4.size());
            Assert.assertThat("justifications differ", supported4, hasItems(j1,j2));

            // only j1 should be supported by triple p.getRules().get(0)
            List<Justification> supported5 = asList(connection.listJustificationsBySupporting(p.getRules().get(0)));
            Assert.assertEquals("number of justifications is wrong", 1, supported5.size());
            Assert.assertThat("justifications differ", supported5, allOf(hasItem(j1), not(hasItem(j2))));


            // *** check listing justifications by supported (inferred) triple

            // there should now be one justification supporting infTriples.get(0)
            List<Justification> supported6 = asList(connection.listJustificationsForTriple((KiWiTriple) infTriples.get(0)));
            Assert.assertEquals("number of justifications is wrong", 1, supported6.size());
            Assert.assertThat("justifications differ", supported6, allOf(hasItem(j1), not(hasItem(j2))));

            // there should now be one justification supporting infTriples.get(1)
            List<Justification> supported7 = asList(connection.listJustificationsForTriple((KiWiTriple) infTriples.get(1)));
            Assert.assertEquals("number of justifications is wrong", 1, supported7.size());
            Assert.assertThat("justifications differ", supported7, allOf(hasItem(j2), not(hasItem(j1))));

            // there should now be no justification supporting infTriples.get(2)
            List<Justification> supported8 = asList(connection.listJustificationsForTriple((KiWiTriple) infTriples.get(2)));
            Assert.assertEquals("number of justifications is wrong", 0, supported8.size());


            // *** check listing unsupported triples
            List<KiWiTriple> unsupported = asList(connection.listUnsupportedTriples());
            Assert.assertEquals("number of unsupported triples is wrong",1,unsupported.size());
            Assert.assertThat("unsupported triples differ", unsupported, hasItem((KiWiTriple)infTriples.get(2)));


            // now we delete justification 2; as a consequence,
            // - there should be only once justification left
            // - there should be two unsupported triples
            connection.deleteJustifications(Collections.singleton(j2));


            // we should now have one justifications in the database
            resultListJustifications = listJustifications.executeQuery();

            Assert.assertTrue(resultListJustifications.next());
            Assert.assertEquals(1, resultListJustifications.getInt("count"));
            resultListJustifications.close();
            connection.commit();

            resultListSupportingTriples = listSupportingTriples.executeQuery();

            Assert.assertTrue(resultListSupportingTriples.next());
            Assert.assertEquals(2, resultListSupportingTriples.getInt("count"));
            resultListSupportingTriples.close();
            connection.commit();

            resultListSupportingRules = listSupportingRules.executeQuery();

            Assert.assertTrue(resultListSupportingRules.next());
            Assert.assertEquals(2, resultListSupportingRules.getInt("count"));
            resultListSupportingRules.close();
            connection.commit();

            List<KiWiTriple> unsupported2 = asList(connection.listUnsupportedTriples());
            Assert.assertEquals("number of unsupported triples is wrong",2,unsupported2.size());
            Assert.assertThat("unsupported triples differ", unsupported2, hasItem((KiWiTriple)infTriples.get(1)));


        } catch(BatchUpdateException ex) {
            if(ex.getNextException() != null) {
                ex.printStackTrace();
                throw ex.getNextException();
            } else {
                throw ex;
            }
        } finally {
            connection.close();
        }

    }
View Full Code Here

TOP

Related Classes of org.apache.marmotta.kiwi.reasoner.persistence.KiWiReasoningConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.