-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathle_input.pl
executable file
·2591 lines (2254 loc) · 127 KB
/
le_input.pl
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
/* le_input: a prolog module with predicates to translate from an
extended version of Logical English into the Prolog or Taxlogtemplate_decl
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Main predicate: text_to_logic(String to be translated, Translation)
Main DCG nonterminal: document(Translation)
See at the end the predicate le_taxlog_translate to be used from SWISH
It assumes an entry with the following structure. One of these expressions:
the meta predicates are:
the predicates are:
the templates are:
the timeless predicates are:
the event predicates are:
the fluents are:
the time-varying predicates are:
followed by the declarations of all the corresponding predicates mentioned in the
knowledge base.
Each declarations define a template with the variables and other words required to
describe a relevant relation. It is a comma separated list of templates which ends
with a period.
After that period, one of the following statement introduces the knowledge base:
the knowledge base includes:
the knowledge base <Name> includes:
And it is followed by the rules and facts written in Logical English syntax.
Each rule must end with a period.
Indentation is used to organize the and/or list of conditions by strict
observance of one condition per line with a level of indentation that
corresponds to each operator and corresponding conditions.
Similarly, there may be sections for scenarios and queries, like:
--
scenario test2 is:
borrower pays an amount to lender on 2015-06-01T00:00:00.
--
and
--
query one is:
for which event:
the small business restructure rollover applies to the event.
query two is:
which tax payer is a party of which event.
query three is:
A first time is after a second time
and the second time is immediately before the first time.
--
which can then be used on the new command interface of LE on SWISH as defined in module le_answer.pl
(e.g. answer/1 and others querying predicates):
? answer("query one with scenario test").
*/
:- module(le_input,
[document/3, text_to_logic/2,
predicate_decl/4, showErrors/2,
op(1000,xfy,user:and), % to support querying
op(800,fx,user:resolve), % to support querying
op(800,fx,user:answer), % to support querying
op(800,fx,user:répondre), % to support querying in french
op(850,xfx,user:with), % to support querying
op(850,xfx,user:avec), % to support querying in french
op(800,fx,user:risposta), % to support querying in italian
op(850,xfx,user:con), % to support querying in italian
op(800,fx,user:responde), % to support querying in spanish
%op(1150,fx,user:show), % to support querying
op(850,xfx,user:of), % to support querying
%op(850,fx,user:'#pred'), % to support scasp
%op(800,xfx,user:'::'), % to support scasp
op(950, xfx, ::), % pred not x :: "...".
op(1200, fx, #),
op(1150, fx, pred),
op(1150, fx, show),
op(1150, fx, abducible),
dictionary/3, meta_dictionary/3, dict/3, meta_dict/3,
parsed/0, source_lang/1, including/0, %just_saved_scasp/2,
this_capsule/1, unpack_tokens/2, clean_comments/2,
query_/2, extract_constant/4, spaces/3, name_as_atom/2, process_types_or_names/4,
matches_name/4, matches_type/4, delete_underscore/2, add_determiner/2, proper_det/2,
portray_clause_ind/1, order_templates/2, process_types_dict/2,
assertall/1,asserted/1,
update_file/3, myDeclaredModule/1, conditions/6, op_stop/1
]).
:- multifile sandbox:safe_primitive/1.
:- use_module('./tokenize/prolog/tokenize.pl').
:- if(current_module(swish)).
:- use_module('le_swish.pl'). % module to handle the gitty filesystem
:- else.
:- use_module('le_local.pl'). % module to handle the local filesystem
:- endif.
:- if(exists_source(library(r/r_call))).
:- use_module(library(r/r_call)).
:- endif.
:- use_module('reasoner.pl').
:- use_module(library(prolog_stack)).
:- table addExp//2, mulExp//2.
:- thread_local text_size/1, error_notice/4, dict/3, meta_dict/3, example/2, local_dict/3, local_meta_dict/3,
last_nl_parsed/1, kbname/1, happens/2, initiates/3, terminates/3, is_type/1, is_/2, is_a/2,
predicates/1, events/1, fluents/1, metapredicates/1, parsed/0, source_lang/1, including/0. % just_saved_scasp/2.
:- discontiguous statement/3, declaration/4, _:example/2, _:query/2, _:is_/2.
% Main clause: text_to_logic(+String,-Clauses) is det
% Errors are added to error_notice
% text_to_logic/2
text_to_logic(String_, Translation) :-
% hack to ensure a newline at the end, for the sake of error reporting:
((sub_atom(String_,_,1,0,NL), memberchk(NL,['\n','\r']) ) -> String=String_ ; atom_concat(String_,'\n',String)),
tokenize(String, Tokens, [cased(true), spaces(true), numbers(true)]),
retractall(last_nl_parsed(_)), asserta(last_nl_parsed(1)), % preparing line counting
unpack_tokens(Tokens, UTokens),
clean_comments(UTokens, CTokens), !,
% print_message(informational, "CTokens: ~w"-[CTokens]),
phrase(document(Translation), CTokens).
%print_message(informational, "Translation: ~w"-[Translation]).
%with_output_to(string(Report), listing(dict/3)),
%print_message(informational, "Dictionaries in memory after loading and parsing ~w\n"-[Report]).
%( phrase(document(Translation), CTokens) ->
% ( print_message(informational, "Translation: ~w"-[Translation]) )
%; ( print_message(informational, "Translation failed: ~w"-[CTokens]), Translation=[], fail)).
% document/3 (or document/1 in dcg)
document(Translation, In, Rest) :-
(parsed -> retractall(parsed); true),
(including -> retract(including); true),
(source_lang(_L) -> retractall(source_lang(_)) ; true),
phrase(header(Settings), In, AfterHeader), !, %print_message(informational, "Declarations completed: ~w"-[Settings]),
phrase(content(Content), AfterHeader, Rest), %print_message(informational, "Content: ~w"-[AfterHeader]),
append(Settings, Content, Translation), !,
%append(Original, [if(is_(A,B), (nonvar(B), is(A,B)))], Translation), % adding def of is_2 no more
assertz(parsed).
% header parses all the declarations and assert them into memory to be invoked by the rules.
% header/3
header(Settings, In, Next) :-
length(In, TextSize), % after comments were removed
phrase(settings(DictEntries, Settings_), In, Next),
fix_settings(Settings_, Settings2),
RulesforErrors = [(text_size(TextSize))|Settings2], % is text_size being used? % asserting the Settings too! predicates, events and fluents
included_files(Settings2, RestoredDictEntries, CollectedRules),
append(Settings2, CollectedRules, Settings),
append(DictEntries, RestoredDictEntries, AllDictEntries),
order_templates(AllDictEntries, OrderedEntries),
process_types_dict(OrderedEntries, Types),
%print_message(informational, "header: types ~w rules ~w"-[Types, CollectedRules]),
append(OrderedEntries, RulesforErrors, SomeRules),
append(SomeRules, Types, MRules),
%print_message(informational, "rules ~w"-[MRules]),
assertall(MRules), !. % asserting contextual information
header(_, Rest, _) :-
asserterror('LE error in the header ', Rest),
fail.
fix_settings(Settings_, Settings3) :-
%print_message(informational, "Settings: ~w"-[Settings_]),
( member(target(_), Settings_) -> Settings1 = Settings_ ; Settings1 = [target(taxlog)|Settings_] ), !, % taxlog as default
% adding dynamic statements for all the predef_dict templates
% adding special header for is_a/2
findall(Pred, filtered_dictionary(Pred), PH),
filter_repeats(PH, PredefHeaders),
%print_message(informational, "Predefined Predicates ~w"-[PredefHeaders]),
( member(predicates(Templates), Settings1) ->
( append(Previous, [predicates(Templates)|Rest], Settings1), % replacing predicates/1
append(Templates, PredefHeaders, AllTemplates), append(Previous, Rest, IncompleteSettings),
Settings2 = [predicates(AllTemplates)|IncompleteSettings] )
; Settings2 = [predicates(PredefHeaders)|Settings1]
),
Settings3 = [query(null, true), example(null, []), abducible(true,true)|Settings2]. % a hack to stop the loop when query is empty
filter_repeats([], []) :- !.
filter_repeats([H|R], RR) :- member(H,R), !, filter_repeats(R, RR).
filter_repeats([H|R], [H|RR]) :- filter_repeats(R, RR).
fix_dictionary(Dict, Dict).
included_files(Settings2, RestoredDictEntries, CollectedRules) :-
member(in_files(ModuleNames), Settings2), % include all those files and get additional DictEntries before ordering
%print_message(informational, "Module Names ~w\n"-[ModuleNames]),
assertz(including), !, % cut to prevent escaping failure of load_all_files
load_all_files(ModuleNames, RestoredDictEntries, CollectedRules).
%print_message(informational, "Restored Entries ~w\n"-[RestoredDictEntries]).
included_files(_, [], []).
%load_all_files/2
%load the prolog files that correspond to the modules names listed in the section of inclusion
%and produces the list of entries that must be added to the dictionaries
load_all_files([], [], []).
load_all_files([Name|R], AllDictEntries, AllRules) :-
%print_message(informational, "Loading ~w"-[Name]),
split_module_name(Name, File, URL),
%print_message(informational, "File ~w URL ~w"-[File, URL]),
concat(File, "-prolog", Part1), concat(Part1, ".pl", Filename),
(URL\=''->atomic_list_concat([File,'-prolog', '+', URL], NewName); atomic_list_concat([File,'-prolog'], NewName)),
%print_message(informational, "File ~w FullName ~w"-[Filename, NewName]),
load_file_module(Filename, NewName, true), !,
%print_message(informational, "the dictionaries of ~w being restored into module ~w"-[Filename, NewName]),
(NewName:local_dict(_,_,_) -> findall(dict(A,B,C), NewName:local_dict(A,B,C), ListDict) ; ListDict = []),
(NewName:local_meta_dict(_,_,_) -> findall(meta_dict(A,B,C), NewName:local_meta_dict(A,B,C), ListMetaDict); ListMetaDict = []),
append(ListDict, ListMetaDict, DictEntries),
%print_message(informational, "the dictionaries being restored are ~w"-[DictEntries]),
%listing(NewName:_),
findall(if(H,B), (member(dict(E, _,_), DictEntries), E\=[], H=..E, clause(NewName:H, B)), Rules),
findall(Pred, (member(dict(E,_,_), ListDict), E\=[], Pred=..E), ListOfPred),
findall(MPred, (member(dict(ME,_,_), ListMetaDict), ME\=[], MPred=..ME), ListOfMPred),
append([predicates(ListOfPred), metapredicates(ListOfMPred)], Rules, TheseRules), % for term expansion
%print_message(informational, "rules to copy ~w"-[Rules]),
%collect_all_preds(SwishModule, DictEntries, Preds),
%print_message(informational, "the dictionaries being set dynamics are ~w"-[Preds]),
%declare_preds_as_dynamic(SwishModule, Preds)
print_message(informational, "Loaded ~w"-[Filename]),
load_all_files(R, RDict, NextRules),
append(RDict, DictEntries, AllDictEntries),
append(TheseRules, NextRules, AllRules).
load_all_files([Filename|_], [], []) :-
print_message(informational, "Failed to load file ~w"-[Filename]), fail.
% Experimental rules for processing types:
process_types_dict(Dictionary, Type_entries) :-
findall(Word,
( (member(dict([_|GoalElements], Types, _), Dictionary);
member(meta_dict([_|GoalElements], Types, _), Dictionary)),
member((_Name-Type), Types),
process_types_or_names([Type], GoalElements, Types, TypeWords),
concat_atom(TypeWords, '_', Word), Word\=''), Templates),
(Templates\=[] -> setof(is_type(Ty), member(Ty, Templates), Type_entries) ; Type_entries = []).
% process_types_or_names/4
process_types_or_names([], _, _, []) :- !.
:- if(exists_source(library(r/r_call))).
process_types_or_names([Word|RestWords], Elements, Types, [the, chart|RestPrintWords] ) :-
nonvar(Word), Word = plot_command(RExecuteCommand),
copy_term(RExecuteCommand,RExecuteCommandForDisplay),
RExecuteCommandForDisplay, % plot the image onto the screen
<- png("image.png"), RExecuteCommand, % plot the image into the file
<- graphics.off(), r_swish:r_download("image.png"), % close the device and show the download button
process_types_or_names(RestWords, Elements, Types, RestPrintWords).
:- endif.
process_types_or_names([Word|RestWords], Elements, Types, PrintExpression ) :-
atom(Word), concat_atom(WordList, '_', Word), !,
process_types_or_names(RestWords, Elements, Types, RestPrintWords),
append(WordList, RestPrintWords, PrintExpression).
process_types_or_names([Word|RestWords], Elements, Types, PrintExpression ) :-
var(Word), matches_name(Word, Elements, Types, Name), !,
process_types_or_names(RestWords, Elements, Types, RestPrintWords),
tokenize_atom(Name, NameWords), delete_underscore(NameWords, CNameWords),
add_determiner(CNameWords, PrintName), append(['*'|PrintName], ['*'|RestPrintWords], PrintExpression).
process_types_or_names([Word|RestWords], Elements, Types, [PrintWord|RestPrintWords] ) :-
matches_type(Word, Elements, Types, date),
((nonvar(Word), number(Word)) -> unparse_time(Word, PrintWord); PrintWord = Word), !,
process_types_or_names(RestWords, Elements, Types, RestPrintWords).
process_types_or_names([Word|RestWords], Elements, Types, [PrintWord|RestPrintWords] ) :-
matches_type(Word, Elements, Types, day),
((nonvar(Word), number(Word)) -> unparse_time(Word, PrintWord); PrintWord = Word), !,
process_types_or_names(RestWords, Elements, Types, RestPrintWords).
process_types_or_names([Word|RestWords], Elements, Types, Output) :-
compound(Word),
translate_goal_into_LE(Word, PrintWord), !, % cut the alternatives
process_types_or_names(RestWords, Elements, Types, RestPrintWords),
append(PrintWord, RestPrintWords, Output).
process_types_or_names([Word|RestWords], Elements, Types, [Word|RestPrintWords] ) :-
process_types_or_names(RestWords, Elements, Types, RestPrintWords).
% Experimental rules for reordering of templates
% order_templates/2
order_templates(NonOrdered, Ordered) :-
predsort(compare_templates, NonOrdered, Ordered).
compare_templates(<, meta_dict(_,_,_), dict(_,_,_)).
compare_templates(=, dict(_,_,T1), dict(_,_,T2)) :- T1 =@= T2.
compare_templates(<, dict(_,_,T1), dict(_,_,T2)) :- length(T1, N1), length(T2, N2), N1>N2.
compare_templates(<, dict(_,_,T1), dict(_,_,T2)) :- length(T1, N), length(T2, N), template_before(T1, T2).
compare_templates(>, Dict1, Dict2) :- not(compare_templates(=, Dict1, Dict2)), not(compare_templates(<, Dict1, Dict2)).
compare_templates(=, meta_dict(_,_,T1), meta_dict(_,_,T2)) :- T1 =@= T2.
compare_templates(<, meta_dict(_,_,T1), meta_dict(_,_,T2)) :- length(T1, N1), length(T2, N2), N1>N2.
compare_templates(<, meta_dict(_,_,T1), meta_dict(_,_,T2)) :- length(T1, N), length(T2, N), template_before(T1, T2).
template_before([H1], [H2]) :- H1 =@= H2.
template_before([H1|_R1], [H2|_R2]) :- nonvar(H1), var(H2).
template_before([H1|_R1], [H2|_R2]) :- H1 @> H2.
template_before([H1|R1], [H2|R2]) :- H1=@=H2, template_before(R1, R2).
/* --------------------------------------------------------- LE DCGs */
% settings/2 or /4
settings(AllR, AllS) -->
spaces_or_newlines(_), declaration(Rules,Setting), settings(RRules, RS),
{append(Setting, RS, AllS), append(Rules, RRules, AllR)}, !.
settings([], [], Stay, Stay) :- !,
( phrase(rules_previous(_), Stay, _) ;
phrase(ontology_, Stay, _) ;
phrase(scenario_, Stay, _) ;
phrase(query_, Stay, _) ;
phrase(the_plots_are_, Stay, _) ).
% settings ending with the start of the knowledge base or ontology or scenarios or queries.
settings(_, _, Rest, _) :-
asserterror('LE error in the declarations on or before ', Rest),
fail.
settings([], [], Stay, Stay).
% content structure: cuts added to avoid search loop
% content/1 or /3
content(T) --> %{print_message(informational, "going for KB:"-[])},
spaces_or_newlines(_), rules_previous(Kbname), %{print_message(informational, "KBName: ~w"-[Kbname])},
kbase_content(S), %{print_message(informational, "KB: ~w"-[S])},
content(R), {append([kbname(Kbname)|S], R, T)}, !.
content(T) --> %{print_message(informational, "going for the ontology:"-[])},
spaces_or_newlines(_), ontology_content(S), %{print_message(informational, "ontology: ~w"-[S])},
content(R), {append(S, R, T)}, !.
% the annexes to the contract are:
content(T) --> %{print_message(informational, "going for the annexes:"-[])},
spaces_or_newlines(_), annexes_content(S), %{print_message(informational, "annexes: ~w"-[S])},
content(R), {append(S, R, T)}, !.
content(T) --> %{print_message(informational, "going for scenario:"-[])},
spaces_or_newlines(_), scenario_content(S), %{print_message(informational, "scenario: ~w"-[S])},
content(R), {append(S, R, T)}, !.
content(T) --> %{print_message(informational, "going for query:"-[])},
spaces_or_newlines(_), query_content(S), content(R), {append(S, R, T)}, !.
content([]) --> spaces_or_newlines(_).
content(_, Rest, _) :-
asserterror('LE error in the content ', Rest),
fail.
% kbase_content/1 or /3
kbase_content(T) -->
spaces_or_newlines(_), statement(S), kbase_content(R),
{append(S, R, T)}, !.
kbase_content([]) -->
spaces_or_newlines(_), [].
kbase_content(_, Rest, _) :-
asserterror('LE error in a knowledge base ', Rest),
fail.
% declaration/2 or /4
% target
declaration([], [target(Language)]) --> % one word description for the language: prolog, taxlog
spaces(_), [the], spaces(_), [target], spaces(_), [language], spaces(_), [is], spaces(_), colon_or_not_,
spaces(_), [Language], spaces(_), period, !, {assertz(source_lang(en))}.
% french: la langue cible est : prolog
declaration([], [target(Language)]) --> % one word description for the language: prolog, taxlog
spaces(_), [la], spaces(_), [langue], spaces(_), [cible], spaces(_), [est], spaces(_), colon_or_not_,
spaces(_), [Language], spaces(_), period, !, {assertz(source_lang(fr))}.
% italian: il linguaggio destinazione è : prolog
declaration([], [target(Language)]) --> % one word description for the language: prolog, taxlog
spaces(_), [il], spaces(_), [linguaggio], spaces(_), [destinazione], spaces(_), [è], spaces(_), colon_or_not_,
spaces(_), [Language], spaces(_), period, !, {assertz(source_lang(it))}.
% spanish: el lenguaje objetivo es: prolog
declaration([], [target(Language)]) --> % one word description for the language: prolog, taxlog
spaces(_), [el], spaces(_), [lenguaje], spaces(_), [objetivo], spaces(_), [es], spaces(_), colon_or_not_,
spaces(_), [Language], spaces(_), period, !, {assertz(source_lang(es))}.
% meta predicates
declaration(Rules, [metapredicates(MetaTemplates)]) -->
meta_predicate_previous, list_of_meta_predicates_decl(Rules, MetaTemplates), !.
%timeless or just templates
declaration(Rules, [predicates(Templates)]) -->
predicate_previous, list_of_predicates_decl(Rules, Templates), !.
%events
declaration(Rules, [events(EventTypes)]) -->
event_predicate_previous, list_of_predicates_decl(Rules, EventTypes), !.
%time varying
declaration(Rules, [fluents(Fluents)]) -->
fluent_predicate_previous, list_of_predicates_decl(Rules, Fluents), !.
%files to be included
declaration([kbname(KBName)], [in_files(Files)]) -->
files_to_include_previous(KBName), list_of_files(Files), !.
%
declaration(_, _, Rest, _) :-
asserterror('LE error in a declaration on or before ', Rest),
fail.
colon_or_not_ --> [':'], spaces(_).
colon_or_not_ --> [].
meta_predicate_previous -->
spaces(_), [the], spaces(_), [metapredicates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
meta_predicate_previous -->
spaces(_), [the], spaces(_), [meta], spaces(_), [predicates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
meta_predicate_previous -->
spaces(_), [the], spaces(_), [meta], spaces(_), ['-'], spaces(_), [predicates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
% french : les modèles sont :
meta_predicate_previous -->
spaces(_), [les], spaces(_), ['méta'], spaces(_), ['modèles'], spaces(_), [sont], spaces(_), [':'], spaces_or_newlines(_).
% italian: i predicati sono:
meta_predicate_previous -->
spaces(_), [i], spaces(_), [meta], spaces(_), [modelli], spaces(_), [sono], spaces(_), [':'], spaces_or_newlines(_).
% spanish: los predicados son:
meta_predicate_previous -->
spaces(_), [los], spaces(_), [meta], spaces(_), [predicados], spaces(_), [son], spaces(_), [':'], spaces_or_newlines(_).
predicate_previous -->
spaces(_), [the], spaces(_), [predicates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
predicate_previous -->
spaces(_), [the], spaces(_), [templates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
predicate_previous -->
spaces(_), [the], spaces(_), [timeless], spaces(_), [predicates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
% french : les modèles sont :
predicate_previous -->
spaces(_), [les], spaces(_), ['modèles'], spaces(_), [sont], spaces(_), [':'], spaces_or_newlines(_).
% italian: i predicati sono:
predicate_previous -->
spaces(_), [i], spaces(_), [modelli], spaces(_), [sono], spaces(_), [':'], spaces_or_newlines(_).
% spanish: los predicados son:
predicate_previous -->
spaces(_), [los], spaces(_), [predicados], spaces(_), [son], spaces(_), [':'], spaces_or_newlines(_).
event_predicate_previous -->
spaces(_), [the], spaces(_), [event], spaces(_), [predicates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
fluent_predicate_previous -->
spaces(_), [the], spaces(_), [fluents], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
fluent_predicate_previous -->
spaces(_), [the], spaces(_), [time], ['-'], [varying], spaces(_), [predicates], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
the_plots_are_ --> spaces(_), [the], spaces(_), [plots], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_).
files_to_include_previous(KBName) -->
spaces_or_newlines(_), [the], spaces(_), ['knowledge'], spaces(_), [base], extract_constant([includes], NameWords), [includes],
spaces(_), [these], spaces(_), [files], spaces(_), [':'], !, spaces_or_newlines(_), {name_as_atom(NameWords, KBName)}.
% at least one predicate declaration required
list_of_predicates_decl([], []) --> spaces_or_newlines(_), next_section, !.
list_of_predicates_decl([Ru|Rin], [F|Rout]) --> spaces_or_newlines(_), predicate_decl(Ru,F), comma_or_period, list_of_predicates_decl(Rin, Rout), !.
list_of_predicates_decl(_, _, Rest, _) :-
asserterror('LE error found in a template declaration ', Rest),
fail.
% at least one predicate declaration required
list_of_meta_predicates_decl([], []) --> spaces_or_newlines(_), next_section, !.
list_of_meta_predicates_decl([Ru|Rin], [F|Rout]) -->
spaces_or_newlines(_), meta_predicate_decl(Ru,F), comma_or_period, list_of_meta_predicates_decl(Rin, Rout).
list_of_meta_predicates_decl(_, _, Rest, _) :-
asserterror('LE error found in the declaration of a meta template ', Rest),
fail.
% at least one filename of a file to include
list_of_files([]) --> spaces_or_newlines(_), next_section, !.
list_of_files([Filename|Rout]) --> spaces_or_newlines(_), extract_string([Filename]),
{print_message(informational, "list_of_files: filename ~w "-[Filename])},
list_of_files(Rout), !.
%{name_as_atom(NameWords, Filename)}.
list_of_files(_, Rest, _) :-
asserterror('LE error found in a file to include ', Rest),
fail.
% next_section/2
% a hack to avoid superflous searches format(string(Mess), "~w", [StopHere]), print_message(informational, Message),
next_section(StopHere, StopHere) :-
phrase(meta_predicate_previous, StopHere, _), !. % format(string(Message), "Next meta predicates", []), print_message(informational, Message).
next_section(StopHere, StopHere) :-
phrase(predicate_previous, StopHere, _), !. % format(string(Message), "Next predicates", []), print_message(informational, Message).
next_section(StopHere, StopHere) :-
phrase(event_predicate_previous, StopHere, _), !. % format(string(Message), "Next ecent predicates", []), print_message(informational, Message).
next_section(StopHere, StopHere) :-
phrase(fluent_predicate_previous, StopHere, _), !. % format(string(Message), "Next fluents", []), print_message(informational, Message).
next_section(StopHere, StopHere) :-
phrase(files_to_include_previous(_), StopHere, _), !.
next_section(StopHere, StopHere) :-
phrase(ontology_, StopHere, _), !.
next_section(StopHere, StopHere) :-
phrase(rules_previous(_), StopHere, _), !. % format(string(Message), "Next knowledge base", []), print_message(informational, Message).
next_section(StopHere, StopHere) :-
phrase(scenario_, StopHere, _), !. % format(string(Message), "Next scenario", []), print_message(informational, Message).
next_section(StopHere, StopHere) :-
phrase(query_, StopHere, _). % format(string(Message), "Next query", []), print_message(informational, Message).
next_section(StopHere, StopHere) :-
phrase(the_plots_are_, StopHere, _), !.
% predicate_decl/2
predicate_decl(dict([Predicate|Arguments],TypesAndNames, Template), Relation) -->
spaces(_), template_decl(RawTemplate),
{build_template(RawTemplate, Predicate, Arguments, TypesAndNames, Template),
Relation =.. [Predicate|Arguments]}, !.
% we are using this resource of the last clause to record the error and its details
% not very useful with loops, of course.
% error clause
predicate_decl(_, _, Rest, _) :-
asserterror('LE error found in a declaration ', Rest),
fail.
% meta_predicate_decl/2
meta_predicate_decl(meta_dict([Predicate|Arguments],TypesAndNames, Template), Relation) -->
spaces(_), template_decl(RawTemplate),
{build_template(RawTemplate, Predicate, Arguments, TypesAndNames, Template),
Relation =.. [Predicate|Arguments]}.
meta_predicate_decl(_, _, Rest, _) :-
asserterror('LE error found in a meta template declaration ', Rest),
fail.
rules_previous(default) -->
spaces_or_newlines(_), [the], spaces(_), [rules], spaces(_), [are], spaces(_), [':'], spaces_or_newlines(_), !.
rules_previous(KBName) -->
spaces_or_newlines(_), [the], spaces(_), ['knowledge'], spaces(_), [base], extract_constant([includes], NameWords), [includes], spaces(_), [':'], !, spaces_or_newlines(_),
{name_as_atom(NameWords, KBName)}.
rules_previous(default) --> % backward compatibility
spaces_or_newlines(_), [the], spaces(_), ['knowledge'], spaces(_), [base], spaces(_), [includes], spaces(_), [':'], spaces_or_newlines(_).
% italian: la base di conoscenza <nome> include
rules_previous(KBName) -->
spaces_or_newlines(_), [la], spaces(_), [base], spaces(_), [di], spaces(_), [conoscenza], spaces(_), extract_constant([include], NameWords), [include], spaces(_), [':'], !, spaces_or_newlines(_),
{name_as_atom(NameWords, KBName)}.
% french: la base de connaissances dont le nom est <nom> comprend :
rules_previous(KBName) -->
spaces_or_newlines(_), [la], spaces(_), [base], spaces(_), [de], spaces(_), [connaissances], spaces(_), [dont], spaces(_), [le], spaces(_), [nom], spaces(_), [est], extract_constant([comprend], NameWords), [comprend], spaces(_), [':'], !, spaces_or_newlines(_),
{name_as_atom(NameWords, KBName)}.
% spanish: la base de conocimiento <nombre> incluye:
rules_previous(KBName) -->
spaces_or_newlines(_), [la], spaces(_), [base], spaces(_), [de], spaces(_), [conocimiento], extract_constant([incluye], NameWords), [incluye], spaces(_), [':'], !, spaces_or_newlines(_),
{name_as_atom(NameWords, KBName)}.
% scenario_content/1 or /3
% a scenario description: assuming one example -> one scenario -> one list of facts.
scenario_content(Scenario) --> %{print_message(informational, "starting scenario: "-[])},
scenario_, extract_constant([is, es, est, è], NameWords), is_colon_, newline, %{print_message(informational, " scenario: ~w"-[NameWords])},
%list_of_facts(Facts), period, !,
spaces(_), assumptions_(Assumptions), !, % period is gone
%{print_message(informational, "scenario: ~w has ~w"-[NameWords, Assumptions])},
{name_as_atom(NameWords, Name), Scenario = [example( Name, [scenario(Assumptions, true)])]}.
scenario_content(_, Rest, _) :-
asserterror('LE error found around this scenario expression: ', Rest), fail.
% ontology_content/1 or /3
% an ontology description. All assumptions are added to the kb after verification.
ontology_content(Ontology) --> %spypoint, %{print_message(informational, "starting scenario: "-[])},
ontology_previous(_Name), kbase_content(Ontology), !.
% for the moment, the ontology is added directly to the kb. .
ontology_content(_, Rest, _) :-
asserterror('LE error found around this ontology expression: ', Rest), fail.
% ontology_previous//1
ontology_previous(default) -->
spaces_or_newlines(_), ss_([the, ontology, is, :]), spaces_or_newlines(_).
ontology_previous(KBName) -->
ontology_, [named], spaces(_), [','], extract_constant([',', is, es, est, 'è'], NameWords), [','], spaces(_), is_colon_, spaces_or_newlines(_), %{print_message(informational, " scenario: ~w"-[NameWords])},
{name_as_atom(NameWords, KBName)}.
% annexes_content/1 or /3
% an annexes description. All assumptions are added to the kb after verification.
annexes_content(Annexes) --> %spypoint, %{print_message(informational, "starting scenario: "-[])},
annexes_previous(_Name), kbase_content(Annexes), !.
% for the moment, the ontology is added directly to the kb. .
annexes_content(_, Rest, _) :-
asserterror('LE error found around this annexes expression: ', Rest), fail.
% annexes_previous//1
annexes_previous(default) -->
spaces_or_newlines(_), ss_([the, annexes, to, the, contract, are, :]), spaces_or_newlines(_).
% query_content/1 or /3
% statement: the different types of statements in a LE text
% a query
query_content(Query) -->
query_, extract_constant([is, es, est, è], NameWords), is_colon_, spaces_or_newlines(_),
query_header(Ind0, Map1),
conditions(Ind0, Map1, _, Conds), !, period, % period stays!
{name_as_atom(NameWords, Name), Query = [query(Name, Conds)]}.
query_content(_, Rest, _) :-
asserterror('LE error found around this expression: ', Rest), fail.
plot_content(PlotList) -->
the_plots_are_, plot_statement_list(PlotList).
plot_statement_list([Statement | StatementRest]) -->
plot_statement(Statement), plot_statement_list(StatementRest).
plot_statement_list([]) --> [].
plot_statement(Statement) --> spaces_or_newlines(_), currentLine(L),
literal_([], Map1, Head), plot_body(Body, Map1, _), period,
{Statement = [if(L, Head, Body)]}.
concat_body_with_comma([A | B], (A, BB)) :-
concat_body_with_comma(B, BB).
concat_body_with_comma([A], A).
plot_body_prefix -->
newline, spaces(_), if_, !.
plot_body_prefix -->
if_, newline_or_nothing, spaces(_).
plot_body(Body, Map1, MapN) -->
plot_body_prefix, !,
plot_body_clause_list(ChartVar, 0, UsedVarList, PlotCommandList, CondList, Map1, MapN),
{
% print_message(informational, "In plot body UsedVarList: ~w \n\n PlotCommandList: ~w \n\nCondList ~w"-[UsedVarList, PlotCommandList, CondList]),
atomics_to_string(PlotCommandList, '\n', PlotCommandListStr),
pad_name_var(_Names, UsedVarList, ParamList, MapN),
% print_message(informational, "ParamList: ~w PlotCommandListStr ~w"-[ParamList,PlotCommandListStr]),
% term_string(PlotTerm, S),
ChartAssignCommand = (ChartVar = plot_command(r_execute(ParamList,PlotCommandListStr,_))),
append(CondList, [ChartAssignCommand], TermList),
concat_body_with_comma(TermList, Body)
% print_message(informational, "In plot body Body: ~w"-[Body])
}.
plot_body_clause_list(ChartVar, DataFrameCount, UsedVarList, PlotCommandList, CondList, Map1, MapN) -->
plot_body_clause(ChartVar, UsedVarHead, PlotCommandHead, CondHead, DataFrameCount, Map1, Map2),
{NextCount is DataFrameCount + 1},
newline, spaces(_), operator(_Op), spaces(_), plot_body_clause_list(ChartVar, NextCount, UsedVarTail, PlotCommandTail, CondTail, Map2, MapN),
{
append(UsedVarHead, UsedVarTail, UsedVarList),
append(PlotCommandHead, PlotCommandTail, PlotCommandList),
append(CondHead, CondTail, CondList)
}.
plot_body_clause_list(ChartVar, DataFrameCount, UsedVarList, PlotCommandList, CondList, Map1, MapN) --> plot_body_clause(ChartVar, UsedVarList, PlotCommandList, CondList, DataFrameCount, Map1, MapN).
% plot_body_clause/5
% used to match normal LE conditions or special plot conditions
plot_body_clause(_, [], [], [Cond], _Count, Map1, MapN) --> condition(Cond, _Ind, Map1, MapN).
plot_body_clause(ChartVar, UsedVarList, [PlotCommand], [], _Count, Map1, MapN) --> chart(ChartVar, UsedVarList, PlotCommand, Map1, MapN).
plot_body_clause(_, [], [PlotCommand], [], _Count, Map1, MapN) --> straightLine(PlotCommand, Map1, MapN).
plot_body_clause(_, [], [PlotCommand], [], _Count, Map1, MapN) --> legend(PlotCommand, Map1, MapN).
plot_body_clause(_, [], [PlotCommand], [DataFrameCommand], Count, Map1, MapN) --> line(DataFrameCommand, PlotCommand, Count, Map1, MapN).
plot_body_clause(_, [], [PlotCommand], [DataFrameCommand], Count, Map1, MapN) --> points(DataFrameCommand, PlotCommand, Count, Map1, MapN).
plot_body_clause(_, [], [PlotCommand], [DataFrameCommand], Count, Map1, MapN) --> verticalLines(DataFrameCommand, PlotCommand, Count, Map1, MapN).
chart(ChartVar, UsedVarList, Command, Map1, MapN) -->
variable_invocation([has], _Name, ChartVar, Map1, MapN), spaces(_),
[has], spaces(_), chart_with_list(UsedVarList, Arguments, Map1, MapN), !,
{
% print_message(informational, "in chart Map1 ~w Arguments ~w"-[Map1, Arguments]),
atomic_list_concat(Arguments, ',', Atom),
format(string(Command), 'plot(NULL, ~w)', [Atom])
}.
legend(Command, Map1, MapN) -->
variable_invocation([displays], _Name, _Var, Map1, MapN), spaces(_), displays_, legend_, [at], spaces(_), [Position], spaces(_), legend_with_list(Arguments), !,
{
atom_string(Position, PositionAtom),
atomic_list_concat(Arguments, ',', Atom),
format(string(Command), 'legend("~w",~w)', [PositionAtom, Atom])
}.
straightLine(Command, Map1, MapN) -->
variable_invocation([displays], _Name, _Var, Map1, MapN), spaces(_), displays_, a_straight_line_, line_with_list(Arguments), !,
{atomic_list_concat(Arguments, ',', Atom), format(string(Command), 'abline(~w)', [Atom]) }.
verticalLines(DataFrameCommand, PlotCommand, Count, Map1, Map2) -->
variable_invocation([displays], _Name, _Var, Map1, Map2), spaces(_), displays_, extract_names(NameX, NameY),
from_, literal_(Map2, MapN, Cond),
as_vertical_lines_, line_with_list(Arguments), !,
{
atomic_concat('verticalLines', Count, DataFrameName),
make_data_frame_command(Cond, MapN, DataFrameName, [NameX, NameY], DataFrameCommand),
atomic_list_concat(Arguments, ',', Atom), format(string(PlotCommand), 'points(~w$~w,~w$~w,type="h",~w)', [DataFrameName, NameX, DataFrameName, NameY, Atom])
}.
points(DataFrameCommand, PlotCommand, Count, Map1, Map2) -->
variable_invocation([displays], _Name, _Var, Map1, Map2), spaces(_), displays_, extract_names(NameX, NameY),
from_, literal_(Map2, MapN, Cond),
as_points_, line_with_list(Arguments), !,
{
atomic_concat('points', Count, DataFrameName),
make_data_frame_command(Cond, MapN, DataFrameName, [NameX, NameY], DataFrameCommand),
atomic_list_concat(Arguments, ',', Atom), format(string(PlotCommand), 'points(~w$~w,~w$~w,~w)',
[DataFrameName, NameX, DataFrameName, NameY, Atom])
}.
line(DataFrameCommand, PlotCommand, Count, Map1, Map2) -->
variable_invocation([displays], _Name, _Var, Map1, Map2), spaces(_), displays_, extract_names(NameX, NameY),
from_, literal_(Map2, MapN, Cond), % the variables defined are local to the condition
as_a_line_, line_with_list(Arguments),
{
atomic_concat('line', Count, DataFrameName),
make_data_frame_command(Cond, MapN, DataFrameName, [NameX, NameY], DataFrameCommand),
% the data frame here has to be sorted using order() before plotting as a line
% as the data collected using r_data_frame are not ordered
atomic_list_concat(Arguments, ',', Atom), format(string(PlotCommand), '~w <- ~w[order(~w$~w),]\n lines(~w$~w,~w$~w,~w)',
[DataFrameName, DataFrameName, DataFrameName, NameX, DataFrameName, NameX, DataFrameName, NameY, Atom])
}.
extract_names(NameX, NameY) -->
variable_invocation_name_extraction([and], NameX), [and], variable_invocation_name_extraction([], NameY).
% {print_message(informational, "NameX ~w NameY ~w"-[NameX, NameY])}.
make_data_frame_command(Cond, MapN, DataFrameName, Names, DataFrameCommand) :-
pad_name_var(Names, _VarList, ParamList, MapN),
DataFrameCommand = r_data_frame(DataFrameName, ParamList, Cond).
pad_name_var([], [], [], _MapN).
pad_name_var([Name | XT], [Var | YT], [Name=Var | ZT], MapN) :-
consult_map(Var, Name, MapN, MapN),
pad_name_var(XT, YT, ZT, MapN).
% chart_with_list used to match different arguments, such as title, xlab, ylab, xlim, ylim, etc.
chart_with_list(VarList, [Argument|ArgumentRest], Map1, MapN) -->
chart_with(VarHead, Argument, Map1, MapN), spaces_or_newlines(_), [and], spaces(_), chart_with_list(VarTail, ArgumentRest, Map1, MapN),
{append(VarHead, VarTail, VarList)}.
chart_with_list(VarList, [Argument], Map1, MapN) --> chart_with(VarList, Argument, Map1, MapN).
% with is optional for line
line_with_list(Arguments) --> spaces_or_newlines(_), [with], spaces(_), line_with_tail(Arguments).
line_with_list([]) --> [].
line_with_tail([H|T]) --> line_with(H), spaces_or_newlines(_), [and], spaces(_), line_with_tail(T).
line_with_tail([H]) --> line_with(H).
% legend must have one with clause
legend_with_list(Arguments) --> spaces_or_newlines(_), [with], spaces(_), legend_with_tail(Arguments).
legend_with_tail([H|T]) --> legend_with(H), spaces_or_newlines(_), [and], spaces(_), legend_with_tail(T).
legend_with_tail([H]) --> legend_with(H).
listOfStringToSingleString(SList, Result) :-
maplist(wrap_with_quotes, SList, SWrappedList),
atomic_list_concat(SWrappedList, ',', Result).
wrap_with_quotes(In, Out) :-
number(In), format(string(Out), '~w', [In]).
wrap_with_quotes(In, Out) :-
not(number(In)), format(string(Out), '"~w"', [In]).
legend_with(Argument) --> a_colour_of_, ['['], extract_list([']'], List, [], []), [']'], spaces(_),
{listOfStringToSingleString(List, ListStr), format(string(Argument), 'col=c(~w)', [ListStr]) }.
legend_with(Argument) --> a_plotting_character_of_, ['['], extract_list([']'], List, [], []), [']'], spaces(_),
{listOfStringToSingleString(List, ListStr), format(string(Argument), 'pch=c(~w)', [ListStr]) }.
legend_with(Argument) --> a_character_expansion_factor_of_, [X], spaces(_),
{number(X), term_to_atom(cex=X, Argument) }.
legend_with(Argument) --> a_text_of_, ['['], extract_list([']'], List, [], []), [']'], spaces(_),
{listOfStringToSingleString(List, ListStr),
%print_message(informational, 'text list=~w'-[List]),
format(string(Argument), 'legend=c(~w)', [ListStr]) }.
legend_with(Argument) --> a_line_type_of_, ['['], extract_list([']'], List, [], []), [']'], spaces(_),
{listOfStringToSingleString(List, ListStr),
%print_message(informational, 'line type list=~w'-[List]),
format(string(Argument), 'lty=c(~w)', [ListStr]) }.
legend_with(Argument) --> a_box_type_of_, [X], spaces(_),
{atom_string(X, XString), term_to_atom(bty=XString, Argument) }.
line_with(Argument) --> a_colour_of_, [X], spaces(_),
{atom_string(X, XAtom), term_to_atom(col=XAtom, Argument) }.
line_with(Argument) --> a_height_of_, [X], spaces(_),
{number(X), term_to_atom(h=X, Argument) }.
line_with(Argument) --> a_width_of_, [X], spaces(_),
{number(X), term_to_atom(lwd=X, Argument) }.
line_with(Argument) --> a_plotting_character_of_, [X], spaces(_),
{number(X), term_to_atom(pch=X, Argument)}.
line_with(Argument) --> a_character_expansion_factor_of_, [X], spaces(_),
{number(X), term_to_atom(cex=X, Argument)}.
chart_with([UsedVar], Argument, Map1, MapN) -->
variable_invocation([as], Name, UsedVar, Map1, MapN), as_title_,
{format(string(Argument), 'main=~w', [Name])}.
chart_with([], Argument, _, _) --> extract_constant([], NameWords), as_title_, !,
{name_as_atom(NameWords, Title), term_to_atom(main=Title, Argument)}.
chart_with([], Argument, _, _) --> extract_constant([], NameWords), as_x_axis_label_, !,
{name_as_atom(NameWords, Label), term_to_atom(xlab=Label, Argument) }.
chart_with([], Argument, _, _) --> extract_constant([], NameWords), as_y_axis_label_, !,
{name_as_atom(NameWords, Label), term_to_atom(ylab=Label, Argument) }.
chart_with([], Argument, _, _) --> x_axis_limits_(X, Y), !,
{term_to_atom(xlim=c(X,Y), Argument)}.
chart_with([], Argument, _, _) --> y_axis_limits_(X, Y), !,
{term_to_atom(ylim=c(X,Y), Argument)}.
displays_ --> [displays], spaces(_).
from_ --> spaces_or_newlines(_), [from], spaces(_).
as_a_line_ --> spaces_or_newlines(_), [as], spaces(_), [a], spaces(_), [line], spaces(_).
as_points_ --> spaces_or_newlines(_), [as], spaces(_), [points], spaces(_).
a_straight_line_ --> [a], spaces(_), [straight], spaces(_), [line], spaces(_).
as_vertical_lines_ --> spaces_or_newlines(_), [as], spaces(_), [vertical], spaces(_), [lines], spaces(_).
legend_ --> [legend], spaces(_).
a_colour_of_ --> [a], spaces(_), [color], spaces(_), [of], spaces(_).
a_colour_of_ --> [a], spaces(_), [colour], spaces(_), [of], spaces(_).
a_height_of_ --> [a], spaces(_), [height], spaces(_), [of], spaces(_).
a_width_of_ --> [a], spaces(_), [width], spaces(_), [of], spaces(_).
a_plotting_character_of_ --> [a], spaces(_), [plotting], spaces(_), [character], spaces(_), [of], spaces(_).
a_character_expansion_factor_of_ --> [a], spaces(_), [character], spaces(_), [expansion], spaces(_), [factor], spaces(_), [of], spaces(_).
a_text_of_ --> [a], spaces(_), [text], spaces(_), [of], spaces(_).
a_line_type_of_ --> [a], spaces(_), [line], spaces(_), [type], spaces(_), [of], spaces(_).
a_box_type_of_ --> [a], spaces(_), [box], spaces(_), [type], spaces(_), [of], spaces(_).
% (holds_at(_149428,_149434) if
% (happens_at(_150138,_150144),
% initiates_at(_150138,_149428,_150144)),
% _150144 before _149434,
% not ((terminates_at(_152720,_149428,_152732),_150144 before _152732),_152732 before _149434))
% it must not be true that
% statement/1 or /3
statement(Statement) -->
it_must_not_be_true_that_, % spaces_or_newlines(_),
newline, spaces(Ind), !, conditions(Ind, [], _MapN, Conditions), spaces_or_newlines(_), period,
{(Conditions = [] -> Statement = [if(empty, true)];
(Statement = [if(empty, Conditions)]))}, !.
% it becomes the case that
% fluent
% when
% event
% if
% statement/1 or /3
statement(Statement) -->
it_becomes_the_case_that_, spaces_or_newlines(_),
literal_([], Map1, holds(Fluent, _)), spaces_or_newlines(_),
when_, spaces_or_newlines(_),
literal_(Map1, Map2, happens(Event, T)), spaces_or_newlines(_),
body_(Body, [map(T, '_change_time')|Map2],_), period,
{(Body = [] -> Statement = [if(initiates(Event, Fluent, T), true)];
(Statement = [if(initiates(Event, Fluent, T), Body)]))}, !.
% it becomes not the case that
% fluent
% when
% event
% if
statement(Statement) -->
it_becomes_not_the_case_that_, spaces_or_newlines(_),
literal_([], Map1, holds(Fluent, _)), spaces_or_newlines(_),
when_, spaces_or_newlines(_),
literal_(Map1, Map2, happens(Event, T)), spaces_or_newlines(_),
body_(Body, [map(T, '_change_time')|Map2],_), period,
{(Body = [] -> Statement = [if(terminates(Event, Fluent, T), true)];
(Statement = [if(terminates(Event, Fluent, T), Body)] %, print_message(informational, "~w"-Statement)
))}, !.
% it is illegal that
% event
% if ...
statement(Statement) -->
it_is_illegal_that_, spaces_or_newlines(_),
literal_([], Map1, happens(Event, T)), body_(Body, Map1, _), period,
{(Body = [] -> Statement = [if(it_is_illegal(Event, T), true)];
Statement = [if(it_is_illegal(Event, T), Body)])},!.
% it is unknown whether
statement(Statement) -->
it_is_unknown_whether_, spaces_or_newlines(_),
literal_([], Map1, Abducible), body_(Body, Map1, _), period,
{(Body = [] -> Statement = [abducible(Abducible, true)];
Statement = [abducible(Abducible, Body)])},!.
% a fact or a rule
statement(Statement) --> currentLine(L),
literal_([], Map1, Head), body_(Body, Map1, _), period,
{(Body = [] -> Statement = [if(L, Head, true)]; Statement = [if(L, Head, Body)])}.
% error
statement(_, Rest, _) :-
asserterror('LE error found around this statement: ', Rest), fail.
list_of_facts([F|R1]) --> literal_([], _,F), rest_list_of_facts(R1).
rest_list_of_facts(L1) --> comma, spaces_or_newlines(_), list_of_facts(L1).
rest_list_of_facts([]) --> [].
% assumptions_/3 or /5
assumptions_([A|R]) -->
spaces_or_newlines(_), rule_([], _, A), % {print_message(informational, "rule in scenario: ~w"-[A])},
assumptions_(R).% {print_message(informational, "rest of rules in scenario: ~w"-[R])}.
assumptions_([]) --> %{print_message(informational, "no more rules in scenario"-[])},
spaces_or_newlines(_).
rule_(InMap, InMap, Rule) -->
it_is_unknown_whether_, spaces_or_newlines(_),
literal_([], Map1, Abducible), body_(Body, Map1, _), period,
{(Body = [] -> Rule = (abducible(Abducible, true):-true); Rule = (abducible(Abducible, Body):-true))},!.
rule_(InMap, OutMap, Rule) -->
literal_(InMap, Map1, Head), body_(Body, Map1, OutMap), period,
%spaces(Ind), condition(Head, Ind, InMap, Map1), body_(Body, Map1, OutMap), period,
{(Body = [] -> Rule = (Head :-true); Rule = (Head :- Body))}.
rule_(M, M, _, Rest, _) :-
asserterror('LE error found in an assumption, near to ', Rest), fail.
% no prolog inside LE!
%statement([Fact]) -->
% spaces(_), prolog_literal_(Fact, [], _), spaces_or_newlines(_), period.
% body/3 or /5
body_([], Map, Map) --> spaces_or_newlines(_).
body_(Conditions, Map1, MapN) -->
newline, spaces(Ind), if_, !, conditions(Ind, Map1, MapN, Conditions), spaces_or_newlines(_).
body_(Conditions, Map1, MapN) -->
if_, newline_or_nothing, spaces(Ind), conditions(Ind, Map1, MapN, Conditions), spaces_or_newlines(_).
newline_or_nothing --> newline.
newline_or_nothing --> [].
% literal_/3 or /5
% literal_ reads a list of words until it finds one of these: ['\n', if, '.']
% it then tries to match those words against a template in memory (see dict/3 predicate).
% The output is then contigent to the type of literal according to the declarations.
literal_(Map1, MapN, FinalLiteral) --> % { print_message(informational, 'at time, literal') },
at_time(T, Map1, Map2), comma, possible_instance(PossibleTemplate),
{ PossibleTemplate \=[], % cant be empty
match_template(PossibleTemplate, Map2, MapN, Literal),
(fluents(Fluents) -> true; Fluents = []),
(events(Events) -> true; Events = []),
(lists:member(Literal, Events) -> FinalLiteral = happens(Literal, T)
; (lists:member(Literal, Fluents) -> FinalLiteral = holds(Literal, T)
; FinalLiteral = Literal))}, !. % by default (including builtins) they are timeless!
literal_(Map1, MapN, FinalLiteral) --> % { print_message(informational, 'literal, at time') },
possible_instance(PossibleTemplate), comma, at_time(T, Map1, Map2),
{ PossibleTemplate \=[], % cant be empty
match_template(PossibleTemplate, Map2, MapN, Literal),
(fluents(Fluents) -> true; Fluents = []),
(events(Events) -> true; Events = []),
(lists:member(Literal, Events) -> FinalLiteral = happens(Literal, T)
; (lists:member(Literal, Fluents) -> FinalLiteral = holds(Literal, T)
; FinalLiteral = Literal))}, !. % by default (including builtins) they are timeless!
literal_(Map1, MapN, FinalLiteral) -->
possible_instance(PossibleTemplate), %{ print_message(informational, "literal_: ~w"-[PossibleTemplate]) },
{ PossibleTemplate \=[], % cant be empty
match_template(PossibleTemplate, Map1, MapN, Literal),
(fluents(Fluents) -> true; Fluents = []),
(events(Events) -> true; Events = []),
(consult_map(Time, '_change_time', Map1, _MapF) -> T=Time; true),
(lists:member(Literal, Events) -> FinalLiteral = happens(Literal, T)
; (lists:member(Literal, Fluents) -> FinalLiteral = holds(Literal, T)
; (FinalLiteral = Literal)))
%print_message(informational, "~w with ~w"-[FinalLiteral, MapF])
}, !. % by default (including builtins) they are timeless!
% rewritten to use in swish. Fixed! It was a name clash. Apparently "literal" is used somewhere else
%literal_(Map1, MapN, Literal, In, Out) :- print_message(informational, ' inside a literal'),
% possible_instance(PossibleTemplate, In, Out), print_message(informational, PossibleTemplate),
% match_template(PossibleTemplate, Map1, MapN, Literal).
% error clause
literal_(M, M, _, Rest, _) :-
asserterror('LE error found in a literal ', Rest), fail.
% conditions/4 or /6
conditions(Ind0, Map1, MapN, Conds) -->
list_of_conds_with_ind(Ind0, Map1, MapN, Errors, ListConds),
{Errors=[] -> ri(Conds, ListConds); (assert_error_os(Errors), fail)}. % preempty validation of errors
conditions(_, Map, Map, _, Rest, _) :-
asserterror('LE indentation error ', Rest), fail.
% list_of_conds_with_ind/5
% list_of_conds_with_ind(+InitialInd, +InMap, -OutMap, -Errors, -ListOfConds)
list_of_conds_with_ind(Ind0, Map1, MapN, [], [Cond|Conditions]) -->
condition(Cond, Ind0, Map1, Map2),
more_conds(Ind0, Ind0,_, Map2, MapN, Conditions).
list_of_conds_with_ind(_, M, M, [error('Error in condition at', LineNumber, Tokens)], [], Rest, _) :-
once( nth1(N,Rest,newline(NextLine)) ), LineNumber is NextLine-2,
RelevantN is N-1,
length(Relevant,RelevantN), append(Relevant,_,Rest),
findall(Token, (member(T,Relevant), (T=newline(_) -> Token='\n' ; Token=T)), Tokens).
more_conds(Ind0, _, Ind3, Map1, MapN, [ind(Ind2), Op, Cond2|RestMapped]) -->
newline, spaces(Ind2), {Ind0 =< Ind2}, % if the new indentation is deeper, it goes on as before.
operator(Op), condition(Cond2, Ind2, Map1, Map2),
%{print_message(informational, "~w"-[Conditions])}, !,
more_conds(Ind0, Ind2, Ind3, Map2, MapN, RestMapped).