/
InferringGravsearchTypeInspector.scala
1656 lines (1470 loc) · 73.2 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 © 2021 - 2022 Swiss National Data and Service Center for the Humanities and/or DaSCH Service Platform contributors.
* SPDX-License-Identifier: Apache-2.0
*/
package org.knora.webapi.messages.util.search.gravsearch.types
import akka.event.{LogSource, LoggingAdapter}
import akka.pattern._
import org.knora.webapi._
import org.knora.webapi.exceptions.{AssertionException, GravsearchException}
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.util.ResponderData
import org.knora.webapi.messages.util.search._
import org.knora.webapi.messages.v2.responder.KnoraReadV2
import org.knora.webapi.messages.v2.responder.ontologymessages.{
EntityInfoGetRequestV2,
EntityInfoGetResponseV2,
ReadClassInfoV2,
ReadPropertyInfoV2
}
import org.knora.webapi.messages.{OntologyConstants, 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 InferTypeOfSubjectOfRdfTypePredicate(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. Use that class as the inferred type.
val inferredType = NonPropertyTypeInfo(classDef.entityInfoContent.classIri, isResourceType = true)
log.debug("InferTypeOfSubjectOfRdfTypePredicate: {} {} .", entityToType, inferredType)
Some(inferredType)
} else if (classDef.isStandoffClass) {
val inferredType =
NonPropertyTypeInfo(classDef.entityInfoContent.classIri, isStandoffTagType = true)
log.debug("InferTypeOfSubjectOfRdfTypePredicate: {} {} .", entityToType, inferredType)
Some(inferredType)
} else {
// It's not a resource class or standoff class. Is it valid in a type inspection result?
if (GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(rdfType.toString)) {
// Yes. Return it.
val inferredType = NonPropertyTypeInfo(rdfType, isValueType = true)
log.debug("InferTypeOfSubjectOfRdfTypePredicate: {} {} .", 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")
}
}
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.GravsearchValueTypeIris.contains(rdfType.toString)) {
// This isn't a Knora entity. If it's valid in a type inspection result, return it.
val inferredType = NonPropertyTypeInfo(rdfType, isValueType = true)
log.debug("InferTypeOfSubjectOfRdfTypePredicate: {} {} .", 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 the `knora-api:objectType` of a property if the property's IRI is used as a predicate.
*/
private class InferTypeOfPropertyFromItsIri(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.
val inferredObjectTypes: Set[GravsearchEntityTypeInfo] = InferenceRuleUtil
.readPropertyInfoToObjectType(readPropertyInfo, entityInfo, usageIndex.querySchema)
.toSet
log.debug("InferTypeOfPropertyFromItsIri: {} {} .", entityToType, inferredObjectTypes.mkString(", "))
inferredObjectTypes
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 InferTypeOfObjectFromPredicate(nextRule: Option[InferenceRule])
extends InferenceRule(nextRule = nextRule) {
override def infer(
entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex
): IntermediateTypeInspectionResult = {
// for standoff links it is necessary to refine the determined types first. TODO: why in this rule and not in all rules?
val updatedIntermediateResult: IntermediateTypeInspectionResult = refineDeterminedTypes(
intermediateResult = intermediateResult,
entityInfo = entityInfo
)
/**
* Performs the inference for this rule on a set of statements.
*/
def inferFromStatements(statements: Set[StatementPattern]): Set[GravsearchEntityTypeInfo] =
statements.flatMap { statement =>
// Is the predicate typeable?
GravsearchTypeInspectionUtil.maybeTypeableEntity(statement.pred) match {
case Some(typeablePred: TypeableEntity) =>
// Yes. Do we have its types?
updatedIntermediateResult.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 = propertyTypeInfo.toNonPropertyTypeInfo
log.debug("InferTypeOfObjectFromPredicate: {} {} .", 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]
}
}
// Has this entity been used as the object of one or more statements?
usageIndex.objectIndex.get(entityToType) match {
case Some(statements: Set[StatementPattern]) =>
// Yes. Try to infer type information from the predicate of each of those statements.
// To keep track of which types are inferred from IRIs representing properties, and which ones
// are inferred from variables representing properties, partition the statements into ones whose
// predicates are IRIs and ones whose predicates are variables.
val (statementsWithPropertyIris, statementsWithVariablesAsPredicates) = statements.partition { statement =>
statement.pred match {
case _: IriRef => true
case _ => false
}
}
// Separately infer types from statements whose predicates are IRIs and statements whose
// predicates are variables.
val typesInferredFromPropertyIris: Set[GravsearchEntityTypeInfo] = inferFromStatements(
statementsWithPropertyIris
)
val typesInferredFromVariablesAsPredicates: Set[GravsearchEntityTypeInfo] = inferFromStatements(
statementsWithVariablesAsPredicates
)
// If any types were inferred from statements whose predicates are IRIs, update the
// intermediate type inspection result with that information.
val intermediateResultWithTypesInferredFromPropertyIris = if (typesInferredFromPropertyIris.nonEmpty) {
updatedIntermediateResult.addTypes(
entityToType,
typesInferredFromPropertyIris,
inferredFromPropertyIri = true
)
} else {
updatedIntermediateResult
}
val intermediateResultWithTypesInferredFromVariablesAsPredicates =
intermediateResultWithTypesInferredFromPropertyIris.addTypes(
entityToType,
typesInferredFromVariablesAsPredicates
)
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResultWithTypesInferredFromVariablesAsPredicates,
entityInfo = entityInfo,
usageIndex = usageIndex
)
case None =>
// This entity hasn't been used as a statement object, so this rule isn't relevant.
runNextRule(
entityToType = entityToType,
intermediateResult = updatedIntermediateResult,
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
}
/**
* Infers an entity's type if the entity is used as the subject of a statement in which the predicate is a
* property IRI whose `knora-api:subjectType` is known.
*/
private class InferTypeOfSubjectFromPredicateIri(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. Try to get the property's knora-api:subjectType from that definition,
// and infer that type as the type of the entity.
InferenceRuleUtil
.readPropertyInfoToSubjectType(readPropertyInfo, entityInfo, usageIndex.querySchema)
.map(_.toNonPropertyTypeInfo)
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 annotation 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, inferredFromPropertyIri = true),
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 InferTypeOfPredicateFromObject(nextRule: Option[InferenceRule])
extends InferenceRule(nextRule = nextRule) {
override def infer(
entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex
): IntermediateTypeInspectionResult = {
// for standoff links it is necessary to refine the types first. TODO: why in this rule and not in all rules?
val updatedIntermediateResult: IntermediateTypeInspectionResult = refineDeterminedTypes(
intermediateResult = intermediateResult,
entityInfo = entityInfo
)
// 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?
updatedIntermediateResult.entities.get(typeableObj) match {
case Some(entityTypes: Set[GravsearchEntityTypeInfo]) =>
// Yes. Use those types.
val alreadyInferredPropertyTypes: Set[PropertyTypeInfo] =
updatedIntermediateResult.entities.getOrElse(entityToType, Set.empty).collect {
case propertyTypeInfo: PropertyTypeInfo => propertyTypeInfo
}
entityTypes.flatMap {
case nonPropertyTypeInfo: NonPropertyTypeInfo =>
// Is this type a subclass of an object type that we already have for this property,
// which we may have got from the property's definition in an ontology?
val baseClassesOfInferredType: Set[SmartIri] =
entityInfo.classInfoMap.get(nonPropertyTypeInfo.typeIri) match {
case Some(classDef) => classDef.allBaseClasses.toSet
case None => Set.empty
}
val isSubclassOfAlreadyInferredType: Boolean = alreadyInferredPropertyTypes.exists {
alreadyInferredType: PropertyTypeInfo =>
baseClassesOfInferredType.contains(alreadyInferredType.objectTypeIri)
}
if (!isSubclassOfAlreadyInferredType) {
// No. Use the inferred type.
val inferredType: GravsearchEntityTypeInfo = nonPropertyTypeInfo.toPropertyTypeInfo
log.debug("InferTypeOfPredicateFromObject: {} {} .", entityToType, inferredType)
Some(inferredType)
} else {
// Yes. Don't infer the more specific type for the property.
None
}
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 = updatedIntermediateResult.addTypes(entityToType, inferredTypes),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers the types of entities if their type was already determined by examining a FILTER expression when
* constructing the usage index.
*/
private class InferTypeOfEntityFromKnownTypeInFilter(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: SmartIri =>
val isValueType = GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(typeFromFilter.toString)
val isStandoffTagType = typeFromFilter.toString == OntologyConstants.KnoraApiV2Complex.StandoffTag
val isResourceType = !(isValueType || isStandoffTagType)
val inferredType = NonPropertyTypeInfo(
typeFromFilter,
isResourceType = isResourceType,
isValueType = isValueType,
isStandoffTagType = isStandoffTagType
)
log.debug("InferTypeOfEntityFromKnownTypeInFilter: {} {} .", entityToType, inferredType)
inferredType
}
case None =>
// We don't have a type for this entity from a FILTER.
Set.empty[GravsearchEntityTypeInfo]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, typesFromFilters),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers a variable's type if it has been compared with a property IRI in a FILTER expression.
*/
private class InferTypeOfVariableFromComparisonWithPropertyIriInFilter(nextRule: Option[InferenceRule])
extends InferenceRule(nextRule = nextRule) {
override def infer(
entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex
): IntermediateTypeInspectionResult = {
val typesFromComparisons: Set[GravsearchEntityTypeInfo] = entityToType match {
// Is this entity a variable?
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. Try to determine the property's knora-api:objectType from that definition.
InferenceRuleUtil
.readPropertyInfoToObjectType(readPropertyInfo, entityInfo, usageIndex.querySchema)
.toSet
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]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, typesFromComparisons),
entityInfo = entityInfo,
usageIndex = usageIndex
)
}
}
/**
* Infers the type of a variable or IRI that has been compared with another variable or IRI in a FILTER expression.
*/
private class InferTypeOfEntityFromComparisonWithOtherEntityInFilter(nextRule: Option[InferenceRule])
extends InferenceRule(nextRule = nextRule) {
override def infer(
entityToType: TypeableEntity,
intermediateResult: IntermediateTypeInspectionResult,
entityInfo: EntityInfoGetResponseV2,
usageIndex: UsageIndex
): IntermediateTypeInspectionResult = {
// Has this entity been compared with one or more other entities in a FILTER?
val typesFromComparisons: Set[GravsearchEntityTypeInfo] =
usageIndex.entitiesComparedInFilters.get(entityToType) match {
case Some(comparedEntities: Set[TypeableEntity]) =>
// Yes. Get the types that have been inferred for those entities, if any.
val inferredTypes = comparedEntities.flatMap(comparedEntity => intermediateResult.entities(comparedEntity))
if (inferredTypes.nonEmpty) {
log.debug("InferTypeOfEntityFromComparisonWithOtherEntityInFilter: {} {} .", entityToType, inferredTypes)
}
inferredTypes
case None =>
// This entity hasn't been compared with other entities in a FILTER.
Set.empty[GravsearchEntityTypeInfo]
}
runNextRule(
entityToType = entityToType,
intermediateResult = intermediateResult.addTypes(entityToType, typesFromComparisons),
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[PropertyTypeInfo] =
// 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 a resource class?
if (readPropertyInfo.isResourceProp) {
// Yes. Use it.
Some(PropertyTypeInfo(subjectType, objectIsResourceType = true))
} else if (
subjectTypeStr == OntologyConstants.KnoraApiV2Complex.Value || OntologyConstants.KnoraApiV2Complex.ValueBaseClasses
.contains(subjectTypeStr)
) {
// If it's knora-api:Value or one of the knora-api:ValueBase classes, don't use it.
None
} else if (OntologyConstants.KnoraApiV2Complex.FileValueClasses.contains(subjectTypeStr)) {
// If it's a file value class, return the representation of file values in the specified schema.
Some(PropertyTypeInfo(getFileTypeForSchema(querySchema), objectIsValueType = true))
} else {
// It's not any of those types. Is it a standoff class?
val isStandoffClass: Boolean = entityInfo.classInfoMap.get(subjectType) match {
case Some(classDef) => classDef.isStandoffClass
case None => false
}
if (isStandoffClass) {
// Yes. Return it as a standoff tag type.
Some(PropertyTypeInfo(subjectType, objectIsStandoffTagType = true))
} else if (GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(subjectTypeStr)) {
// It's not any of those. If it's a value type, return it.
Some(PropertyTypeInfo(subjectType, objectIsValueType = true))
} 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 =>
// Subject type of the predicate is not known but this is a resource property?
if (readPropertyInfo.isResourceProp) {
// Yes. Infer knora-api:subjectType knora-api:Resource.
Some(PropertyTypeInfo(getResourceTypeIriForSchema(querySchema), objectIsResourceType = true))
} else 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[PropertyTypeInfo] =
// Is this a file value property?
if (readPropertyInfo.isFileValueProp) {
// Yes, return the representation of file values in the specified schema.
Some(PropertyTypeInfo(getFileTypeForSchema(querySchema), objectIsValueType = true))
} 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. Return it as a standoff tag type.
Some(PropertyTypeInfo(objectType, objectIsStandoffTagType = true))
} else if (readPropertyInfo.isLinkProp) { // No. Is this a link property?
// Yes. Return it as a resource type.
Some(PropertyTypeInfo(objectType, objectIsResourceType = true))
} else if (GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(objectTypeStr)) {
// It's not any of those. If it's a value type, return it.
Some(PropertyTypeInfo(objectType, objectIsValueType = true))
} 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. It's important that InferTypeOfPropertyFromItsIri
// is run before InferTypeOfPredicateFromObject, so that the latter doesn't add a subtype of a type
// already added by the former.
private val firstIterationRulePipeline = new InferTypeOfSubjectOfRdfTypePredicate(
Some(
new InferTypeOfPropertyFromItsIri(
Some(
new InferTypeOfSubjectFromPredicateIri(
Some(
new InferTypeOfEntityFromKnownTypeInFilter(
Some(
new InferTypeOfVariableFromComparisonWithPropertyIriInFilter(
Some(new InferTypeOfObjectFromPredicate(Some(new InferTypeOfPredicateFromObject(None))))
)
)
)
)
)
)
)
)
)
// The inference rule pipeline for subsequent iterations. Excludes rules that cannot return additional
// information if they are run more than once.
private val subsequentIterationRulePipeline = new InferTypeOfObjectFromPredicate(
Some(new InferTypeOfPredicateFromObject(Some(new InferTypeOfEntityFromComparisonWithOtherEntityInFilter(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.
* @param entitiesComparedInFilters variables or IRIs that are compared to other variables or IRIs in FILTER expressions.
*/
case class UsageIndex(
knoraClassIris: Set[SmartIri] = Set.empty,
knoraPropertyIris: Set[SmartIri] = Set.empty,
subjectIndex: Map[TypeableEntity, Set[StatementPattern]] = Map.empty,
predicateIndex: Map[TypeableEntity, Set[StatementPattern]] = Map.empty,
objectIndex: Map[TypeableEntity, Set[StatementPattern]] = Map.empty,
knoraPropertyVariablesInFilters: Map[TypeableVariable, Set[SmartIri]] = Map.empty,
typedEntitiesInFilters: Map[TypeableEntity, Set[SmartIri]] = Map.empty,
entitiesComparedInFilters: Map[TypeableEntity, Set[TypeableEntity]] = Map.empty,
querySchema: ApiV2Schema
)
override def inspectTypes(
previousResult: IntermediateTypeInspectionResult,
whereClause: WhereClause,
requestingUser: UserADM
): Future[IntermediateTypeInspectionResult] = {
log.debug("========== Starting type inference ==========")
for {
// get index of entity usage in the query and ontology information about all the Knora class and property IRIs mentioned in the query
(usageIndex, allEntityInfo) <- getUsageIndexAndEntityInfos(whereClause, requestingUser)
// Iterate over the inference rules until no new type information can be inferred.
intermediateResult: IntermediateTypeInspectionResult = doIterations(
iterationNumber = 1,
intermediateResult = previousResult,
entityInfo = allEntityInfo,
usageIndex = usageIndex
)
// refine the determined types before sending to the next inspector
refinedIntermediateResult: IntermediateTypeInspectionResult = refineDeterminedTypes(
intermediateResult = intermediateResult,
entityInfo = allEntityInfo
)
// sanitize the inconsistent resource types inferred for an entity
sanitizedResults: IntermediateTypeInspectionResult = sanitizeInconsistentResourceTypes(
refinedIntermediateResult,
usageIndex.querySchema,
entityInfo = allEntityInfo
)
// Pass the intermediate result to the next type inspector in the pipeline.
lastResult: IntermediateTypeInspectionResult <- runNextInspector(
intermediateResult = sanitizedResults,
whereClause = whereClause,
requestingUser = requestingUser
)
} yield lastResult
}
/**
* Get index of entity usage in the where clause of query and all ontology information about all the Knora class and property IRIs mentioned in the query.
*
* @param whereClause the query where clause.
* @param requestingUser the user requesting the query.
* @return a tuple containing the usage index and all entity information acquired from the ontology.
*/
def getUsageIndexAndEntityInfos(
whereClause: WhereClause,
requestingUser: UserADM
): Future[(UsageIndex, EntityInfoGetResponseV2)] =
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
)
} yield (usageIndexWithAdditionalClasses, allEntityInfo)
/**
* 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 {