/*
(c) Copyright 2008 Hewlett-Packard Development Company, LP
All rights reserved.
$Id$
*/
package com.hp.jena.ymris.translations;
import static com.hp.hpl.jena.graph.test.GraphTestBase.*;
import java.io.*;
import java.util.*;
import org.junit.Test;
import com.hp.hpl.jena.graph.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.reasoner.*;
import com.hp.hpl.jena.reasoner.rulesys.*;
import com.hp.hpl.jena.reasoner.rulesys.Rule;
import com.hp.hpl.jena.shared.*;
import com.hp.hpl.jena.vocabulary.ReasonerVocabulary;
import com.hp.jena.ymris.deploy.reasoner.DirectReasoner;
import com.hp.jena.ymris.grammar.*;
import com.hp.jena.ymris.util.Pair;
import com.hp.jena.ymris.yast.*;
/**
Compile jena2 rules into corresponding jena3 rules.
@author kers
*/
public class translate
{
public static void main( String [] args ) throws ParseException, IOException
{
new translate().translateOwlFBrules();
}
@Test public void testCase() throws IOException, ParseException
{
compareRulesFrom( "testing/t1.rules" );
}
private void translateOwlFBrules() throws ParseException, IOException
{
compareRulesFrom( "etc/owl-fb.rules" );
}
private void compareRulesFrom( String rulesFile ) throws IOException, ParseException
{
List<Rule> rules = Rule.rulesFromURL( rulesFile );
TwoStage s = translateGroup( rules );
String x = asYmrisString( s, "poggles" );
stringToFile( "J2.rules", x );
Graph g = translateRules( x );
Model m = ModelFactory.createModelForGraph( g );
// m.write( System.out,"TTL" );
GenericRuleReasoner grr = new GenericRuleReasoner( rules );
// grr.setTransitiveClosureCaching( false );
InfGraph ig = grr.bind( graphWith( "" ) );
shouldBeTheSame( ig, g );
}
private void shouldBeTheSame( InfGraph grrg, Graph netG )
{
Set<Triple> igTriples = grrg.find( Triple.ANY ).toSet();
Set<Triple> gTriples = netG.find( Triple.ANY ).toSet();
System.err.println( ">> ig: #" + igTriples.size() + ", g: #" + gTriples.size() );
Set<Triple> igWithoutG = new HashSet<Triple>( igTriples );
igWithoutG.removeAll( gTriples );
Set<Triple> gWithoutIg = new HashSet<Triple>( gTriples );
gWithoutIg.removeAll( igTriples );
System.err.println( ">> ig-g: #" + igWithoutG.size() + ", g-ig: #" + gWithoutIg.size() );
for (Triple t: igWithoutG) System.err.println( "]] ig-only: " + t );
for (Triple t: gWithoutIg) System.err.println( "]] net-only: " + t );
}
private void stringToFile( String fileName, String x ) throws IOException
{
FileOutputStream fos = new FileOutputStream( new File( fileName ) );
PrintStream ps = new PrintStream( fos );
ps.print( x );
ps.close();
fos.close();
}
private Graph translateRules( String rules ) throws ParseException
{
Ymris y = new Ymris( new StringReader( rules ) );
YAST yast = y.ymris();
List<RuleSet> ruleSets = yast.ruleSets();
RuleSet A = ruleSets.get(0), B = ruleSets.get(1);
// Net B = YASTtoNet.rulesetToNet( ruleSets.get( 1 ) );
Graph base = graphWith( "" );
InfGraph igA = new DirectReasoner( A ).bind( base );
igA.size();
igA.getPrefixMapping()
.setNsPrefix( "xsd", "http://www.w3.org/2001/XMLSchema#" )
.setNsPrefix( "rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#" )
.setNsPrefix( "rdfs", "http://www.w3.org/2000/01/rdf-schema#" )
.setNsPrefix( "rb", "urn:x-hp-jena:rubrik/xsdBase" )
;
ModelFactory.createModelForGraph( igA ).write( System.err, "TTL" );
InfGraph igB = new DirectReasoner( B ).bind( igA );
igB.size();
return igB;
}
public static class TwoStage extends Pair<List<AbsRule>, List<AbsRule>>
{
public TwoStage( List<AbsRule> a, List<AbsRule> b )
{ super( a, b ); }
}
public TwoStage translateGroup( List<Rule> rules )
{
List<AbsRule> forwards = new ArrayList<AbsRule>();
List<AbsRule> backwards = new ArrayList<AbsRule>();
for (Rule r: rules)
{
AbsRule translated = AbsRule.translateRule( r );
if (translated.isBackwards)
backwards.add( translated );
else if (translated.backwards.isEmpty())
forwards.add( translated );
else
{
assert translated.backwards.size() == 1;
AbsRule backward = translated.backwards.get(0);
AbsRule rejoined = AbsRule.create
( translated.name
, false
, both( translated.premises, backward.premises )
, both( translated.filters, backward.filters )
, both( translated.conclusion, backward.conclusion )
, both( translated.actions, backward.actions )
, new ArrayList<AbsRule>()
);
backwards.add( rejoined );
}
}
return new TwoStage( forwards, backwards );
}
public void toYmrisFile( TwoStage s, String baseName, File to )
{
FileOutputStream fos = outToFile( to );
PrintStream out = new PrintStream( fos );
printAsYmris( s, baseName, out );
out.flush();
close( fos );
}
private void close( FileOutputStream fos )
{
try { fos.close(); }
catch (IOException e) { throw new WrappedIOException( e ); }
}
private FileOutputStream outToFile( File to )
{
try { return new FileOutputStream( to ); }
catch (FileNotFoundException e) { throw new NotFoundException( to.toString() ); }
}
public String asYmrisString( TwoStage s, String baseName )
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream out = new PrintStream( bos );
printAsYmris( s, baseName, out );
out.flush();
return bos.toString();
}
public void printAsYmris( TwoStage s, String baseName, PrintStream out )
{
prettily( out, baseName + " (forwards)", s.getA() );
prettily( out, baseName + " (backwards)", s.getB() );
}
private <T> List<T> both( List<T> a, List<T> b )
{
List<T> result = new ArrayList<T>( a );
result.addAll( b );
return result;
}
private void prettily( PrintStream out, String name, List<AbsRule> rules )
{
out.println( "RULESET \"" + name + "\"" );
prettilyPrefixes( out );
for (AbsRule a: rules) prettily( out, a );
}
private void prettilyPrefixes( PrintStream out )
{
PrefixMapping pm = PrefixMapping.Factory.create()
.setNsPrefixes( PrefixMapping.Standard )
.setNsPrefix( "rb", ReasonerVocabulary.getRBNamespace() )
;
for (String prefix: pm.getNsPrefixMap().keySet())
{
out.println( "PREFIX " + prefix + ": <" + pm.getNsPrefixURI( prefix ) + ">" );
}
}
private void prettily( PrintStream out, AbsRule a )
{
List<Expression> deferred = new ArrayList<Expression>();
out.println( " RULE " + prettyName( a.name ) );
out.print( " { " );
prettily( out, a.premises );
prettilyFilter( out, a.filters, deferred );
out.println( " }" );
out.print( " => " );
prettilyAction( out, deferred, a.actions );
out.print( "{ " );
prettily( out, fixMakeInstance( a.conclusion, deferred ) );
out.println( " }" );
}
private List<Term> fixMakeInstance( List<Term> conclusions, List<Expression> deferred )
{
if (deferred.size() == 1 && conclusions.size() == 1)
{
Expression mi = deferred.get(0);
Node [] args = mi.args;
int length = args.length;
Node x = args[0], p = args[1];
Node t = args[length - 1], d = length == 3 ? null : args[2];
Term c = conclusions.get(0);
List<Term> result = new ArrayList<Term>();
result.add( reviseForMakeInstance( c, x, p, d, t ) );
return result;
}
else if (conclusions.size() == 0)
{
return conclusions;
}
else
return conclusions;
}
private Term reviseForMakeInstance( Term c, Node x, Node p, Node d, Node t )
{
Item bnode = new BNode( d );
if (c.o.node.equals( t ))
{ // should be (x p t)
return new Term( c.s, c.p, bnode );
}
else
{ // should be (t type something)
return new Term( bnode, c.p, c.o );
}
}
private String prettyName( String name )
{
return name == null ? "" : "\"" + name + "\""; }
private void prettilyAction( PrintStream out, List<Expression> deferred, List<Expression> actions )
{
String gap = "";
for (int i = 0; i < deferred.size(); i += 1)
{
Expression e = deferred.get(i);
if (e.name.equals( "hide" ))
{
actions.add( 0, e );
deferred.remove( i );
}
else if (e.name.equals( "makeTemp" ))
{
actions.add( 0, makeLetAnon( e.args[0] ) );
deferred.remove( i );
}
}
if (!actions.isEmpty())
{
// System.err.println( ">> ACTIONS: " + actions );
}
for (Expression action: actions)
{
if (action.name.equals( "tableAll" ))
{
// supress
}
else
{
action.prettily( this, " DO ", out );
}
}
}
private Expression makeLetAnon( final Node letVar )
{
return new Expression( "letAnon", new Node[]{ letVar } )
{
@Override public void prettily( translate translate, String tag, PrintStream out )
{
out.print( "LET " );
translate.prettyNode( out, letVar );
out.print( " = " );
out.print( "jena2:newAnon( )" );
}
};
}
private void prettilyFilter( PrintStream out, List<Expression> filters, List<Expression> deferred )
{
for (Expression f: filters )
{
String name = f.name;
if (name.equals( "makeInstance" ) || name.equals( "hide" ) || name.equals( "makeTemp" ))
{
deferred.add( f );
}
else
{
f.prettily( this, " FILTER ", out );
}
}
}
public void prettyNode( PrintStream out, Node arg )
{
if (arg.isURI()) printURI( out, arg );
else if (arg.isLiteral()) prettilyLiteral( out, arg );
else out.print( arg );
}
private void printURI( PrintStream out, Node arg )
{
String uri = arg.getURI();
String compressed = AbsRule.prefixes.qnameFor( uri );
out.print( compressed.equals( uri ) ? "<" + uri + ">" : compressed );
}
private void prettilyLiteral( PrintStream out, Node arg )
{
if (arg.getLiteralDatatypeURI().equals( "urn:x-hp-jena:Functor" ))
{
out.print( "$F_" );
out.print( angled( arg.getLiteralLexicalForm() ) );
}
else
out.print( Item.literal( arg ) );
}
private String angled( String spelling )
{
return spelling.replaceAll( "\\^\\^([^ )]+)", "^^<$1>" ).replaceAll( " ", ", ");
}
private void prettily( PrintStream out, List<Term> terms )
{
String dot = "";
for (Term t: terms)
{
out.print( dot );
dot = ". ";
prettily( out, t );
}
}
private void prettily( PrintStream out, Term t )
{
prettily( out, t.s );
out.print( " " );
prettily( out, t.p );
out.print( " " );
prettily( out, t.o );
}
private void prettily( PrintStream out, Item o )
{
Node arg = o.node;
if (o instanceof BNode)
{
((BNode) o).asYmris( out );
}
else
{
if (arg.isURI()) printURI( out, arg );
else if (arg.isLiteral()) prettilyLiteral( out, arg );
else out.print( arg );
}
}
}
/*
(c) Copyright 2009 Hewlett-Packard Development Company, LP
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/