1   package eu.fbk.dkm.premon.premonitor;
2   
3   import eu.fbk.dkm.premon.vocab.ESO;
4   import eu.fbk.dkm.premon.vocab.FBMETA;
5   import eu.fbk.dkm.premon.vocab.PM;
6   import eu.fbk.dkm.premon.vocab.PMO;
7   import eu.fbk.rdfpro.*;
8   import eu.fbk.rdfpro.util.Algebra;
9   import eu.fbk.rdfpro.util.Namespaces;
10  import eu.fbk.rdfpro.util.QuadModel;
11  import eu.fbk.rdfpro.util.Statements;
12  import org.openrdf.model.*;
13  import org.openrdf.model.vocabulary.RDF;
14  import org.openrdf.model.vocabulary.RDFS;
15  import org.openrdf.query.BindingSet;
16  import org.openrdf.query.MalformedQueryException;
17  import org.openrdf.query.TupleQuery;
18  import org.openrdf.query.algebra.TupleExpr;
19  import org.openrdf.rio.RDFHandler;
20  import org.openrdf.rio.RDFHandlerException;
21  
22  import java.io.File;
23  import java.io.IOException;
24  import java.util.*;
25  import java.util.concurrent.atomic.AtomicInteger;
26  
27  /**
28   * Created by marcorospocher on 08/05/2017.
29   */
30  public class EsoConverter extends Converter {
31  
32  
33  
34      //private HashMap<Resource,Set<URI>> esoCL_fnFrameMAP = new HashMap<Resource,Set<URI>>();
35      private String role_FE_query = "SELECT DISTINCT ?combo ?role\n" +
36              "WHERE { ?eso  <http://www.newsreader-project.eu/domain-ontology#correspondToFrameNetFrame_closeMatch> ?frame . \n" +
37              "	?eso (rdfs:subClassOf|owl:equivalentClass)/owl:hasValue ?rule . \n" +
38              "	?rule <http://www.newsreader-project.eu/domain-ontology#hasSituationRuleAssertion> ?ass . \n" +
39              "	?ass (<http://www.newsreader-project.eu/domain-ontology#hasSituationAssertionObject>|<http://www.newsreader-project.eu/domain-ontology#hasSituationAssertionSubject>) ?role1 .\n" +
40              "	FILTER (str(?role) = str(?role1)) . ?role <http://www.newsreader-project.eu/domain-ontology#correspondToFrameNetElement> ?FE .\n" +
41              "	BIND(IRI(CONCAT(\"[PREFIX][FNV]-\",LCASE(STRAFTER(?frame,\"#\")),\"@\",LCASE(STRAFTER(?FE,\"#\")))) as ?combo)\n" +
42              "}\n" +
43              "ORDER BY ?role ?combo";
44  
45      private ArrayList<String> fnLinks = new ArrayList<>();
46  
47      public EsoConverter(final File path, final RDFHandler sink, final Properties properties,
48                          Map<String, URI> wnInfo) {
49          super(path, properties.getProperty("source"), sink, properties, properties.getProperty("language"), wnInfo);
50  
51          addLinks(fnLinks, properties.getProperty("linkfn"));
52  
53      }
54  
55      @Override
56      public void convert() throws IOException, RDFHandlerException {
57  
58  
59          //read input file(s)
60          try {
61              final QuadModel model = readTriples();
62  
63              LOGGER.info("Read ESO Ontology");
64  
65              final Ruleset tboxRuleset = Ruleset
66                      .fromRDF("classpath:/eu/fbk/dkm/premon/premonitor/ruleset.ttl");
67              RuleEngine.create(tboxRuleset).eval(model);
68  
69              LOGGER.info("ESO TBox Ontology Closure");
70  
71              // processClassesMappings
72              processClassMappings(model, ESO.CORRESPOND_FRAME_CLOSE, PMO.ONTO_MATCH);
73  
74              preocessRoleMappings(model, PMO.ONTO_MATCH);
75  
76  
77  
78  
79          }catch (RDFHandlerException e){
80              throw e;
81          } catch (MalformedQueryException e) {
82              e.printStackTrace();
83          }
84  
85      }
86  
87      private void preocessRoleMappings(QuadModel model, URI premon_prop) throws MalformedQueryException {
88  
89          for (String fnLink:this.fnLinks
90                  ) {
91              TupleExpr query = Algebra.parseTupleExpr(this.role_FE_query.replace("[FNV]",fnLink).replace("[PREFIX]", PM.NAMESPACE), null, Namespaces.DEFAULT.uriMap());
92              Iterator<BindingSet> iterator = model.evaluate(query, null, null);
93              int i = 0;
94              while (iterator.hasNext()) {
95                  i++;
96                  BindingSet resultRow = iterator.next();
97                  URI fnFE = createURI(resultRow.getValue("combo").toString());
98                  URI esoRole = createURI(resultRow.getValue("role").toString());
99  
100                 addStatementToSink(fnFE, premon_prop, esoRole);
101                 addStatementToSink(fnFE, RDF.TYPE, PMO.SEMANTIC_ROLE);
102             }
103             LOGGER.info("Number of Extracted " + fnLink+"-"+this.resource+" Semantic Role ontoMatch: " + i);
104         }
105     }
106 
107     private void processClassMappings(QuadModel model, URI frameBroad_prop, URI premon_prop) {
108 
109         for (String fnLink:this.fnLinks
110                 ) {
111             Iterator<Statement> iter_fb = model.iterator(null, frameBroad_prop, null);
112             int i = 0;
113             while (iter_fb.hasNext()) {
114                 i++;
115                 Statement stmt = iter_fb.next();
116                 final Resource eso = stmt.getSubject();
117                 final Value framenet = stmt.getObject();
118 
119                 LOGGER.debug("subj "+eso.toString());
120                 LOGGER.debug("obj "+framenet.stringValue());
121 
122                 String frame = framenet.stringValue().substring(framenet.stringValue().lastIndexOf("#") + 1).toLowerCase();
123                 URI fnFrameURI = uriForRoleset(frame, fnLink);
124                 LOGGER.debug("frame " + fnFrameURI.toString());
125 
126 
127                 addStatementToSink(fnFrameURI, premon_prop, eso);
128                 addStatementToSink(fnFrameURI, RDF.TYPE, PMO.SEMANTIC_CLASS);
129 
130             }
131             LOGGER.info("Number of Extracted " + fnLink+"-"+this.resource+" Semantic Class ontoMatch: " + i);
132         }
133     }
134 
135 
136 
137 
138     private QuadModel readTriples() throws RDFHandlerException {
139         final QuadModel model = QuadModel.create();
140 
141         for (final File file : this.path.listFiles()) {
142             try {
143 
144                 final AtomicInteger counter = new AtomicInteger();
145                 final RDFSource source = RDFSources.read(false, true, null, null,
146                         file.getAbsolutePath());
147 
148                 source.emit(new AbstractRDFHandler() {
149 
150                             @Override
151                             public void handleStatement(final Statement stmt) throws RDFHandlerException {
152                                 final URI p = stmt.getPredicate();
153                                 final Value o = stmt.getObject();
154                                 model.add(stmt);
155                                 counter.incrementAndGet();
156                             }
157 
158 
159                 }, 1);
160                 LOGGER.info("{} triples read from {}", counter, file);
161             } catch (RDFHandlerException e) {
162                 e.printStackTrace();
163             }
164         }
165         return model;
166 
167     }
168 
169 
170     @Override protected URI getPosURI(String textualPOS) {
171         return null;
172     }
173 
174     @Override public String getArgLabel() {
175         return "";
176     }
177 }