/
InferringGravsearchTypeInspector.scala
1122 lines (984 loc) · 63.4 KB
/
InferringGravsearchTypeInspector.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright © 2015-2019 the contributors (see Contributors.md).
*
* This file is part of Knora.
*
* Knora is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knora is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with Knora. If not, see <http://www.gnu.org/licenses/>.
*/
package org.knora.webapi.responders.v2.search.gravsearch.types
import akka.event.{LogSource, LoggingAdapter}
import akka.pattern._
import org.knora.webapi._
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.v2.responder.KnoraReadV2
import org.knora.webapi.messages.v2.responder.ontologymessages.{EntityInfoGetRequestV2, EntityInfoGetResponseV2, ReadClassInfoV2, ReadPropertyInfoV2}
import org.knora.webapi.responders.ResponderData
import org.knora.webapi.responders.v2.search._
import org.knora.webapi.util.IriConversions._
import org.knora.webapi.util.{SmartIri, StringFormatter}
import scala.annotation.tailrec
import scala.concurrent.Future
/**
* A Gravsearch type inspector that infers types, relying on information from the relevant ontologies.
*/
class InferringGravsearchTypeInspector(nextInspector: Option[GravsearchTypeInspector],
responderData: ResponderData) extends GravsearchTypeInspector(nextInspector = nextInspector, responderData = responderData) {
import InferringGravsearchTypeInspector._
private val responderManager = responderData.appActor
private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
private val log: LoggingAdapter = akka.event.Logging(system, this)
// The maximum number of type inference iterations.
private val MAX_ITERATIONS = 50
/**
* Represents an inference rule in a pipeline. Each rule in the pipeline tries to determine type information
* about a typeable entity, then calls the next rule in the pipeline.
*
* @param nextRule the next rule in the pipeline.
*/
private abstract class InferenceRule(protected val nextRule: Option[InferenceRule]) {
/**
* Attempts to determine the type of a single entity. Each implementation must end by calling
* `runNextRule`.
*
* @param entityToType the entity whose type needs to be determined.
* @param intermediateResult the current intermediate type inference result.
* @param entityInfo information about Knora ontology entities mentioned in the Gravsearch query.
* @param usageIndex an index of entity usage in the query.
* @return the types that the rule inferred for the entity, or an empty set if no type could be determined.
*/
def infer(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult
/**
* Runs the next rule in the pipeline.
*
* @param entityToType the entity whose type needs to be determined.
* @param intermediateResult this rule's intermediate result.
* @param entityInfo information about Knora ontology entities mentioned in the Gravsearch query.
* @param usageIndex an index of entity usage in the query.
* @return the types that the rule inferred for the entity, or an empty set if no type could be determined.
*/
protected def runNextRule(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
// Is there another rule in the pipeline?
nextRule match {
case Some(rule) =>
// Yes. Run that rule.
rule.infer(
entityToType = entityToType,
intermediateResult = intermediateResult,
entityInfo = entityInfo,
usageIndex = usageIndex
)
case None =>
// No. Return the result we have.
intermediateResult
}
}
}
/**
* Infers the type of an entity if there is an `rdf:type` statement about it.
*/
private class RdfTypeRule(nextRule: Option[InferenceRule]) extends InferenceRule(nextRule = nextRule) {
override def infer(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
// Has this entity been used as a subject?
val inferredTypes: Set[GravsearchEntityTypeInfo] = usageIndex.subjectIndex.get(entityToType) match {
case Some(statements) =>
// Yes. If it's been used with the predicate rdf:type with an IRI object, collect those objects.
val rdfTypes: Set[SmartIri] = statements.collect {
case StatementPattern(_, IriRef(predIri, _), IriRef(objIri, _), _) if predIri.toString == OntologyConstants.Rdf.Type => objIri
}
rdfTypes.flatMap {
rdfType =>
// Is this type a Knora entity?
if (rdfType.isKnoraEntityIri) {
// Yes. Has the ontology responder provided a class definition for it?
entityInfo.classInfoMap.get(rdfType) match {
case Some(classDef) =>
// Yes. Is it a resource class?
if (classDef.isResourceClass) {
// Yes. Infer rdf:type knora-api:Resource.
val inferredType = NonPropertyTypeInfo(InferenceRuleUtil.getResourceTypeIriForSchema(usageIndex.querySchema))
log.debug("RdfTypeRule: {} {} .", entityToType, inferredType)
Some(inferredType)
} else if (classDef.isStandoffClass) {
// It's not a resource class, it's a standoff class. Infer rdf:type knora-api:StandoffTag.
val inferredType = NonPropertyTypeInfo(OntologyConstants.KnoraApiV2Complex.StandoffTag.toSmartIri)
log.debug("RdfTypeRule: {} {} .", entityToType, inferredType)
Some(inferredType)
} else {
val inferredType = NonPropertyTypeInfo(rdfType)
// It's not a resource class or standoff class. Is it valid in a type inspection result?
if (GravsearchTypeInspectionUtil.GravsearchTypeIris.contains(rdfType.toString)) {
// Yes. Return it.
val inferredType = NonPropertyTypeInfo(rdfType)
log.debug("RdfTypeRule: {} {} .", entityToType, inferredType)
Some(inferredType)
} else {
// No. This must mean it's not allowed in Gravsearch queries.
throw GravsearchException(s"Type not allowed in Gravsearch queries: $entityToType $inferredType")
}
}
case None =>
// The ontology responder hasn't provided a definition of this class.
// This should have caused an error earlier from the ontology responder.
throw AssertionException(s"No information found about class ${IriRef(rdfType).toString}")
}
} else if (GravsearchTypeInspectionUtil.GravsearchTypeIris.contains(rdfType.toString)) {
// This isn't a Knora entity. If it's valid in a type inspection result, return it.
val inferredType = NonPropertyTypeInfo(rdfType)
log.debug("RdfTypeRule: {} {} .", entityToType, inferredType)
Some(inferredType)
} else {
None
}
}
case None =>
// This entity hasn't been used as a subject, so this rule isn't relevant.
Set.empty[GravsearchEntityTypeInfo]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, inferredTypes),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers a Knora property's `knora-api:objectType` if the property's IRI is used as a predicate.
*/
private class PropertyIriObjectTypeRule(nextRule: Option[InferenceRule]) extends InferenceRule(nextRule = nextRule) {
override def infer(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
// Is this entity an IRI?
val inferredTypes: Set[GravsearchEntityTypeInfo] = entityToType match {
case TypeableIri(iri) =>
// Yes. Is it a Knora property IRI?
if (usageIndex.knoraPropertyIris.contains(iri)) {
// Yes. Has the ontology responder provided information about it?
entityInfo.propertyInfoMap.get(iri) match {
case Some(readPropertyInfo: ReadPropertyInfoV2) =>
// Yes. Try to infer its knora-api:objectType from the provided information.
InferenceRuleUtil.readPropertyInfoToObjectType(readPropertyInfo, entityInfo, usageIndex.querySchema) match {
case Some(objectTypeIri: SmartIri) =>
val inferredType = PropertyTypeInfo(objectTypeIri = objectTypeIri)
log.debug("PropertyIriObjectTypeRule: {} {} .", entityToType, inferredType)
Set(inferredType)
case None =>
// Its knora-api:objectType couldn't be inferred.
Set.empty[GravsearchEntityTypeInfo]
}
case None =>
// The ontology responder hasn't provided a definition of this property. This should have caused
// an error earlier from the ontology responder.
throw AssertionException(s"No information found about property $iri")
}
} else {
// The IRI isn't a Knora property IRI, so this rule isn't relevant.
Set.empty[GravsearchEntityTypeInfo]
}
case _ =>
// This entity isn't an IRI, so this rule isn't relevant.
Set.empty[GravsearchEntityTypeInfo]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, inferredTypes),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers an entity's type if the entity is used as the object of a statement and the predicate's
* `knora-api:objectType` is known.
*/
private class TypeOfObjectFromPropertyRule(nextRule: Option[InferenceRule]) extends InferenceRule(nextRule = nextRule) {
override def infer(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
// Has this entity been used as the object of one or more statements?
val inferredTypes: Set[GravsearchEntityTypeInfo] = usageIndex.objectIndex.get(entityToType) match {
case Some(statements) =>
// Yes. Try to infer type information from the predicate of each of those statements.
statements.flatMap {
statement =>
// Is the predicate typeable?
GravsearchTypeInspectionUtil.maybeTypeableEntity(statement.pred) match {
case Some(typeablePred: TypeableEntity) =>
// Yes. Do we have its types?
intermediateResult.entities.get(typeablePred) match {
case Some(entityTypes: Set[GravsearchEntityTypeInfo]) =>
// Yes. Use the knora-api:objectType of each PropertyTypeInfo.
entityTypes.flatMap {
case propertyTypeInfo: PropertyTypeInfo =>
val inferredType: GravsearchEntityTypeInfo = NonPropertyTypeInfo(propertyTypeInfo.objectTypeIri)
log.debug("TypeOfObjectFromPropertyRule: {} {} .", entityToType, inferredType)
Some(inferredType)
case _ =>
None
}
case _ =>
// We don't have the predicate's type.
Set.empty[GravsearchEntityTypeInfo]
}
case None =>
// The predicate isn't typeable.
Set.empty[GravsearchEntityTypeInfo]
}
}
case None =>
// This entity hasn't been used as a statement object, so this rule isn't relevant.
Set.empty[GravsearchEntityTypeInfo]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, inferredTypes),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers an entity's type if the entity is used as the subject of a statement, the predicate is an IRI, and
* the predicate's `knora-api:subjectType` is known.
*/
private class TypeOfSubjectFromPropertyRule(nextRule: Option[InferenceRule]) extends InferenceRule(nextRule = nextRule) {
override def infer(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
// Has this entity been used as the subject of one or more statements?
val inferredTypes: Set[GravsearchEntityTypeInfo] = usageIndex.subjectIndex.get(entityToType) match {
case Some(statements) =>
// Yes. Try to infer type information from the predicate of each of those statements.
statements.flatMap {
statement =>
// Is the predicate a Knora IRI, and not a type annotation predicate?
statement.pred match {
case IriRef(predIri, _) if predIri.isKnoraEntityIri && !GravsearchTypeInspectionUtil.TypeAnnotationProperties.allTypeAnnotationIris.contains(predIri.toString) =>
// Yes. Has the ontology responder provided a property definition for it?
entityInfo.propertyInfoMap.get(predIri) match {
case Some(readPropertyInfo: ReadPropertyInfoV2) =>
// Yes. Can we infer the property's knora-api:subjectType from that definition?
InferenceRuleUtil.readPropertyInfoToSubjectType(readPropertyInfo, entityInfo, usageIndex.querySchema) match {
case Some(subjectTypeIri: SmartIri) =>
// Yes. Use that type.
val inferredType = NonPropertyTypeInfo(subjectTypeIri)
log.debug("TypeOfSubjectFromPropertyRule: {} {} .", entityToType, inferredType)
Some(inferredType)
case None =>
// No. This rule can't infer the entity's type.
None
}
case None =>
// The ontology responder hasn't provided a definition of this property. This should have caused
// an error earlier from the ontology responder.
throw AssertionException(s"No information found about property $predIri")
}
case _ =>
// The predicate isn't a Knora IRI, or is a type inspection predicate, so this rule isn't relevant.
None
}
}
case None =>
// This entity hasn't been used as a subject, so this rule isn't relevant.
Set.empty[GravsearchEntityTypeInfo]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, inferredTypes),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers the `knora-api:objectType` of a property variable or IRI if it's used with an object whose type is known.
*/
private class PropertyTypeFromObjectRule(nextRule: Option[InferenceRule]) extends InferenceRule(nextRule = nextRule) {
override def infer(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
// Has this entity been used as a predicate?
val inferredTypes: Set[GravsearchEntityTypeInfo] = usageIndex.predicateIndex.get(entityToType) match {
case Some(statements) =>
// Yes. Try to infer its knora-api:objectType from the object of each of those statements.
statements.flatMap {
statement =>
// Is the object typeable?
GravsearchTypeInspectionUtil.maybeTypeableEntity(statement.obj) match {
case Some(typeableObj: TypeableEntity) =>
// Yes. Do we have its types?
intermediateResult.entities.get(typeableObj) match {
case Some(entityTypes: Set[GravsearchEntityTypeInfo]) =>
// Yes. Use those types.
entityTypes.flatMap {
case nonPropertyTypeInfo: NonPropertyTypeInfo =>
val inferredType: GravsearchEntityTypeInfo = PropertyTypeInfo(nonPropertyTypeInfo.typeIri)
log.debug("PropertyTypeFromObjectRule: {} {} .", entityToType, inferredType)
Some(inferredType)
case _ =>
None
}
case _ =>
// We don't have the object's type.
Set.empty[GravsearchEntityTypeInfo]
}
case None =>
// The object isn't typeable.
Set.empty[GravsearchEntityTypeInfo]
}
}
case None =>
// This entity hasn't been used as a predicate, so this rule isn't relevant.
Set.empty[GravsearchEntityTypeInfo]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, inferredTypes),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers the types of entities from their use in FILTER expressions.
*/
private class EntityTypeFromFilterRule(nextRule: Option[InferenceRule]) extends InferenceRule(nextRule = nextRule) {
override def infer(entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
// Do we have one or more types for this entity from a FILTER?
val typesFromFilters: Set[GravsearchEntityTypeInfo] = usageIndex.typedEntitiesInFilters.get(entityToType) match {
case Some(typesFromFilters: Set[SmartIri]) =>
// Yes. Return those types.
typesFromFilters.map {
typeFromFilter =>
val inferredType = NonPropertyTypeInfo(typeFromFilter)
log.debug("EntityTypeFromFilterRule: {} {} .", entityToType, inferredType)
inferredType
}
case None =>
// We don't have a type for this entity from a FILTER.
Set.empty[GravsearchEntityTypeInfo]
}
// Is this entity a variable?
val typesFromPropertyIriComparisons: Set[GravsearchEntityTypeInfo] = entityToType match {
case variableToType: TypeableVariable =>
// Yes. Has it been used as a predicate?
usageIndex.predicateIndex.get(entityToType) match {
case Some(_) =>
// Yes. Has it been compared with one or more Knora property IRIs in a FILTER?
usageIndex.knoraPropertyVariablesInFilters.get(variableToType) match {
case Some(propertyIris: Set[SmartIri]) =>
// Yes.
propertyIris.flatMap {
propertyIri: SmartIri =>
// Has the ontology responder provided a definition of this property?
entityInfo.propertyInfoMap.get(propertyIri) match {
case Some(readPropertyInfo: ReadPropertyInfoV2) =>
// Yes. Can we determine the property's knora-api:objectType from that definition?
InferenceRuleUtil.readPropertyInfoToObjectType(readPropertyInfo, entityInfo, usageIndex.querySchema) match {
case Some(objectTypeIri: SmartIri) =>
// Yes. Use that type.
val inferredType = PropertyTypeInfo(objectTypeIri = objectTypeIri)
log.debug("EntityTypeFromFilterRule: {} {} .", variableToType, inferredType)
Some(inferredType)
case None =>
// No knora-api:objectType could be determined for the property IRI.
None
}
case None =>
// The ontology responder hasn't provided a definition of this property. This should have caused
// an error earlier from the ontology responder.
throw AssertionException(s"No information found about property $propertyIri")
}
}
case None =>
// The variable hasn't been compared with an IRI in a FILTER.
Set.empty[GravsearchEntityTypeInfo]
}
case None =>
// The variable hasn't been used as a predicate.
Set.empty[GravsearchEntityTypeInfo]
}
case _ =>
// The entity isn't a variable.
Set.empty[GravsearchEntityTypeInfo]
}
val inferredTypes: Set[GravsearchEntityTypeInfo] = typesFromFilters ++ typesFromPropertyIriComparisons
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, inferredTypes),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Utility functions for type inference rules.
*/
private object InferenceRuleUtil {
/**
* Returns knora-api:Resource in the specified schema.
*
* @param querySchema the ontology schema that the query is written in.
*/
def getResourceTypeIriForSchema(querySchema: ApiV2Schema): SmartIri = {
querySchema match {
case ApiV2Simple => OntologyConstants.KnoraApiV2Simple.Resource.toSmartIri
case ApiV2Complex => OntologyConstants.KnoraApiV2Complex.Resource.toSmartIri
}
}
/**
* Returns knora-api:File (if the simple schema is given) or knora-api:FileValue (if the complex schema is given).
*
* @param querySchema the ontology schema that the query is written in.
*/
def getFileTypeForSchema(querySchema: ApiV2Schema): SmartIri = {
querySchema match {
case ApiV2Simple => OntologyConstants.KnoraApiV2Simple.File.toSmartIri
case ApiV2Complex => OntologyConstants.KnoraApiV2Complex.FileValue.toSmartIri
}
}
/**
* Given a [[ReadPropertyInfoV2]], returns the IRI of the inferred `knora-api:subjectType` of the property, if any.
*
* @param readPropertyInfo the property definition.
* @param querySchema the query schema.
* @return the IRI of the inferred `knora-api:subjectType` of the property, or `None` if it could not inferred.
*/
def readPropertyInfoToSubjectType(readPropertyInfo: ReadPropertyInfoV2, entityInfo: EntityInfoGetResponseV2, querySchema: ApiV2Schema): Option[SmartIri] = {
// Is this a resource property?
if (readPropertyInfo.isResourceProp) {
// Yes. Infer knora-api:subjectType knora-api:Resource.
Some(getResourceTypeIriForSchema(querySchema))
} else {
// It's not a resource property. Get the knora-api:subjectType that the ontology responder provided.
readPropertyInfo.entityInfoContent.getPredicateIriObject(OntologyConstants.KnoraApiV2Simple.SubjectType.toSmartIri).
orElse(readPropertyInfo.entityInfoContent.getPredicateIriObject(OntologyConstants.KnoraApiV2Complex.SubjectType.toSmartIri)) match {
case Some(subjectType: SmartIri) =>
val subjectTypeStr = subjectType.toString
// Is it knora-api:Value or one of the knora-api:ValueBase classes?
if (subjectTypeStr == OntologyConstants.KnoraApiV2Complex.Value || OntologyConstants.KnoraApiV2Complex.ValueBaseClasses.contains(subjectTypeStr)) {
// Yes. Don't use it.
None
} else if (OntologyConstants.KnoraApiV2Complex.FileValueClasses.contains(subjectTypeStr)) {
// No. If it's a file value class, return the representation of file values in the specified schema.
Some(getFileTypeForSchema(querySchema))
} else {
// It's not a file value class, either. Is it a standoff class?
val isStandoffClass: Boolean = entityInfo.classInfoMap.get(subjectType) match {
case Some(classDef) => classDef.isStandoffClass
case None => false
}
if (isStandoffClass) {
// Yes. Infer knora-api:subjectType knora-api:StandoffTag.
Some(OntologyConstants.KnoraApiV2Complex.StandoffTag.toSmartIri)
} else if (GravsearchTypeInspectionUtil.GravsearchTypeIris.contains(subjectTypeStr)) {
// It's not any of those. If it's valid in a type inspection result, return it.
Some(subjectType)
} else {
// It's not valid in a type inspection result. This must mean it's not allowed in Gravsearch queries.
throw GravsearchException(s"Type not allowed in Gravsearch queries: ${readPropertyInfo.entityInfoContent.propertyIri} knora-api:subjectType $subjectType")
}
}
case None => None
}
}
}
/**
* Given a [[ReadPropertyInfoV2]], returns the IRI of the inferred `knora-api:objectType` of the property, if any.
*
* @param readPropertyInfo the property definition.
* @param querySchema the ontology schema that the query is written in.
* @return the IRI of the inferred `knora-api:objectType` of the property, or `None` if it could not inferred.
*/
def readPropertyInfoToObjectType(readPropertyInfo: ReadPropertyInfoV2, entityInfo: EntityInfoGetResponseV2, querySchema: ApiV2Schema): Option[SmartIri] = {
// Is this a link property?
if (readPropertyInfo.isLinkProp) {
// Yes. Infer knora-api:objectType knora-api:Resource.
Some(getResourceTypeIriForSchema(querySchema))
} else if (readPropertyInfo.isFileValueProp) {
// No. If it's a file value property, return the representation of file values in the specified schema.
Some(getFileTypeForSchema(querySchema))
} else {
// It's not a link property. Get the knora-api:objectType that the ontology responder provided.
readPropertyInfo.entityInfoContent.getPredicateIriObject(OntologyConstants.KnoraApiV2Simple.ObjectType.toSmartIri).
orElse(readPropertyInfo.entityInfoContent.getPredicateIriObject(OntologyConstants.KnoraApiV2Complex.ObjectType.toSmartIri)) match {
case Some(objectType: SmartIri) =>
val objectTypeStr = objectType.toString
// Is it knora-api:Value?
if (objectTypeStr == OntologyConstants.KnoraApiV2Complex.Value) {
// Yes. Don't use it.
None
} else {
// No. Is it a standoff class?
val isStandoffClass: Boolean = entityInfo.classInfoMap.get(objectType) match {
case Some(classDef) => classDef.isStandoffClass
case None => false
}
if (isStandoffClass) {
// Yes. Infer knora-api:subjectType knora-api:StandoffTag.
Some(OntologyConstants.KnoraApiV2Complex.StandoffTag.toSmartIri)
} else if (GravsearchTypeInspectionUtil.GravsearchTypeIris.contains(objectTypeStr)) {
// It's not any of those. If it's valid in a type inspection result, return it.
Some(objectType)
} else {
// No. This must mean it's not allowed in Gravsearch queries.
throw GravsearchException(s"Type not allowed in Gravsearch queries: ${readPropertyInfo.entityInfoContent.propertyIri} knora-api:objectType $objectType")
}
}
case None => None
}
}
}
}
// The inference rule pipeline for the first iteration. Includes rules that cannot return additional
// information if they are run more than once.
private val firstIterationRulePipeline = new RdfTypeRule(
Some(new PropertyIriObjectTypeRule(
Some(new TypeOfSubjectFromPropertyRule(
Some(new EntityTypeFromFilterRule(
Some(new TypeOfObjectFromPropertyRule(
Some(new PropertyTypeFromObjectRule(None)))))))))))
// The inference rule pipeline for subsequent iterations. Excludes rules that cannot return additional
// if they are run more than once.
private val subsequentIterationRulePipeline = new TypeOfObjectFromPropertyRule(
Some(new PropertyTypeFromObjectRule(None)))
/**
* An index of entity usage in a Gravsearch query.
*
* @param knoraClassIris the Knora class IRIs that are used in the query.
* @param knoraPropertyIris the Knora property IRIs that are used in the query.
* @param subjectIndex a map of all statement subjects to the statements they occur in.
* @param predicateIndex map of all statement predicates to the statements they occur in.
* @param objectIndex a map of all statement objects to the statements they occur in.
* @param knoraPropertyVariablesInFilters a map of query variables to Knora property IRIs that they are compared to in
* FILTER expressions.
* @param typedEntitiesInFilters a map of entities to types found for them in FILTER expressions.
*/
private case class UsageIndex(knoraClassIris: Set[SmartIri] = Set.empty[SmartIri],
knoraPropertyIris: Set[SmartIri] = Set.empty[SmartIri],
subjectIndex: Map[TypeableEntity, Set[StatementPattern]] = Map.empty[TypeableEntity, Set[StatementPattern]],
predicateIndex: Map[TypeableEntity, Set[StatementPattern]] = Map.empty[TypeableEntity, Set[StatementPattern]],
objectIndex: Map[TypeableEntity, Set[StatementPattern]] = Map.empty[TypeableEntity, Set[StatementPattern]],
knoraPropertyVariablesInFilters: Map[TypeableVariable, Set[SmartIri]] = Map.empty[TypeableVariable, Set[SmartIri]],
typedEntitiesInFilters: Map[TypeableEntity, Set[SmartIri]] = Map.empty[TypeableEntity, Set[SmartIri]],
querySchema: ApiV2Schema)
override def inspectTypes(previousResult: IntermediateTypeInspectionResult,
whereClause: WhereClause,
requestingUser: UserADM): Future[IntermediateTypeInspectionResult] = {
log.debug("========== Starting type inference ==========")
for {
// Make an index of entity usage in the query.
usageIndex <- Future(makeUsageIndex(whereClause))
// Ask the ontology responder about all the Knora class and property IRIs mentioned in the query.
initialEntityInfoRequest = EntityInfoGetRequestV2(
classIris = usageIndex.knoraClassIris,
propertyIris = usageIndex.knoraPropertyIris,
requestingUser = requestingUser
)
initialEntityInfo: EntityInfoGetResponseV2 <- (responderManager ? initialEntityInfoRequest).mapTo[EntityInfoGetResponseV2]
// The ontology responder may return the requested information in the internal schema. Convert each entity
// definition back to the input schema.
initialEntityInfoInInputSchemas: EntityInfoGetResponseV2 = convertEntityInfoResponseToInputSchemas(
usageIndex = usageIndex,
entityInfo = initialEntityInfo
)
// Ask the ontology responder about all the Knora classes mentioned as subject or object types of the
// properties returned.
subjectAndObjectTypes: Set[SmartIri] = initialEntityInfoInInputSchemas.propertyInfoMap.foldLeft(Set.empty[SmartIri]) {
case (acc, (propertyIri, propertyDef)) =>
val propertyIriSchema = propertyIri.getOntologySchema match {
case Some(apiV2Schema: ApiV2Schema) => apiV2Schema
case other => throw AssertionException(s"Expected an ApiV2Schema, got $other")
}
val maybeSubjectType: Option[SmartIri] = propertyDef.entityInfoContent.getPredicateIriObject(OntologyConstants.KnoraApi.getSubjectTypePredicate(propertyIriSchema).toSmartIri) match {
case Some(subjectType) if subjectType.isKnoraEntityIri => Some(subjectType)
case _ => None
}
val maybeObjectType: Option[SmartIri] = propertyDef.entityInfoContent.getPredicateIriObject(OntologyConstants.KnoraApi.getObjectTypePredicate(propertyIriSchema).toSmartIri) match {
case Some(objectType) if objectType.isKnoraEntityIri => Some(objectType)
case _ => None
}
acc ++ maybeSubjectType ++ maybeObjectType
}
additionalEntityInfoRequest = EntityInfoGetRequestV2(
classIris = subjectAndObjectTypes,
requestingUser = requestingUser
)
additionalEntityInfo: EntityInfoGetResponseV2 <- (responderManager ? additionalEntityInfoRequest).mapTo[EntityInfoGetResponseV2]
// Add the additional classes to the usage index.
usageIndexWithAdditionalClasses = usageIndex.copy(
knoraClassIris = usageIndex.knoraClassIris ++ subjectAndObjectTypes
)
// The ontology responder may return the requested information in the internal schema. Convert each entity
// definition back to the input schema.
additionalEntityInfoInInputSchemas: EntityInfoGetResponseV2 = convertEntityInfoResponseToInputSchemas(
usageIndex = usageIndexWithAdditionalClasses,
entityInfo = additionalEntityInfo
)
// Combine all the entity info into one object.
allEntityInfo: EntityInfoGetResponseV2 = initialEntityInfoInInputSchemas.copy(
classInfoMap = initialEntityInfoInInputSchemas.classInfoMap ++ additionalEntityInfoInInputSchemas.classInfoMap
)
// Iterate over the inference rules until no new type information can be inferred.
intermediateResult: IntermediateTypeInspectionResult = doIterations(
iterationNumber = 1,
intermediateResult = previousResult,
entityInfo = allEntityInfo,
usageIndex = usageIndexWithAdditionalClasses
)
// Pass the intermediate result to the next type inspector in the pipeline.
lastResult: IntermediateTypeInspectionResult <- runNextInspector(
intermediateResult = intermediateResult,
whereClause = whereClause,
requestingUser = requestingUser
)
} yield lastResult
}
/**
* Given an [[EntityInfoGetResponseV2]], converts each class and property back to the input schema
* found in the usage index.
*
* @param usageIndex the usage index.
* @param entityInfo the [[EntityInfoGetResponseV2]] that was returned by the ontology responder.
* @return an [[EntityInfoGetResponseV2]] in which the classes and properties are represented in the schemas
* found in the usage index.
*/
private def convertEntityInfoResponseToInputSchemas(usageIndex: UsageIndex,
entityInfo: EntityInfoGetResponseV2): EntityInfoGetResponseV2 = {
/**
* Given a map of Knora class or property definitions, converts each one to the schema in which it was requested.
*
* @param inputEntityIris the IRIs of the entities that were requested.
* @param entityMap a map of entity IRIs to entity definitions as returned by the ontology responder.
* @tparam C the entity definition type, which can be [[ReadClassInfoV2]] or [[ReadPropertyInfoV2]].
* @return a map of entity IRIs to entity definitions, with each IRI and definition represented in the
* schema in which it was requested.
*/
def toInputSchema[C <: KnoraReadV2[C]](inputEntityIris: Set[SmartIri], entityMap: Map[SmartIri, C]): Map[SmartIri, C] = {
inputEntityIris.flatMap {
inputEntityIri =>
val inputSchema = inputEntityIri.getOntologySchema.get match {
case apiV2Schema: ApiV2Schema => apiV2Schema
case _ => throw GravsearchException(s"Invalid schema in IRI $inputEntityIri")
}
val maybeReadEntityInfo: Option[C] = entityMap.get(inputEntityIri).orElse {
entityMap.get(inputEntityIri.toOntologySchema(InternalSchema))
}
maybeReadEntityInfo.map {
readEntityInfo => inputEntityIri -> readEntityInfo.toOntologySchema(inputSchema)
}
}.toMap
}
EntityInfoGetResponseV2(
classInfoMap = toInputSchema(usageIndex.knoraClassIris, entityInfo.classInfoMap),
propertyInfoMap = toInputSchema(usageIndex.knoraPropertyIris, entityInfo.propertyInfoMap)
)
}
/**
* Runs all the inference rules repeatedly until no new type information can be found.
*
* @param iterationNumber the current iteration number.
* @param intermediateResult the current intermediate result.
* @param entityInfo information about Knora ontology entities mentioned in the Gravsearch query.
* @param usageIndex an index of entity usage in the query.
* @return a new intermediate result.
*/
@tailrec
private def doIterations(iterationNumber: Int,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex): IntermediateTypeInspectionResult = {
if (iterationNumber > MAX_ITERATIONS) {
throw GravsearchException(s"Too many type inference iterations")
}
// Run an iteration of type inference and get its result.
log.debug(s"****** Inference iteration $iterationNumber (untyped ${intermediateResult.untypedEntities.size}, inconsistent ${intermediateResult.entitiesWithInconsistentTypes.size})")
val iterationResult: IntermediateTypeInspectionResult = intermediateResult.entities.keySet.foldLeft(intermediateResult) {
case (acc: IntermediateTypeInspectionResult, entityToType: TypeableEntity) =>
val pipeline: InferenceRule = if (iterationNumber == 1) {
firstIterationRulePipeline
} else {
subsequentIterationRulePipeline
}
pipeline.infer(
entityToType = entityToType,
intermediateResult = acc,
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
// If no new type information was found, stop.
if (iterationResult == intermediateResult) {
log.debug("No new information, stopping iterations")
intermediateResult
} else {
doIterations(
iterationNumber = iterationNumber + 1,
intermediateResult = iterationResult,
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Creates a usage index from a Gravsearch WHERE clause.
*/
private class UsageIndexCollectingWhereVisitor extends WhereVisitor[UsageIndex] {
/**
* Collects information for the usage index from statements.
*
* @param statementPattern the pattern to be visited.
* @param acc the accumulator.
* @return the accumulator.
*/
override def visitStatementInWhere(statementPattern: StatementPattern, acc: UsageIndex): UsageIndex = {
// Index the statement by subject.
val subjectIndex: Map[TypeableEntity, Set[StatementPattern]] = addIndexEntry(
statementEntity = statementPattern.subj,
statementPattern = statementPattern,
statementIndex = acc.subjectIndex
)
// Index the statement by predicate.
val predicateIndex: Map[TypeableEntity, Set[StatementPattern]] = addIndexEntry(
statementEntity = statementPattern.pred,
statementPattern = statementPattern,
statementIndex = acc.predicateIndex
)
// Index the statement by object.
val objectIndex: Map[TypeableEntity, Set[StatementPattern]] = addIndexEntry(
statementEntity = statementPattern.obj,
statementPattern = statementPattern,
statementIndex = acc.objectIndex
)
// If the statement's predicate is rdf:type, and its object is a Knora entity, add it to the
// set of Knora class IRIs.
val knoraClassIris: Set[SmartIri] = acc.knoraClassIris ++ (statementPattern.pred match {
case IriRef(predIri, _) if predIri.toString == OntologyConstants.Rdf.Type =>
statementPattern.obj match {
case IriRef(objIri, _) if objIri.isKnoraEntityIri =>
Some(objIri)
case _ => None
}
case _ => None
})
// If the statement's predicate is a Knora property, and isn't a type annotation predicate, add it to the set of Knora property IRIs.
val knoraPropertyIris: Set[SmartIri] = acc.knoraPropertyIris ++ (statementPattern.pred match {
case IriRef(predIri, _) if predIri.isKnoraEntityIri && !GravsearchTypeInspectionUtil.TypeAnnotationProperties.allTypeAnnotationIris.contains(predIri.toString) =>
Some(predIri)
case _ => None
})
acc.copy(
knoraClassIris = knoraClassIris,
knoraPropertyIris = knoraPropertyIris,
subjectIndex = subjectIndex,
predicateIndex = predicateIndex,
objectIndex = objectIndex
)
}
/**
* Given a statement pattern and an entity contained in it, checks whether the entity is typeable, and makes an index
* entry if so.
*
* @param statementEntity the entity (subject, predicate, or object).
* @param statementPattern the statement pattern.
* @param statementIndex an accumulator for a statement index.
* @return an updated accumulator.
*/
private def addIndexEntry(statementEntity: Entity,
statementPattern: StatementPattern,
statementIndex: Map[TypeableEntity, Set[StatementPattern]]): Map[TypeableEntity, Set[StatementPattern]] = {
GravsearchTypeInspectionUtil.maybeTypeableEntity(statementEntity) match {
case Some(typeableEntity) =>
val currentPatterns = statementIndex.getOrElse(typeableEntity, Set.empty[StatementPattern])
statementIndex + (typeableEntity -> (currentPatterns + statementPattern))
case None => statementIndex
}
}
/**
* Collects information for the usage index from filters.
*
* @param filterPattern the pattern to be visited.
* @param acc the accumulator.
* @return the accumulator.
*/
override def visitFilter(filterPattern: FilterPattern, acc: UsageIndex): UsageIndex = {
visitFilterExpression(filterPattern.expression, acc)
}
/**
* Collects information for the usage index from filter expressions.
*
* @param filterExpression the filter expression to be visited.
* @param acc the accumulator.
* @return the accumulator.
*/
private def visitFilterExpression(filterExpression: Expression, acc: UsageIndex): UsageIndex = {
filterExpression match {
case compareExpression: CompareExpression =>
compareExpression match {
case CompareExpression(queryVariable: QueryVariable, operator: CompareExpressionOperator.Value, iriRef: IriRef)
if operator == CompareExpressionOperator.EQUALS && iriRef.iri.isKnoraEntityIri =>
// A variable is compared to a Knora entity IRI, which must be a property IRI.
// Index the property IRI.
val typeableVariable = TypeableVariable(queryVariable.variableName)
val currentIris: Set[SmartIri] = acc.knoraPropertyVariablesInFilters.getOrElse(typeableVariable, Set.empty[SmartIri])
acc.copy(
knoraPropertyIris = acc.knoraPropertyIris + iriRef.iri,
knoraPropertyVariablesInFilters = acc.knoraPropertyVariablesInFilters + (typeableVariable -> (currentIris + iriRef.iri))
)
case CompareExpression(queryVariable: QueryVariable, _, xsdLiteral: XsdLiteral) =>
// A variable is compared to an XSD literal. Index the variable and the literal's type.
val typeableVariable = TypeableVariable(queryVariable.variableName)
val currentVarTypesFromFilters: Set[SmartIri] = acc.typedEntitiesInFilters.getOrElse(typeableVariable, Set.empty[SmartIri])
acc.copy(
typedEntitiesInFilters = acc.typedEntitiesInFilters + (typeableVariable -> (currentVarTypesFromFilters + xsdLiteral.datatype))
)
case _ =>
val accFromLeft = visitFilterExpression(compareExpression.leftArg, acc)
visitFilterExpression(compareExpression.rightArg, accFromLeft)
}
case functionCallExpression: FunctionCallExpression =>
// One or more variables are used in functions. Index them and their types, if those can be determined from
// the function.
functionCallExpression.functionIri.iri.toString match {
case OntologyConstants.KnoraApiV2Simple.MatchFunction |
OntologyConstants.KnoraApiV2Simple.MatchTextFunction |
OntologyConstants.KnoraApiV2Complex.MatchFunction =>
// The first argument is a variable representing a string.
val textVar = TypeableVariable(functionCallExpression.getArgAsQueryVar(0).variableName)
val currentTextVarTypesFromFilters: Set[SmartIri] = acc.typedEntitiesInFilters.getOrElse(textVar, Set.empty[SmartIri])
acc.copy(
typedEntitiesInFilters = acc.typedEntitiesInFilters +
(textVar -> (currentTextVarTypesFromFilters + OntologyConstants.Xsd.String.toSmartIri))
)
case OntologyConstants.KnoraApiV2Complex.MatchTextFunction =>
// The first argument is a variable representing a text value.
val textVar = TypeableVariable(functionCallExpression.getArgAsQueryVar(0).variableName)
val currentTextVarTypesFromFilters: Set[SmartIri] = acc.typedEntitiesInFilters.getOrElse(textVar, Set.empty[SmartIri])