-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathctrlstrct_run.py
2098 lines (1697 loc) · 90.4 KB
/
ctrlstrct_run.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
# ctrlstrct_run.py
""" Импорт алгоритмов и трасс из текста (из файлов в handcrafted_traces/*),
наполнение ими чистой онтологии,
добавление SWRL-правил, определённых в ctrlstrct_swrl.py (используя import), сохранение исходной онтологии в файл,
запуск ризонинга (опционально).
"""
import io
# from pprint import pprint
# from owlready2 import *
from onto_helpers import *
from transliterate import slugify
from trace_gen.txt2algntr import get_ith_expr_value, find_by_key_in, find_by_keyval_in
from explanations import format_explanation, get_leaf_classes
from external_run import timer, run_swiprolog_reasoning, run_jena_reasoning, invoke_jena_reasoning_service, JENA_RULE_PATHS, JENA_RULE_PATHS_SOLVE_ALG, measure_stats_for_pellet_running, measure_stats_for_clingo_running, measure_stats_for_dlv_running, get_process_run_stats
from common_helpers import Uniqualizer, delete_file
onto_path.append(".")
# ONTOLOGY_maxID = 1
ONTOLOGY_IRI = 'http://vstu.ru/poas/code'
# options to not to save the parts of ontology while doing reasoning
WRITE_INVOLVES_CONCEPT = False
WRITE_PRINCIPAL_VIOLATION = False
WRITE_SKOS_CONCEPT = False
WRITE_CONCEPT_FLAG_LABEL = False
def prepare_name(s):
"""Transliterate given word is needed"""
try:
return slugify(s, "ru") or s
except:
print(' slugify() threw error for action name: ', name)
return s
# наладим связи между элементами алгоритма
def link_objects(onto, iri_subj : str, prop_name : str, iri_obj : str, prop_superclasses=(Thing >> Thing, )):
"""Make a relation between two individuals that must exist in the ontology. The property, however, is created if does not exist (the `prop_superclasses` are applied to the new property)."""
prop = onto[prop_name]
if not prop:
with onto:
# новое свойство по заданному имени
print('!! найдено свойство вне онтологии:', prop_name)
prop = types.new_class(prop_name, prop_superclasses)
# связываем объекты свойством
make_triple(onto[iri_subj], prop, onto[iri_obj])
def uniqualize_iri(onto, iri):
"""uniqualize individual's name"""
n = 2; orig_iri = iri
while onto[iri]: # пока есть объект с таким именем
# модифицировать имя
iri = orig_iri + ("_%d" % n); n += 1
# print(iri)
return iri
def uniqualize_id(onto, id_:int):
"""uniqualize individual's id"""
prop = onto.id
existing = [o for s, o in prop.get_relations()]
while id_ in existing: # пока есть объект с таким ID
# модифицировать ID
id_ += 100
return id_
class TraceTester():
def __init__(self, trace_data):
"""trace_data: dict like
{
"trace_name" : str,
"algorithm_name": str,
"trace" : list,
"algorithm" : dict,
"header_boolean_chain" : list of bool - chain of conditions results
}
"""
self.data = trace_data
# pprint(trace_data)
# pprint(trace_data["trace"])
# pprint(trace_data["algorithm"])
# exit()
# индекс всех объектов АЛГОРИТМА для быстрого поиска по id
self.id2obj = self.data["algorithm"].get("id2obj", {})
self.initial_repair_data()
self.act_iris = []
self._maxID = 1
def initial_repair_data(self):
'''patch data if it is not connected properly but is replicated instead (ex. after JSON serialization)'''
# repair dicts' "id" values that are str, not int
k = 'id'
for d in find_by_key_in(k, self.data):
if isinstance(d[k], str):
d[k] = int(d[k])
# repair dicts keys that are str, not int
for k in list(self.id2obj.keys()):
if isinstance(k, str):
self.id2obj[int(k)] = self.id2obj[k]
del self.id2obj[k]
data = self.data["algorithm"] # data to repair
if "functions" not in data:
data["functions"] = ()
roots = data["global_code"], data["functions"] # where actual data to be stored
# referers = data["entry_point"], data["id2obj"] # these should only refer to some nodes within roots.
k = 'id'
for d in find_by_keyval_in(k, data["entry_point"][k], roots):
data["entry_point"] = d # reassign the approriate node from roots (global_code or main function)
break
for ID in list(self.id2obj.keys()):
for d in find_by_keyval_in(k, ID, roots):
self.id2obj[ID] = d # reassign the approriate node from roots
break
def newID(self, what=None):
while True:
self._maxID += 1
if self._maxID not in self.id2obj:
break
return self._maxID
def alg_entry(self):
if "entry_point" in self.data["algorithm"]:
alg_node = self.data["algorithm"]["entry_point"]
else:
raise "Cannot resolve 'entry_point' from algorithm's keys: " + str(list(self.data["algorithm"].keys()))
return alg_node
def make_correct_trace(self, noop=False):
self.data["correct_trace"] = []
self.expr_id2values = {}
if noop:
# !!!
return
def _gen(states_str):
for ch in states_str:
yield bool(int(ch))
while 1:
yield None
self.indent_depth = 0 # should increase on entering a function
self.last_cond_tuple = (-1, False)
self.consequent_mode = "normal" # other values: "return", "break", "continue"
self._maxID = max(self._maxID, max(map(int, self.id2obj.keys())) + 10)
# decide where to read expr values from
self.values_source = None
if self.data["header_boolean_chain"]:
# source №1: the boolean chain attached to the trace
self.values_source = "boolean_chain"
self.condition_value_generator = _gen(self.data["header_boolean_chain"])
elif self.data["algorithm"]["expr_values"]:
# source №2: the values defined beside algorithm lines
# (this is used for 1-1 case when no boolean chain specified)
self.values_source = "algorithm"
else:
# source №3: the values defined beside trace lines
# (this is less preferred as the trace may contain errors)
self.values_source = "trace"
# print(f'Trace {self.data["trace_name"]}: values_source detected:', self.values_source)
def next_cond_value(expr_name=None, executes_id=None, n=None, default=False):
i, _ = self.last_cond_tuple
v = None
if self.values_source == "boolean_chain":
v = next(self.condition_value_generator)
else:
assert n is not None, str(n)
if self.values_source == "algorithm":
assert expr_name is not None, str(expr_name)
expr_values_dict = self.data["algorithm"]["expr_values"]
if expr_name in expr_values_dict:
expr_values = expr_values_dict[expr_name]
else:
raise ValueError(f"Algorithm processing error: No values of condition expression '{expr_name}' are provided.\nConsider example of how to specify values [true, true, false] for this condition as if it belongs to a loop:\n <pre>while {expr_name} -> 110 // loop_name</pre>")
v = get_ith_expr_value(expr_values, i=n - 1)
if self.values_source == "trace":
# find act with appropriate name and exec_time (phase is defaulted to "finished" as values are attached to these only)
assert expr_name is not None or executes_id is not None, str((expr_name, executes_id))
# print(self.data["trace"])
acts = [
act for act in
find_by_keyval_in("n", str(n), self.data["trace"])
# act["n"] == n and
if act["phase"] in ("finished", 'performed')
and (
# act["name"] == expr_name or
act["executes"] == executes_id
)
]
if acts:
assert len(acts) == 1, "Expected 1 act to be found, but got:\n " + str(acts)
act = acts[0]
v = act.get("value", None)
else:
print("Warning: cannot find student_act: %s" % (dict(expr_name=expr_name, executes_id=executes_id, n=n)))
if v is None:
v = default
print("next_cond_value(): defaulting to", default)
# v = bool(v)
self.last_cond_tuple = (i+1, v)
# print(f"next_cond_value: {v}")
return v
# long recursive function
def make_correct_trace_for_alg_node(node):
# copy reference
result = self.data["correct_trace"]
if node["type"] in {"func"}:
# phase = "started"
# ith = 1 + len([x for x in find_by_keyval_in("executes", node["body"]["id"], result) if x["phase"] == phase])
# result.append({
# "id": self.newID(),
# "name": node["name"],
# "executes": node["body"]["id"],
# "phase": phase,
# "n": ith,
# # "text_line": None,
# # "comment": None,
# })
for body_node in node["body"]["body"]:
make_correct_trace_for_alg_node(body_node)
if self.consequent_mode == "return":
self.consequent_mode = "normal"
break
if self.consequent_mode != "normal":
# return encountered
self.consequent_mode = "normal"
# phase = "finished"
# # ith = 1 + len([x for x in find_by_keyval_in("executes", node["body"]["id"], result) if x["phase"] == phase])
# result.append({
# "id": self.newID(),
# "name": node["name"],
# "executes": node["body"]["id"],
# "phase": phase,
# "n": ith,
# # "text_line": None,
# # "comment": None,
# })
if node["type"] in {"func_call"}:
func_id = node["func_id"]
# self.algorithm['functions']
func = self.id2obj[func_id]
phase = "started"
# ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
ith = 1 + len([x for x in find_by_keyval_in("func_id", func_id, result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"func_id": func_id,
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
self.indent_depth += 1
make_correct_trace_for_alg_node(func)
self.indent_depth -= 1
phase = "finished"
# # ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
# ith = 1 + len([x for x in find_by_keyval_in("func_id", func_id, result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"func_id": func_id,
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
if node["type"] in {"sequence", "else"}:
# do not wrap 'global_code'
if node["name"] != 'global_code':
phase = "started"
ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
for body_node in node["body"]:
make_correct_trace_for_alg_node(body_node)
if self.consequent_mode != "normal":
break
# do not wrap 'global_code'
if node["name"] != 'global_code':
phase = "finished"
# ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
if node["type"] in {"alternative"}:
phase = "started"
ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
for branch in node["branches"]:
make_correct_trace_for_alg_node(branch)
if self.last_cond_tuple[1] == True:
break
if self.consequent_mode != "normal":
break
phase = "finished"
# ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
if node["type"] in {"if", "else-if"}:
make_correct_trace_for_alg_node(node["cond"])
_,cond_v = self.last_cond_tuple
if cond_v:
phase = "started"
ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
for body_node in node["body"]:
make_correct_trace_for_alg_node(body_node)
if self.consequent_mode != "normal":
break
phase = "finished"
# ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
if node["type"] in {"expr"}:
if "has_func_call" in node:
make_correct_trace_for_alg_node(node["has_func_call"])
# "else":
if "has_func_call" not in node or ("merge_child_end_act" in node and not node["merge_child_end_act"]):
# just an ordinary trace line
phase = "performed"
ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
value = next_cond_value(node["name"], node["id"], ith)
self.expr_id2values[node["id"]] = self.expr_id2values.get(node["id"], []) + [value]
result.append({
"id": self.newID(),
"name": node["name"],
"value": value,
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
if node["type"] in {"stmt", "break", "continue", "return"}:
if "has_func_call" in node:
# relevant for "stmt" & "return"
make_correct_trace_for_alg_node(node["has_func_call"])
# if not node["merge_child_end_act"]:
# # separate "run" button
# # ... integrated into following `if`.
# "else":
if "has_func_call" not in node or ("merge_child_end_act" in node and not node["merge_child_end_act"]):
# just an ordinary trace line
phase = "performed"
ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
if node["type"] in {"break", "continue", "return"}:
self.consequent_mode = node["type"]
return # just stupidly stop current sequence
# TODO: keep the list of loop classes up-to-date
if node["type"] in {"while_loop", "do_while_loop", "do_until_loop", "for_loop", "foreach_loop", "infinite_loop", }:
phase = "started"
ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
inverse_cond = node["type"] == "do_until_loop"
stop_cond_value = (True == inverse_cond)
def _loop_context(): # wrapper for return
# loop begin
if node["type"] in {"for_loop", "foreach_loop"}:
make_correct_trace_for_alg_node(node["init"])
if node["type"] in {"while_loop", "for_loop", "foreach_loop"}:
make_correct_trace_for_alg_node(node["cond"])
if self.last_cond_tuple[1] == stop_cond_value:
return
# loop cycle
while True:
if node["type"] in {"foreach_loop"}:
make_correct_trace_for_alg_node(node["update"])
# итерация цикла!
make_correct_trace_for_alg_node(node["body"])
# как обрабатывать break из цикла?
if self.consequent_mode == "continue":
# reset mode
self.consequent_mode = "normal"
elif self.consequent_mode == "break":
# reset mode
self.consequent_mode = "normal"
return
elif self.consequent_mode != "normal":
# return encountered
return
if node["type"] in {"for_loop"}:
make_correct_trace_for_alg_node(node["update"])
if node["type"] not in {"infinite_loop"}:
make_correct_trace_for_alg_node(node["cond"])
if self.last_cond_tuple[1] == stop_cond_value:
return
_loop_context() # make a loop
phase = "finished"
# ith = 1 + len([x for x in find_by_keyval_in("executes", node["id"], result) if x["phase"] == phase])
result.append({
"id": self.newID(),
"name": node["name"],
"executes": node["id"],
"phase": phase,
"n": ith,
"indent_depth": self.indent_depth,
# "text_line": None,
# "comment": None,
})
alg_node = self.alg_entry()
name = "программа"
phase = "started"
self.data["correct_trace"].append({
"id": self.newID(),
"name": name,
"executes": alg_node["id"],
"phase": phase,
"n": 1,
# "text_line": None,
# "comment": None,
})
make_correct_trace_for_alg_node(alg_node)
phase = "finished"
self.data["correct_trace"].append({
"id": self.newID(),
"name": name,
"executes": alg_node["id"],
"phase": phase,
"n": 1,
# "text_line": None,
# "comment": None,
})
# print(self.data["trace"])
# print()
# print(self.data["correct_trace"])
# exit()
def inject_to_ontology(self, onto):
self.inject_algorithm_to_ontology(onto)
self.make_correct_trace(noop=True)
self.prepare_act_candidates(onto)
self.inject_trace_to_ontology(onto, self.data["trace"], (), "student_next")
# self.inject_trace_to_ontology(onto, self.data["correct_trace"], ("correct_act",), "correct_next")
# self.merge_traces(onto, self.data["student_act_iri_list"], self.data["correct_act_iri_list"])
def prepare_id2obj(self):
alg_objects = list(find_by_type(self.data["algorithm"]))
if not self.id2obj:
# fill it once
for d in alg_objects:
if "id" in d:
self.id2obj[ d["id"] ] = d
# store to original algorithm dict
self.data["algorithm"]["id2obj"] = self.id2obj
def inject_algorithm_to_ontology(self, onto):
"Prepares self.id2obj and writes algorithm to ontology if it isn't there."
if "entry_point" not in self.data["algorithm"]:
alg_node = self.data["algorithm"]["global_code"]
# polyfill entry_point to be global_code
self.data["algorithm"]["entry_point"] = alg_node
self.prepare_id2obj()
with onto:
if onto.algorithm_name and self.data["algorithm_name"] in [s for _,s in onto.algorithm_name.get_relations()]:
# do nothing as the algorithm is in the ontology
return
alg_objects = list(find_by_type(self.data["algorithm"]))
written_ids = set()
# make algorithm classes and individuals
for d in alg_objects:
if "id" not in d:
continue
id_ = d.get("id")
# (once more) protection from objects cloned via JSON serialization
if id_ in written_ids:
continue
else:
written_ids.add(id_)
type_ = d.get("type")
name = d.get("name", None) or d.get("stmt_name", "")
assert type_, "Error: No 'type' in algorithm object: " + str(d)
id_ = int(id_)
clean_name = prepare_name(name)
class_ = onto[type_]
if not class_:
# make a new class in the ontology
class_ = types.new_class(type_, (Thing, ))
# формируем имя экземпляра в онтологии
iri = "{}_{}".format(id_, clean_name)
iri = uniqualize_iri(onto, iri)
# сохраняем назад в наш словарь (для привязки к актам трассы)
d["iri"] = iri
### print('### saving iri back to dict:', iri)
# создаём объект
obj = class_(iri)
# привязываем id
make_triple(obj, onto.id, id_)
# привязываем имя
make_triple(obj, onto.stmt_name, name)
# make special string link identifying algorithm
if type_ == "algorithm":
prop = onto["algorithm_name"]
if not prop:
with onto:
# новое свойство по заданному имени
prop = types.new_class("algorithm_name", (Thing >> str, ))
make_triple(obj, prop, self.data["algorithm_name"])
elif True: # new experimental feature
# connect begin & end
class_ = onto.boundary
for prop_name in ("begin_of", "end_of"):
bound = class_(prop_name + "_" + iri)
make_triple(bound, onto[prop_name], obj)
# Добавляем скалярные поля
for field in ('func_name', "func_args", "func_id", "merge_child_begin_act", "merge_child_end_act"):
if field in d:
prop = onto[field]
if not prop:
assert False, f'{field} property not in onto!'
# with onto:
# # новое свойство по заданному имени
# prop = types.new_class(field, (DataProperty, ))
make_triple(obj, prop, d[field])
# link the instances: repeat the structure completely
for d in alg_objects:
if "id" not in d:
continue
for k in d: # ищем объекты среди полей словаря
v = d[k]
if isinstance(v, dict) and "id" in v and "iri" in v:
# connect all the properties of the instance
link_objects(onto, d["iri"], k, v["iri"], (Thing >> Thing, onto.parent_of,) )
elif isinstance(v, (list, set)):
# make an ordered linked_list for list, unorederd for set
# print("check out list", k, "...")
# сделаем список, если в нём нормальные "наши" объекты
subobject_iri_list = [subv["iri"] for subv in v if isinstance(subv, dict) and "id" in subv and "iri" in subv]
if not subobject_iri_list:
continue
iri = d["iri"]
# всякий список (действий, веток, ...) должен быть оформлен как linked_list.
if k == "body" and isinstance(v, list):
# делаем объект последовательностью (нужно для тел циклов, веток, функций)
onto[iri].is_a.append( onto.linked_list )
# else: # это нормально для других списков
# print("Warning: key of sequence is '%s' (consider using 'body')" % k)
subelem__prop_name = k+"_item"
for i, subiri in enumerate(subobject_iri_list):
# главная связь
link_objects(onto, iri, subelem__prop_name, subiri, (Thing >> Thing, onto.parent_of,) )
if isinstance(v, list): # for list only
# последовательность
if i >= 1:
prev_iri = subobject_iri_list[i-1]
link_objects(onto, prev_iri, "next", subiri)
# set the index of elem in the list
onto[subiri].item_index = i
# первый / последний
if i == 0:
# mark as first elem of the list
onto[subiri].is_a.append(onto.first_item)
if i == len(subobject_iri_list)-1:
# mark as last act of the list
onto[subiri].is_a.append(onto.last_item)
def prepare_act_candidates(self, onto, extra_act_entries=0):
"""Create all possible acts for each statement.
Maximum executon number will be exceeded by `extra_act_entries`.
/* Resulting set of acts of size N will be repeated N times, each act to be possibly placed at each index of the trace, covering the set of all possible traces. */ """
assert extra_act_entries == 0, f"extra_act_entries={extra_act_entries}" # TODO: remove parameter (it is deprecated now)
alg_id2max_exec_n = {st_id:0 for st_id in self.id2obj.keys()} # executed stmt id to max exec_time of the act
for act in self.data["correct_trace"]:
executed_id = act["executes"]
exec_n = act["n"]
alg_id2max_exec_n[executed_id] = exec_n # assume "n"s appear consequently in the trace
# ensure that student's acts exist
for act in self.data["trace"]:
executed_id = act["executes"]
exec_n = act.get("n", "1")
alg_id2max_exec_n[executed_id] = max(
int(exec_n), # assume "n"s appear consequently in the trace
int(alg_id2max_exec_n[executed_id]))
entry_stmt_id = self.alg_entry()["id"]
max_act_ID = 1000
def set_id(act_obj):
nonlocal max_act_ID
max_act_ID += 1
make_triple(act_obj, onto.id, max_act_ID)
# make top-level act representing the trace ...
iri = f'trace_{self.data["trace_name"]}'
if self.data["header_boolean_chain"]:
iri += f'_c{"".join(map(str, map(int, self.data["header_boolean_chain"])))}'
iri = iri.replace(" ", "_").strip("_")
iri = prepare_name(iri)
iri = uniqualize_iri(onto, iri)
trace_obj = onto.trace(iri)
self.trace_obj = trace_obj # remember for trace injection
trace_obj.is_a.append(onto.correct_act)
make_triple(trace_obj, onto.executes, onto[self.data["algorithm"]["iri"]])
set_id(trace_obj)
make_triple(trace_obj, onto.index, 0)
make_triple(trace_obj, onto.student_index, 0)
make_triple(trace_obj, onto.exec_time, 0) # set to 0 so next is 1
make_triple(trace_obj, onto.depth, 0) # set to 0 so next is 1
make_triple(trace_obj, onto.in_trace, trace_obj) # each act belongs to trace
# N = sum(alg_id2max_exec_n.values()) * 2 # as each stmt has begin & end!
# print(F"N of layers and N acts on layer: {N}")
for st_id, max_n in alg_id2max_exec_n.items():
alg_elem = self.id2obj[st_id]
if alg_elem["type"] in {"algorithm"}:
continue
# prepare data
name = alg_elem.get("name", "unkn")
clean_name = prepare_name(name)
mark2act_obj = {} # executed stmt id to list of act iri's can be consequently used in trace
# for index in range(1, N + 1):
for exec_n in range(1, max_n + 1):
# make instances: act_begin, act_end
number_mark = "" if max_n <=1 else ("_n%02d" % exec_n)
iri_template = f"%s_{clean_name}{number_mark}" # _i{index:02}
for mark, class_, boundary_prop in [("b", onto.act_begin, onto.begin_of), ("e", onto.act_end, onto.end_of)]:
iri = iri_template % mark
iri = uniqualize_iri(onto, iri)
obj = class_(iri)
# obj.is_a.append(class_X)
boundary = get_relation_subject(boundary_prop, onto[alg_elem["iri"]])
# print("boundary:", boundary)
make_triple(obj, onto.executes, boundary)
set_id(obj)
### make_triple(obj, onto.index, index)
make_triple(obj, onto.exec_time, exec_n)
make_triple(obj, onto.in_trace, trace_obj)
# # connect "next_sibling"
# if exec_n == 1:
# make_triple(trace_obj, onto.next_sibling, obj)
# else:
# make_triple(mark2act_obj[mark], onto.next_sibling, obj)
# keep current value for next iteration
mark2act_obj[mark] = obj
# attach expr value: for act_end only!
if mark == "e" and alg_elem["type"] in ("expr",):
values = self.expr_id2values[st_id] if st_id in self.expr_id2values else []
# if len(values) <= exec_n:
if exec_n <= len(values):
value = values[exec_n - 1]
else:
value = False
print("attach expr value: defaulting to False...")
# print(obj, onto.expr_value, value)
make_triple(obj, onto.expr_value, value)
# # connect trace begin and 1st act with "next"
# if mark == "b" and st_id == entry_stmt_id and index == exec_n == 1:
# obj.is_a.append(onto.correct_act)
# # obj.is_a.append(onto.current_act)
# make_triple(trace_obj, onto.next_act, obj)
def inject_trace_to_ontology(self, onto, trace, act_classnames=("act",), next_propertyname=None):
"Writes specified trace to ontology assigning properties to pre-created acts."
### print(' INJECTING the following TRACE:', *map(lambda d: ' -> ' + d['as_string'], trace), '', sep='\n')
additional_classes = [onto[nm] for nm in act_classnames]
assert all(additional_classes), f"additional_classes={additional_classes}, {act_classnames}, {onto}"
# make trace acts as individuals
prop_class = onto[next_propertyname]
def connect_next_act(obj):
trace_acts_list.append(obj)
# формируем последовательный список
if prop_class and len(trace_acts_list) > 1:
# привязываем next, если указано
prev_obj = trace_acts_list[-2]
obj = trace_acts_list[-1]
# print(">>", prev_obj, "-<-", obj)
make_triple(prev_obj, prop_class, obj)
if trace_acts_list:
num = len(trace_acts_list)
make_triple(obj, onto.student_index, num)
def find_act(class_, executes: int, exec_time: int, **fields: dict):
for obj in class_.instances():
# print(F"{obj}: ")
if ((
# an act executes a boundary while trace executes algorithm itself
obj.executes.INDIRECT_boundary_of or obj.executes
).id == executes and
((obj.exec_time == exec_time) or (exec_time is None)) and
(self.trace_obj in obj.in_trace) and
all((getattr(obj, k, None) == v) or (v is None) for k,v in fields.items())):
return obj
print(f"act not found: ex={executes}, {', '.join([f'n={exec_time}'] + [f'{k}={v}' for k,v in fields.items()])}")
return None
with onto:
i = 0
# act_index = 0
trace_acts_list = []
trace_acts_list.append(find_act(onto.trace, self.data["algorithm"]["id"], 0))
for d in trace:
i += 1
if "id" in d:
id_ = d.get("id")
executes = d.get("executes")
# phase: (started|finished|performed)
phase = d.get("phase") # , "performed"
n = d.get("n", None) or d.get("n_", None)
iteration_n = d.get("iteration_n", None)
name = d.get("name", None) or d.get("action", None) # ! name <- action
text_line = d.get("text_line", None)
expr_value = d.get("value", None)
id_ = int(id_)
clean_name = prepare_name(name)
phase_mark = {"started":"b", "finished":"e", "performed":"p",}[phase]
n = n and int(n) # convert if not None (n cannot be 0)
number_mark = "" if not n else ("_n%d" % n)
# find related algorithm element
assert executes in self.id2obj, (self.id2obj, d)
alg_elem = self.id2obj[executes]
# iri_template = "{}%s_{}{}".format(text_line or id_, clean_name, number_mark)
if phase_mark in ("b", "p"):
# начало акта
obj = find_act(onto.act_begin, executes, n or None)
if obj:
for class_ in additional_classes:
obj.is_a.append(class_)
# привязываем нужные свойства
make_triple(obj, onto.text_line, text_line)
make_triple(obj, onto.id, id_) # ID могут быть не уникальны, но должны соответствовать id актов из GIU
if iteration_n:
make_triple(obj, onto.student_iteration_n, iteration_n)
connect_next_act(obj)
else:
print(" act name:", name)
# # НЕ привязываем id (т.к. может повторяться у начал и концов. TO FIX?)
# if "value" in d:
# make_triple(obj, onto.expr_value, d["value"])
if phase_mark in ("e", "p"):
# конец акта
obj = find_act(onto.act_end, executes, n or None)
if obj:
for class_ in additional_classes:
obj.is_a.append(class_)
# привязываем нужные свойства
make_triple(obj, onto.text_line, text_line)
make_triple(obj, onto.id, id_) # ID могут быть не уникальны, но должны соответствовать id актов из GIU
if expr_value is not None:
make_triple(obj, onto.expr_value, expr_value)
if iteration_n:
make_triple(obj, onto.student_iteration_n, iteration_n)
connect_next_act(obj)
else:
print(" act name:", name)
# iri_list_key = act_classnames[0] + "_iri_list"
# self.data[iri_list_key] = trace_acts_list
# end of TraceTester class
def make_trace_for_algorithm(alg_dict):
"""just a wrapper for TraceTester.make_correct_trace() method"""
try:
trace_data = {
"algorithm": alg_dict,
"header_boolean_chain": None,
}
tt = TraceTester(trace_data)
tt.prepare_id2obj()
tt.make_correct_trace()
# Очистить словарь alg_dict["id2obj"] от рекурсивной ссылки на сам alg_dict
for key in alg_dict["id2obj"]:
if alg_dict["id2obj"][key] is alg_dict:
del alg_dict["id2obj"][key]
break
return tt.data["correct_trace"]
except Exception as e:
print("Error !")
print("Error making correct_trace:")
print(" ", e)
# raise e # useful for debugging
return str(e)
def algorithm_only_to_onto(alg_tr, onto):
"""just a wrapper for TraceTester.inject_algorithm_to_ontology() method: