-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyses.py
1888 lines (1767 loc) · 94.3 KB
/
analyses.py
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
from ctypes import util
from dataclasses import replace
import datetime
from html import entities
from operator import sub
import re
import socket
from string import whitespace
from tabnanny import check
import time
from xml.dom.minidom import Document
from xml.parsers import expat
import json
from rdflib import VOID
import requests
from KnowledgeGraph import KnowledgeGraph
from QualityDimensions.Accuracy import Accuracy
from QualityDimensions.Availability import Availability
from QualityDimensions.Believability import Believability
from QualityDimensions.Completeness import Completeness
from QualityDimensions.Conciseness import Conciseness
from QualityDimensions.Consistency import Consistency
from QualityDimensions.Currency import Currency
from QualityDimensions.Extra import Extra
from QualityDimensions.Interlinking import Interlinking
from QualityDimensions.Interpretability import Interpretability
from QualityDimensions.Licensing import Licensing
from QualityDimensions.Performance import Performance
from QualityDimensions.RepresentationalConciseness import RepresentationalConciseness
from QualityDimensions.RepresentationalConsistency import RepresentationalConsistency
from QualityDimensions.Reputation import Reputation
from QualityDimensions.Security import Security
from QualityDimensions.Understendability import Understendability
from QualityDimensions.Verifiability import Verifiability
from QualityDimensions.Versatility import Versatility
from QualityDimensions.Volatility import Volatility
from Sources import Sources
from bloomfilter import BloomFilter
import utils
from API import Aggregator
from API import LOVAPI
from SPARQLWrapper import *
from SPARQLWrapper import SPARQLExceptions
from urllib.error import HTTPError, URLError
import urllib.request
import query
import numpy
import Graph
import networkx as nx
import VoIDAnalyses
import QualityDimensions.AmountOfData
import ssl
import score
from score import Score
import os
import logging
def analyses(idKG,analysis_date,nameKG):
utils.skipCheckSSL() #IGNORE THE ERROR [SSL: CERTIFICATE_VERIFY_FAILED]
available = False
isHTML = False
absent = False
restricted = False
void = False
internalError = False
queryNotSupported = False
availableDump = '-'
metadata = Aggregator.getDataPackage(idKG)
if nameKG == '':
nameKG = Aggregator.getNameKG(metadata)
accessUrl = Aggregator.getSPARQLEndpoint(idKG)
#Set log format
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(kg_id)s | %(kg_name)s | %(message)s')
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s | %(levelname)s | %(kg_id)s | %(kg_name)s | %(message)s')
#Set format also for the root logger, to follow the same format also for the log on console
root_logger = logging.getLogger()
root_logger.handlers[0].setFormatter(formatter)
#Logger configuration
logger = logging.getLogger('KG analysis')
logger.setLevel(logging.DEBUG)
#Handler to write log on file
here = os.path.dirname(os.path.abspath(__file__))
save_path = os.path.join(here,'./Analysis results')
save_path = os.path.join(save_path, analysis_date+".log")
file_handler = logging.FileHandler(save_path)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
#Handler to write log on console
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_handler.setFormatter(formatter)
logger.handlers = []
logger.addHandler(file_handler)
kg_info = {"kg_id": f"{idKG}", "kg_name" : f"{nameKG}" }
logger.info('Analysis started...',extra=kg_info)
logger.info(f"SPARQL endpoint link: {accessUrl}",extra=kg_info)
endpoint = ''
start_analysis = time.time()
if accessUrl == False: #CHECK IF THE SPARQL END POINT LINK IS IN THE METADATA
endpoint = '-'
logger.warning('SPARQL endpoint missing in the metadata',extra=kg_info)
absent = True
available = False
else:
try:
result = query.checkEndPoint(accessUrl)
if isinstance(result,bytes):
newUrl = utils.checkRedirect(accessUrl) #IF WE GET HTML IN THE RESPONSE, CHECK IF THE ENDPOINT IS NOW AT ANOTHER ADDRESS
result = query.checkEndPoint(newUrl)
if isinstance(result,bytes):
endpoint = '-'
logger.warning('The result from the SPARQL endpoint is not structured data (HTML data returned)',extra=kg_info)
available = False
else:
endpoint = 'Available'
available = True
accessUrl = newUrl
else:
endpoint = 'Available'
available = True
except(HTTPError,URLError,SPARQLExceptions.EndPointNotFound,socket.gaierror) as response: #IF THERE IS ONE OF THESE EXCEPTION, ENDPOINT IS OFFLINE
endpoint = '-'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
except SPARQLExceptions.EndPointInternalError as response: #QUERY NOT SUPPORTED
endpoint = '-'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
except(json.JSONDecodeError, SPARQLExceptions.QueryBadFormed,expat.ExpatError) as response: # NO AUTOMATICALLY (?), Error decoding the response
endpoint = '-'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
except(SPARQLExceptions.Unauthorized) as response: #RESTRICTED ACCCESS TO THE ENDPOINT
endpoint = 'Restricted access to the endpoint'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
restricted = True
except Exception as error:
logger.warning('Availability | SPARQL endpoint availability | ' + str(error),extra=kg_info)
endpoint = 'offline'
available = False
if available == False and absent == False:
try:
newUrl = utils.checkRedirect(accessUrl) #TEST OF ACCESS TO THE ENDPOINT IN CASE OF REDIRECT ON ADDRESS
if newUrl != accessUrl:
result = query.checkEndPoint(newUrl)
if isinstance(result,Document) or isinstance(result,dict):
accessUrl = newUrl
available = True
endpoint = 'Available'
except(HTTPError,URLError,SPARQLExceptions.EndPointNotFound,socket.gaierror) as response:
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
except SPARQLExceptions.EndPointInternalError as response:
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
endpoint = '-'
except(json.JSONDecodeError, SPARQLExceptions.QueryBadFormed,expat.ExpatError) as response:
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
endpoint = '-'
available = False
except(SPARQLExceptions.Unauthorized) as response:
endpoint = 'restricted access to the endpoint'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
restricted = True
except Exception as error:
logger.warning('Availability | SPARQL endpoint availability | ' + str(error),extra=kg_info)
endpoint = 'offline'
available = False
#GET THE SOURCE OF THE DATASET
sources = Aggregator.getSource(metadata)
if sources == False:
sourcesC = Sources('absent','absent','absent')
else:
sourcesC = Sources(sources.get('web','Absent'),sources.get('name','Absent'),sources.get('email','Absent'))
if available == False and absent == False and sourcesC.web != 'absent': #TRY TO ACCESS AT THE SPARQL ENDPOINT ADDING \sparql AT THE END OF THE DATASET URL
try:
newUrl = sourcesC.web + '/sparql'
result = query.checkEndPoint(newUrl)
if isinstance(result,Document) or isinstance(result,dict):
accessUrl = newUrl
available = True
endpoint = 'Available'
logger.info(f"SPARQL endpoint link: {accessUrl}",extra=kg_info)
except(HTTPError,URLError,SPARQLExceptions.EndPointNotFound,socket.gaierror) as response: #IF THERE IS ONE OF THESE EXCEPTION, ENDPOINT IS OFFLINE
endpoint = '-'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
except SPARQLExceptions.EndPointInternalError as response: #QUERY NOT SUPPORTED
endpoint = '-'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
except(json.JSONDecodeError, SPARQLExceptions.QueryBadFormed,expat.ExpatError) as response: # NO AUTOMATICALLY (?), Error decoding the response
endpoint = '-'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
except(SPARQLExceptions.Unauthorized) as response: #RESTRICTED ACCCESS TO THE ENDPOINT
endpoint = 'Restricted access to the endpoint'
logger.warning('Availability | SPARQL endpoint availability | ' + str(response),extra=kg_info)
available = False
restricted = True
except Exception as error:
logger.warning('Availability | SPARQL endpoint availability | ' + str(error),extra=kg_info)
endpoint = 'offline'
available = False
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'SPARQL endpoint availability check','Availability',analysis_date)
#GET NUMBERS OF TRIPLES FROM METADATA
triplesM = Aggregator.getTriples(metadata)
try:
triplesM = int(triplesM)
except ValueError:
triplesM = 0
#GET OTHER RESOURCES OF THE DATASET
resourcesDH = Aggregator.getOtherResources(idKG)
#CHECK THE AVAILABILITY OF THE URL IN THE RESOURCES LIST AND ADDING A FIELD STATUS. STATUS = ACTIVE IF THE URL IS ONLINE, STATUS = OFFLINE IF THE URL IS OFFLINE
resourcesDH = utils.insertAvailability(resourcesDH)
#CHECK AVAILABILITY FOR DOWNLOAD OF THE DATASET
downloadUrl = []
offlineDump = []
availableDownload = utils.checkAvailabilityForDownload(resourcesDH)
downloadUrl = downloadUrl + utils.getLinkDownload(resourcesDH)
offlineDump = offlineDump + utils.getLinkOfflineDump(resourcesDH)
otResources = utils.toObjectResources(resourcesDH) #CREATING A LIST OF RESOURCES OBJECT
metadata_media_type = utils.extract_media_type(resourcesDH)
#CHECK THE AVAILABILITY OF VOID FILE
start_analysis = time.time()
urlV = utils.getUrlVoID(otResources)
voidStatus = ''
if isinstance(urlV,str):
try:
voidFile = VoIDAnalyses.parseVoID(urlV)
void = True
voidStatus = 'VoID file available'
except:
try:
voidFile = VoIDAnalyses.parseVoIDTtl(urlV)
void = True
voidStatus = 'VoID file available'
except:
void = False
voidStatus = 'VoID file offline'
if void == False and not isinstance(urlV,str) and sourcesC.web != 'absent' and sourcesC.web != 'Absent':
urlV = sourcesC.web + '/.well-known/void'
try:
voidFile = VoIDAnalyses.parseVoID(urlV)
void = True
voidStatus = 'VoID file available'
logger.info(f"VoID file link: {urlV}",extra=kg_info)
except:
try:
voidFile = VoIDAnalyses.parseVoIDTtl(urlV)
void = True
voidStatus = 'VoID file available'
except urllib.error.HTTPError as e:
if e.code == 404:
voidStatus = 'VoID file absent'
else:
void = False
voidStatus = 'VoID file offline'
except urllib.error.URLError as e:
voidStatus = 'VoID file absent'
except Exception as e:
void = False
voidStatus = 'VoID file offline'
if not isinstance(urlV,str):
voidStatus = 'VoID file absent'
logger.info(f"VoID file link: {urlV}",extra=kg_info)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'VoID file availability check', 'Availability',analysis_date)
logger.info(f"SPARQL endpoint availability: {available}",extra=kg_info)
if available == True: #IF ENDOPOINT IS ONLINE WE GET ALL NECESSARY INFORMATION FROM THE ENDPOINT
start_analysis = time.time()
#TRY TO GET ALL TRIPLES (IMPORTANT FOR CALCULATING VARIOUS METRICS)
allTriples = []
try:
allTriples = query.getAllTriplesSPO(accessUrl)
except:
logger.warning('Impossible to recover all the triples in the KG',extra=kg_info)
allTriples = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Recovery of all triples', 'Extra',analysis_date)
#GET LATENCY (MIN-MAX-AVERAGE)
try:
start_analysis = time.time()
latency = query.testLatency(accessUrl)
sumLatency = sum(latency)
av = sumLatency/len(latency)
minL = min(latency)
maxL = max(latency)
standardDeviation = numpy.std(latency)
sumLatency = str(sumLatency)
percentile25L = numpy.percentile(latency,25)
percentile75L = numpy.percentile(latency,75)
medianL = numpy.median(latency)
av = "%.3f"%av
av = str(av)
minL = "%.3f"%minL
minL = str(minL)
maxL = "%.3f"%maxL
maxL = str(maxL)
standardDeviation = "%.3f"%standardDeviation
standardDeviation = str(standardDeviation)
sumLatency = sumLatency.replace('.',',')
av = av.replace('.',',')
minL = minL.replace('.',',')
maxL = maxL.replace('.',',')
standardDeviation = standardDeviation.replace('.',',')
percentile25L = "%.3f"%percentile25L
medianL = "%.3f"%medianL
percentile75L = "%.3f"%percentile75L
percentile25L = str(percentile25L)
percentile75L = str(percentile75L)
medianL = str(medianL)
percentile25L = percentile25L.replace('.',',')
percentile75L = percentile75L.replace('.',',')
medianL = medianL.replace('.',',')
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Total latancy measurement', 'Performance',analysis_date)
except urllib.error.HTTPError as response:
logger.warning(f'Performance | Latency | {str(response)}',extra=kg_info)
responseStr = '-'
av = responseStr
minL = responseStr
maxL = responseStr
standardDeviation = responseStr
percentile25L = responseStr
percentile75L = responseStr
medianL = responseStr
except SPARQLExceptions.QueryBadFormed:
logger.warning('Performance | Latency | Query bad formed',extra=kg_info)
responseStr = '-'
av = responseStr
minL = responseStr
maxL = responseStr
standardDeviation = responseStr
percentile25L = responseStr
percentile75L = responseStr
medianL = responseStr
except SPARQLExceptions.EndPointInternalError:
logger.warning('Performance | Latency | SPARQL endpoint internal error',extra=kg_info)
responseStr = '-'
av = responseStr
minL = responseStr
maxL = responseStr
standardDeviation = responseStr
percentile25L = responseStr
percentile75L = responseStr
medianL = responseStr
except Exception as error:
logger.error('Performance | Latency | ' + str(error),extra=kg_info)
responseStr = '-'
av = responseStr
minL = responseStr
maxL = responseStr
standardDeviation = responseStr
percentile25L = responseStr
percentile75L = responseStr
medianL = responseStr
#GET THE TRIPLES WITH A QUERY
start_analysis = time.time()
try:
triplesQuery = query.getNumTripleQuery(accessUrl)
except urllib.error.HTTPError as response:
logger.warning(f'Error while counting the number of triples: {str(response)}',extra=kg_info)
triplesQuery = '-'
except(SPARQLExceptions.QueryBadFormed,SPARQLExceptions.EndPointInternalError) as response:
logger.warning(f'Error while counting the number of triples: {str(response)}',extra=kg_info)
triplesQuery = '-'
except Exception as error:
logger.warning(f'Error while counting the number of triples: {str(error)}',extra=kg_info)
triplesQuery = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Number of triples check', 'Amount of data',analysis_date)
#CHECK IF RESULTS FROM SPARQL ENDPOINT IS LIMITED
if isinstance(allTriples,list) and isinstance(triplesQuery,int):
if len(allTriples) < triplesQuery:
limited = True
logger.warning(f'The number of triples that can be retrieved from the sparql endpoint is limited',extra=kg_info)
else:
limited = False
else:
limited = 'impossible to verify'
#CHECK IF NEW TERMS ARE DECLARED IN THE DATASET
newTermsD = []
triplesO = []
try:
start_analysis = time.time()
objectList = []
triplesO = query.getAllTypeO(accessUrl)
newTermsD = LOVAPI.searchTermsList(triplesO)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'New terms check', 'Interoperability',analysis_date)
except Exception as error:
logger.warning(f'Representational-consistency | Reuse of terms | {str(error)}',extra=kg_info)
newTermsD = '-'
#GET THE LANGUAGE OF KG
start_analysis = time.time()
try:
languages = query.getLangugeSupported(accessUrl)
except urllib.error.HTTPError as response:
languages = response
except (SPARQLExceptions.QueryBadFormed,SPARQLExceptions.EndPointNotFound) as response:
logger.warning(f'Versatility | Languages | Query not supported or endpoint not found',extra=kg_info)
languages = '-'
except Exception as error:
logger.warning(f'Versatility | Languages | {str(error)}',extra=kg_info)
languages = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Languages check','Versatility',analysis_date)
#GET THE NUMBER OF THE BLANK NODE
start_analysis = time.time()
try:
numBlankNode = query.numBlankNode(accessUrl)
except urllib.error.HTTPError as response:
logger.warning(f'Interpretability | Number of blank nodes | HTTP error',extra=kg_info)
numBlankNode = '-'
except (SPARQLExceptions.QueryBadFormed,SPARQLExceptions.EndPointInternalError) as response:
logger.warning(f'Interpretability | Number of blank nodes | {str(response)}',extra=kg_info)
numBlankNode = '-'
except Exception as error:
logger.warning(f'Interpretability | Number of blank nodes | {str(error)}',extra=kg_info)
numBlankNode = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Number of blank nodes check', 'Interpretability',analysis_date)
#CHECK IF SPARQL ENDPOINT USE HTTPS
try:
start_analysis = time.time()
sec_access_url = accessUrl.replace('http','https')
isSecure = query.checkEndPoint(sec_access_url)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Check HTTPS', 'Security',analysis_date)
if isinstance(isSecure,Document) or isinstance(isSecure,dict):
isSecure = True
except: #IF WE GET A SPARQL QUERY ON URL WITH HTTPS AND GET AN EXCEPTION THEN ENDPOINT ISN'T AVAILABLE ON HTTPS
isSecure = False
#CHECK IF IT USES RDF STRUCTURES
start_analysis = time.time()
try:
RDFStructures = query.checkRDFDataStructures(accessUrl)
except Exception as error:
logger.warning(f'Representational-conciseness | Use of RDF structures | {str(error)}',extra=kg_info)
RDFStructures = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'RDF structures check','Interpretability',analysis_date)
#CHECK IF THERE ARE DIFFERENT SERIALISATION FORMATS
start_analysis = time.time()
try:
formats = query.checkSerialisationFormat(accessUrl) #CHECK IF THE LINK IS ONLINE
except Exception as error:
logger.warning(f'Versatility | Serialization formats | {str(error)}',extra=kg_info)
formats = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Serialization formats check', 'Versatility',analysis_date)
#CHECK FOR DOWNLOAD LINKS FOR THE DATASET WITH DCAT PREDICATE
dcat_links = []
try:
other_download_links = query.get_download_link(accessUrl)
for link in other_download_links:
status = utils.checkAvailabilityResource(link)
if status == True:
dcat_links.append(link)
except Exception as error:
logger.warning('Versatility | Languages | Download links, error during query with the dcat:downloadURL predicate',extra=kg_info)
#CHECK IF IN THE DATASET IS INDICATED THE LINK TO DONWLOAD THE DATASET
start_analysis = time.time()
try:
urlList = query.checkDataDump(accessUrl)
if isinstance(urlList,list):
availableDump = utils.checkAvailabilityListResources(urlList)
urlsDump = utils.getActiveDumps(urlList)
urlsInactive = utils.getInactiveDumps(urlList)
downloadUrl = downloadUrl + urlsDump
offlineDump = offlineDump + urlsInactive
else:
availableDump = 'absent'
except Exception as error:
logger.warning(f'Availability | RDF dump| {str(error)}',extra=kg_info)
availableDump = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'RDF dump link check','Availability',analysis_date)
#CHEK IF THERE IS AN INDICATION OF A LICENSE MACHINE REDEABLE
start_analysis = time.time()
try:
licenseMr = query.checkLicenseMR2(accessUrl)
if isinstance(licenseMr,list):
licenseMr = licenseMr[0]
except Exception as error:
licenseMr = '-'
logger.warning(f'Licensing | Machine-redeable license | {str(error)}',extra=kg_info)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'MR license check','License',analysis_date)
#CHECK IF THERE IS AN INDICATION OF A LICENSE HUMAN REDEABLE
start_analysis = time.time()
try:
licenseHr = query.checkLicenseHR(accessUrl)
except (SPARQLExceptions.QueryBadFormed,SPARQLExceptions.EndPointInternalError) as response:
licenseHr = '-'
logger.warning(f'Licensing | Human-redeable license | {str(response)}',extra=kg_info)
except Exception as error:
licenseHr = '-'
logger.warning(f'Licensing | Human-redeable license | {str(error)}',extra=kg_info)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'HR license check', 'License',analysis_date)
#CHECK NUMBER OF PROPERTY
start_analysis = time.time()
try:
numProperty = query.numberOfProperty(accessUrl)
except Exception as error:
numProperty = '-'
logger.warning(f'Amount of data | Number of properties | {str(error)}',extra=kg_info)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Number of property check','Amount of data',analysis_date)
#GET NUMBER OF TRIPLES WITH LABEL
start_analysis = time.time()
try:
numLabel = query.getNumLabel(accessUrl)
except Exception as error:
numLabel = '-'
logger.warning(f'Amount of data | Number of labels | {str(error)}',extra=kg_info)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Number of label check','Understandability',analysis_date)
#GET THE REGEX OF THE URLs USED
start_analysis = time.time()
regex = []
try:
regex = query.checkUriRegex(accessUrl)
except Exception as error:
logger.warning(f'Understandability | URIs regex | {str(error)}',extra=kg_info)
regex = '-'
#CHECK IF IS INDICATED A URI SPACE INSTEAD OF A REGEX AND WE TRAFORM IT TO REGEX
try:
pattern = query.checkUriPattern(accessUrl)
if isinstance(pattern,list):
for i in range(len(pattern)):
newRegex = utils.trasforrmToRegex(pattern[i])
regex.append(newRegex)
except Exception as error:
logger.warning(f'Understandability | URIs regex | {str(error)}',extra=kg_info)
pattern = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'URI regex check', 'Understandability',analysis_date)
#GET THE VOCABULARIES OF THE KG
start_analysis = time.time()
try:
vocabularies = query.getVocabularies(accessUrl)
except Exception as error:
logger.warning(f'Understandability | Vocabularies | {str(error)}',extra=kg_info)
vocabularies = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Vocabs check', 'Understandability',analysis_date)
#GET THE AUTHOR OF THE DATASET WITH A QUERY
start_analysis = time.time()
try:
authorQ = query.getCreator(accessUrl)
except Exception as error:
logger.warning(f'Verifiability | Verifiying publisher information | {str(error)}',extra=kg_info)
authorQ = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Authors check', 'Verifiability',analysis_date)
#GET THE PUBLISHERS OF THE DATASET
start_analysis = time.time()
try:
publisher = query.getPublisher(accessUrl)
except Exception as error:
publisher = '-'
logger.warning(f'Verifiability | Verifiying publisher information | {str(error)}',extra=kg_info)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Publishers check', 'Verifiability',analysis_date)
#GET THE THROUGHPUT
try:
start_analysis = time.time()
countList = utils.getThroughput(accessUrl)
minThroughput = min(countList)
maxThroughput = max(countList)
sumThroughput = sum(countList)
averageThroughput = sumThroughput/len(countList)
standardDeviationT = numpy.std(countList)
percentile25T = numpy.percentile(countList,25)
percentile75T = numpy.percentile(countList,75)
medianT = numpy.median(countList)
percentile25T = str(percentile25T)
percentile25T = percentile25T.replace('.',',')
percentile75T = str(percentile75T)
percentile75T = percentile75T.replace('.',',')
medianT = str(medianT)
medianT = medianT.replace('.',',')
standardDeviationT = str(standardDeviationT)
standardDeviationT = standardDeviationT.replace('.',',')
averageThroughput = str(averageThroughput)
averageThroughput = averageThroughput.replace('.',',')
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Throughput check', 'Performance',analysis_date)
except Exception as error:
logger.warning(f'Performance | High Throughput | {str(error)}',extra=kg_info)
errorResponse = '-'
minThroughput = errorResponse
maxThroughput = errorResponse
averageThroughput = errorResponse
standardDeviationT = errorResponse
percentile25T = errorResponse
percentile75T = errorResponse
medianT = errorResponse
#GET THE THROUGHPUT NO OFFSET
try:
countListNoOff = utils.getThroughputNoOff(accessUrl)
minThroughputNoOff = min(countListNoOff)
maxThroughputNoOff = max(countListNoOff)
sumThroughputNoOff = sum(countListNoOff)
averageThroughputNoOff = sumThroughput/len(countListNoOff)
standardDeviationTNoOff = numpy.std(countListNoOff)
standardDeviationTNoOff = str(standardDeviationT)
standardDeviationTNoOff = standardDeviationT.replace('.',',')
averageThroughputNoOff = str(averageThroughput)
averageThroughputNoOff = averageThroughput.replace('.',',')
except Exception as error:
logger.warning(f'Performance | High Throughput | {str(error)}',extra=kg_info)
errorResponseNoOff = '-'
minThroughputNoOff = errorResponseNoOff
maxThroughputNoOff = errorResponseNoOff
averageThroughputNoOff = errorResponseNoOff
standardDeviationTNoOff = errorResponseNoOff
#GET NUMBER OF ENTITIES
start_analysis = time.time()
try:
numEntities = query.getNumEntities(accessUrl)
except Exception as error:
logger.warning(f'Amount of data | Scope | {str(error)}',extra=kg_info)
numEntities = '-'
#GET NUMBER OF ENTITIES WITH REGEX
try:
if len(regex) > 0:
entitiesRe = 0
for i in range(len(regex)):
entitiesRe = entitiesRe + query.getNumEntitiesRegex(accessUrl,regex[i])
else:
entitiesRe = '-'
logger.warning(f'Amount of data | Scope | Insufficient data',extra=kg_info)
except Exception as error:
logger.warning(f'Amount of data | Scope | {str(error)}',extra=kg_info)
etitiesRe = '-'
if not(isinstance(entitiesRe,int)) or entitiesRe == 0: #IF CONTROL WITH SPARQL ENDPOINT FAILS WE COUNT THE ENTITY BY RECOVERING ALL THE TRIPLES
try:
start_analysis = time.time()
if isinstance(allTriples,list) and isinstance(regex,list):
if len(regex) > 0:
entitiesRe = 0
for i in range(len(regex)):
r = regex[i]
for j in range(len(allTriples)):
s = allTriples[j].get('s')
valueS = s.get('value')
if utils.checkString(r,valueS) == True:
entitiesRe = entitiesRe + 1
entitiesRe = str(entitiesRe)
entitiesRe = entitiesRe + f" (out of {len(allTriples )} triples considered)"
else:
logger.warning(f'Amount of data | Scope | Insufficient data',extra=kg_info)
entitiesRe = '-'
else:
entitiesRe = '-'
logger.warning(f'Amount of data | Scope | Insufficient data',extra=kg_info)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Check the number of entities', 'Amount of data',analysis_date)
except Exception as error:
logger.warning(f'Amount of data | Scope | {str(error)}',extra=kg_info)
entitiesRe = '-'
#GET THE CONTRIBUTORS OF THE DATASET
start_analysis = time.time()
try:
contributors = query.getContributors(accessUrl)
except Exception as error:
logger.warning(f'Verifiability | Verifiying publisher information | {str(error)}',extra=kg_info)
contributors = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Contribs. check', 'Verifiability',analysis_date)
#GET THE NUMBER OF sameAs CHAINS
start_analysis = time.time()
try:
numberSameAs = query.getSameAsChains(accessUrl)
except Exception as error:
logger.warning(f'Interlinking | sameAs chains | {str(error)}',extra=kg_info)
numberSameAs = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'sameAs chians check', 'Interlinking',analysis_date)
#GET THE NUMBER OF SKOS-Mapping properties
start_analysis = time.time()
try:
numberSkosMapping = query.getSkosMapping(accessUrl)
except Exception as error:
logger.warning(f'Interlinking | SKOS Mapping properties | {str(error)}',extra=kg_info)
numberSkosMapping = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'skos check', 'Interlinking',analysis_date)
#GET THE NUMBER OF SKOS-Mapping properties
start_analysis = time.time()
try:
numberSkosMapping = query.getSkosMapping(accessUrl)
except Exception as error:
logger.warning(f'Interlinking | SKOS Mapping properties | {str(error)}',extra=kg_info)
numberSkosMapping = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'skos check', 'Interlinking',analysis_date)
#GET THE DATASET UPDATE FREQUENCY
start_analysis = time.time()
try:
frequency = query.getFrequency(accessUrl)
except Exception as error:
logger.warning(f'Volatility | Timeliness frequency | {str(error)}',extra=kg_info)
frequency = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'dataset update frequency check', 'Timeliness',analysis_date)
#GET THE CREATION DATE
start_analysis = time.time()
try:
creationDate = query.getCreationDateMin(accessUrl)
if creationDate == False or creationDate == '':
creationDate = query.getCreationDate(accessUrl)
except:
try:
creationDate = query.getCreationDate(accessUrl)
except Exception as error:
logger.warning(f'Currency | Age of data | {str(error)}',extra=kg_info)
creationDate = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Creation date check', 'Currency',analysis_date)
#GET THE LAST MODIFICATION DATE OF THE DATASET
start_analysis = time.time()
try:
modificationDate = query.getModificationDateMax(accessUrl)
if modificationDate == False or modificationDate == '':
modificationDate = query.getModificationDate(accessUrl)
except:
try:
modificationDate = query.getModificationDate(accessUrl)
except Exception as error:
logger.warning(f'Currency | Specification of the modification date of statements | {error}',extra=kg_info)
modificationDate = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Modification date check', 'Currency',analysis_date)
#GET HISTORICAL UPDATES
historicalUp = []
try:
historicalUp = []
dateUpdates = query.getDateUpdates(accessUrl)
if isinstance(dateUpdates,list):
newL = list(set(dateUpdates))
newL.sort(key=lambda date: datetime.datetime.strptime(date,"%Y-%m-%d"))
for i in newL:
i = str(i)
num = query.getNumUpdatedData(accessUrl,i)
valueUp = f"{i}|{num}"
valueUp = valueUp.strip()
historicalUp.append(valueUp)
except Exception as error:
logger.warning(f'Currency | Update history | {str(error)}',extra=kg_info)
historicalUp = '-'
#GET THE NUMBER OF TRIPLES UPDATED
try:
numTriplesUpdated = query.getNumUpdatedData(accessUrl,modificationDate)
except Exception as error:
logger.warning(f'Currency | Number of triples updated | {str(error)}',extra=kg_info)
numTriplesUpdated = '-'
#URI LENGHT CALCULATION (SUBJECT)
start_analysis = time.time()
try:
lenghtList = []
logger.info(f'Calculating the URIs length...',extra=kg_info)
for i in range(len(allTriples)):
s = allTriples[i].get('s')
uri = s.get('value')
if utils.validateURI(uri) == True:
lenghtList.append(len(uri))
sumLenghts = sum(lenghtList)
avLenghts = sumLenghts/len(lenghtList)
avLenghts = str(avLenghts)
avLenghts = avLenghts.replace('.',',')
avLenghts = avLenghts + f" (out of {len(allTriples)} triples considered)"
standardDeviationL = numpy.std(lenghtList)
standardDeviationL = str(standardDeviationL)
standardDeviationL = standardDeviationL.replace('.',',')
minLenghtS = min(lenghtList)
maxLenghtS = max(lenghtList)
medianLenghtS = numpy.median(lenghtList)
percentile25LenghtS = numpy.percentile(lenghtList,25)
percentile75LenghtS = numpy.percentile(lenghtList,75)
minLenghtS = str(minLenghtS)
maxLenghtS = str(maxLenghtS)
medianLenghtS = str(medianLenghtS)
percentile25LenghtS = str(percentile25LenghtS)
percentile75LenghtS = str(percentile75LenghtS)
minLenghtS = minLenghtS.replace('.',',')
maxLenghtS = maxLenghtS.replace('.',',')
medianLenghtS = medianLenghtS.replace('.',',')
percentile25LenghtS = percentile25LenghtS.replace('.',',')
percentile75LenghtS = percentile75LenghtS.replace('.',',')
except Exception as error:
logger.warning(f'Representational-conciseness | Keeping URI short | {str(error)}',extra=kg_info)
errorMessage = '-'
standardDeviationL = errorMessage
avLenghts = errorMessage
minLenghtS = errorMessage
maxLenghtS = errorMessage
medianLenghtS = errorMessage
percentile25LenghtS = errorMessage
percentile75LenghtS = errorMessage
#URI LENGHT CALCULATION (OBJECT)
allUri = []
try:
uriListO = query.getAllObject(accessUrl)
lenghtListO = []
for i in range(len(uriListO)):
uriO = uriListO[i]
if utils.validateURI(uriO) == True:
lenghtListO.append(len(uriO))
sumLenghtsO = sum(lenghtListO)
avLenghtsO = sumLenghtsO/len(lenghtListO)
avLenghtsO = str(avLenghtsO)
avLenghtsO = avLenghtsO.replace('.',',')
avLenghtsO = avLenghtsO+f" (out of {len(uriListO)} triples considered)"
standardDeviationLO = numpy.std(lenghtListO)
standardDeviationLO = str(standardDeviationLO)
standardDeviationLO = standardDeviationLO.replace('.',',')
minLenghtO = min(lenghtListO)
maxLenghtO = max(lenghtListO)
medianLenghtO = numpy.median(lenghtListO)
percentile25LenghtO = numpy.percentile(lenghtListO,25)
percentile75LenghtO = numpy.percentile(lenghtListO,75)
minLenghtO = str(minLenghtO)
maxLenghtO = str(maxLenghtO)
medianLenghtO = str(medianLenghtO)
percentile25LenghtO = str(percentile25LenghtO)
percentile75LenghtO = str(percentile75LenghtO)
minLenghtO = minLenghtO.replace('.',',')
maxLenghtO = maxLenghtO.replace('.',',')
medianLenghtO = medianLenghtO.replace('.',',')
percentile25LenghtO = percentile25LenghtO.replace('.',',')
percentile75LenghtO = percentile75LenghtO.replace('.',',')
except Exception as error:
logger.warning(f'Representational-conciseness | Keeping URI short | {str(error)}',extra=kg_info)
errorMessage = '-'
uriListO = errorMessage
avLenghtsO = errorMessage
standardDeviationLO = errorMessage
minLenghtO = errorMessage
maxLenghtO = errorMessage
medianLenghtO = errorMessage
percentile25LenghtO = errorMessage
percentile75LenghtO = errorMessage
#URI LENGHT CALCULATION (PREDICATE)
try:
uriListP = query.getAllPredicate2(accessUrl)
lenghtListP = []
for i in range(len(uriListP)):
uriP = uriListP[i]
if utils.validateURI(uriP) == True:
lenghtListP.append(len(uriP))
sumLenghtsP = sum(lenghtListP)
avLenghtsP = sumLenghtsP/len(lenghtListP)
avLenghtsP = str(avLenghtsP)
avLenghtsP = avLenghtsP.replace('.',',')
avLenghtsP = avLenghtsP+f" (out of {len(uriListP)} triples considered)"
standardDeviationLP = numpy.std(lenghtListP)
standardDeviationLP = str(standardDeviationLP)
standardDeviationLP = standardDeviationLP.replace('.',',')
minLenghtP = min(lenghtListP)
maxLenghtP = max(lenghtListP)
medianLenghtP = numpy.median(lenghtListP)
percentile25LenghtP = numpy.percentile(lenghtListP,25)
percentile75LenghtP = numpy.percentile(lenghtListP,75)
minLenghtP = str(minLenghtP)
maxLenghtP = str(maxLenghtP)
medianLenghtP = str(medianLenghtP)
percentile25LenghtP = str(percentile25LenghtP)
percentile75LenghtP = str(percentile75LenghtP)
minLenghtP = minLenghtP.replace('.',',')
maxLenghtP = maxLenghtP.replace('.',',')
medianLenghtP = medianLenghtP.replace('.',',')
percentile25LenghtP = percentile25LenghtP.replace('.',',')
percentile75LenghtP = percentile75LenghtP.replace('.',',')
except Exception as error:
logger.warning(f'Representational-conciseness | Keeping URI short | {str(error)}',extra=kg_info)
errorMessage = '-'
uriListP = errorMessage
avLenghtsP = errorMessage
standardDeviationLP = errorMessage
minLenghtP = errorMessage
maxLenghtP = errorMessage
medianLenghtP = errorMessage
percentile25LenghtP = errorMessage
percentile75LenghtP = errorMessage
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'URIs length', 'Rep.Conc.',analysis_date)
#A LIST OF ALL URIs IS REQUIRED TO CALCULATE THE SCORE
if isinstance(allTriples,list) and isinstance(uriListP,list) and isinstance(uriListO,list):
uriListS = []
for i in range(len(allTriples)):
s = allTriples[i].get('s')
uri = s.get('value')
uriListS.append(uri)
allUri = uriListO + uriListP + uriListS
#CHECK IF EXISTING VOCABULARIES ARE RE-USED IN THE DATASET
try:
start_analysis = time.time()
newVocab = []
if isinstance(vocabularies,list):
for i in range(len(vocabularies)):
vocab = vocabularies[i]
result = LOVAPI.findVocabulary(vocab)
if result == False:
newVocab.append(vocab)
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'New vocabularies check','Interoperability',analysis_date)
except Exception as error:
logger.warning(f'Representational-consistency | re-use of existing terms | {str(error)}',extra=kg_info)
newVocab = '-'
#CHECK USE OF DEPRECATED CLASSES AND PROPERTIES
start_analysis = time.time()
try:
deprecated = query.getDeprecated(accessUrl)
except Exception as error:
logger.warning(f'Consistency| Use of members of deprecated classes or properties| {str(error)}',extra=kg_info)
deprecated = '-'
end_analysis = time.time()
utils.write_time(nameKG,end_analysis-start_analysis,'Deprecated classes/propertiers check', 'Consistency',analysis_date)
#CHECK FOR FUNCTIONAL PROPERTIES WITH INCONSISTENT VALUE
try:
start_analysis = time.time()
violationFP = []
triplesFP = query.getFP(accessUrl)
for triple in triplesFP:
s = triple.get('s')
subject1 = s.get('value')