1 % (c) 2025-2025 Lehrstuhl fuer Softwaretechnik und Programmiersprachen,
2 % Heinrich Heine Universitaet Duesseldorf
3 % This software is licenced under EPL 1.0 (http://www.eclipse.org/org/documents/epl-v10.html)
4
5 :- module(clingo_interface,[run_clingo/2, run_clingo/5,
6 reset_clingo_interface/0,
7 clingo_generated_id/4,
8 register_clingo_generated_id/4]).
9
10 :- use_module(probsrc(module_information),[module_info/2]).
11 :- module_info(group,b2asp).
12 :- module_info(description,'Running clingo on a file and parsing model output.').
13
14 :- use_module(library(lists)).
15 :- use_module(library(file_systems),[file_exists/1]).
16 :- use_module(library(process)).
17
18 :- if(current_module(error_manager)).
19 :- use_module(probsrc(error_manager)).
20 :- use_module(probsrc(tools_strings),[ajoin/2]).
21 :- use_module(probsrc(debug)).
22 :- use_module(probsrc(preferences)).
23 :- use_module(probsrc(system_call),[safe_process_create/3]).
24 get_clingo_path(Path) :- get_preference(path_to_clingo,Path).
25 add_b2asp_error(Msg,Args) :- add_error(b2asp,Msg,Args).
26 add_b2asp_warning(Msg,Args) :- add_warning(b2asp,Msg,Args).
27 :- else.
28 get_clingo_path('C:/Users/hhuri/Desktop/stage/clingo-5.4.0-win64/clingo.exe').
29 get_clingo_path('/opt/homebrew/bin/clingo').
30 add_b2asp_error(Msg,Args) :-
31 write(user_error,Msg), write(user_error,Args), nl(user_error).
32 add_b2asp_warning(Msg,Args) :-
33 add_b2asp_error(Msg,Args).
34 debug_mode(on).
35 debug_format(_,FS,A) :- format(user_output,FS,A).
36 safe_process_create(Cmd,Args,Opts) :- process_create(Cmd,Args,Opts).
37 :- endif.
38
39 run_clingo(File,Result) :- run_clingo(File,1,_,Result,_).
40 run_clingo(File,MaxNrModels,WT,Result,Exhaustive) :-
41 statistics(walltime,[Start,_]),
42 (debug_mode(on) -> DOpt=['-V'] ; DOpt=[]),
43 (MaxNrModels<2 -> ModelsOpt='--models=1' % so that code works without ajoin
44 ; ajoin(['--models=',MaxNrModels],ModelsOpt)),
45 OtherOptions = [ModelsOpt|DOpt] , % =0 outputs all models
46 debug_format(19,' Running CLINGO on ~w (options=~w)~n',[File,OtherOptions]),flush_output,
47 Options = [process(Process),stdout(pipe(JStdout,[encoding(utf8)])),
48 stderr(pipe(JStderr,[encoding(utf8)]))],
49 (get_clingo_path(Clingo), file_exists(Clingo)-> true
50 ; get_clingo_path(Clingo) -> add_b2asp_error('Cannot find Clingo binary at (be sure to set path_to_clingo preference to point to clingo binary): ',Clingo),fail
51 ; add_b2asp_error('Cannot find Clingo binary (be sure to set path_to_clingo preference to point to clingo binary)',''),fail
52 ),
53 safe_process_create(Clingo, [File|OtherOptions], Options),
54 read_all(JStdout,Clingo,stdout,OutLines), % read before process_wait; avoid blocking clingo
55 read_all(JStderr,Clingo,stderr,ErrLines),
56 process_wait(Process,Exit),
57 % above almost corresponds to: system_call_with_options(Clingo,[File|OtherOptions],[],OutLines,ErrLines,ExitCode)
58 % except that here we do not call append/2 on OutLines and ErrLines
59 statistics(walltime,[Stop,_]), WT is Stop-Start,
60 format(' CLINGO walltime: ~w ms, ~w~n',[WT,Exit]),flush_output,
61 debug_format(19,'--- CLINGO OUTPUT ----~n',[]),flush_output,
62 process_clingo_output(OutLines,Models),
63 if((Exit=exit(Code),
64 % ErrLines = [], % clingo write debug info on stderr (parsed program, rewritten program)
65 translate_clingo_exit_code(Code,Models,Result,Exhaustive)
66 ),
67 (debug_format(19,'Clingo exit code = ~w -> ~w (~w)~n',[Code,Result,Exhaustive]),
68 show_stderr(ErrLines)),
69 (format('Unrecognised exit code: ~w~n',[Exit]),
70 show_stderr(ErrLines),
71 Result=no_solution_found(Exit))
72 ).
73
74 show_stderr([]) :- !.
75 show_stderr(ErrLines) :-
76 append(ErrLines,ErrText),
77 (ErrText = [] -> true
78 ; format('--- CLINGO STDERR ----~n~s~n',[ErrText])).
79
80 % see https://github.com/potassco/clasp/issues/42#issuecomment-459981038%3E
81 translate_clingo_exit_code(0,_,no_solution_found('E_UNKNOWN'),non_exhaustive).
82 translate_clingo_exit_code(1,_,no_solution_found('E_INTERRUPT'),non_exhaustive).
83 translate_clingo_exit_code(33,_,no_solution_found('E_MEMORY'),non_exhaustive).
84 translate_clingo_exit_code(65,_,no_solution_found('E_ERROR'),non_exhaustive). % is for syntax error and unsafe vars
85 translate_clingo_exit_code(128,_,no_solution_found('E_NO_RUN'),non_exhaustive).
86 translate_clingo_exit_code(20,_,contradiction_found,exhaustive). % UNSATISFIABLE (E_EXHAUST)
87 translate_clingo_exit_code(10,Sols,solution(Sol),non_exhaustive) :-
88 get_sol(Sols,Sol). % E_SAT = 10, /*!< At least one model was found.
89 translate_clingo_exit_code(30,Sols,solution(Sol),exhaustive) :-
90 get_sol(Sols,Sol). %all_solutions_found (E_EXHAUST)
91
92 get_sol([Sol|T],R) :- !, member(R,[Sol|T]).
93 get_sol(L,R) :- add_b2asp_error('Unexpected clingo solution: ',L), R=[].
94
95 %get_first_sol([Sol|_],R) :- !, R=Sol.
96 %get_first_sol(L,R) :- add_b2asp_error('Unexpected clingo solution: ',L), R=[].
97
98 % process clingo output stream and extract answers (stable models)
99 process_clingo_output([],[]).
100 process_clingo_output([[0'\n]|T],Models) :- !, process_clingo_output(T,Models).
101 process_clingo_output([Line|T],Models) :- debug_format(19,'>>> ~s~n',[Line]),
102 clingo_answer_line(Nr,Line,[]), !,
103 process_clingo_model_line(T,Nr,Models).
104 process_clingo_output([_|T],Models) :- process_clingo_output(T,Models).
105
106 process_clingo_model_line([[0'\n]|T],Nr,Models) :- !, process_clingo_model_line(T,Nr,Models).
107 process_clingo_model_line([ModelLine|T],Nr,[BSolution|TM]) :- clingo_model(Model,ModelLine,[]), !,
108 debug_format(19,'>>> ~s~n',[ModelLine]),
109 length(Model,Len),
110 format('Parsed clingo model ~w with ~w relevant atoms~n',[Nr,Len]),
111 sort(Model,SModel), % TODO: extract solution for registered identifiers
112 keyclumped(SModel,Groups),
113 %write(Groups),nl,
114 translate_clingo_model_to_bindings(Groups,BSolution),
115 %write(BSolution),nl,
116 process_clingo_output(T,TM).
117 process_clingo_model_line(T,Nr,Models) :-
118 add_b2asp_error('Could not parse clingo model answer: ',Nr),
119 process_clingo_output(T,Models).
120
121 % TRANSLATING clingo model atoms back to B values
122 % -----------------------------------------------
123
124 translate_clingo_model_to_bindings(Model,Bindings) :-
125 findall(expected(Pred,Kind,BaseType,BID),clingo_generated_id(Pred,Kind,BaseType,BID),ExpectedPreds),
126 sort(ExpectedPreds,SExpectedPreds),
127 translate_clingo_model_to_bindings3(Model,SExpectedPreds,Bindings).
128
129 translate_clingo_model_to_bindings3([],[],Sol) :- !, Sol=[].
130 translate_clingo_model_to_bindings3([Pred-ModelArgs|TM],[expected(Pred,Kind,BaseType,BID)|ET],
131 [bind(BID,BVal)|BT]) :- !,
132 translate_clingo_value(Kind,BaseType,ModelArgs,BVal),
133 translate_clingo_model_to_bindings3(TM,ET,BT).
134 translate_clingo_model_to_bindings3(Model,[expected(Pred,Kind,_BaseType,BID)|ET],
135 [bind(BID,BVal)|BT]) :- !,
136 (Kind=set
137 -> debug_format(19,'Setting set to empty: ~w (~w)~n',[Pred,BID]),
138 BVal=[] % the clingo identifier represents a set, we have no facts meaning the set is empty
139 ; add_b2asp_error('No value for clingo scalar in model: ',Pred),
140 BVal=term(undefined)
141 ),
142 translate_clingo_model_to_bindings3(Model,ET,BT).
143
144 % translate a solution for a clingo identifier back to a B value
145 translate_clingo_value(scalar,BaseType,[[ClingoVal]],BVal) :- !,
146 translate_clingo_scalar(BaseType,ClingoVal,BVal).
147 translate_clingo_value(scalar,BaseType,[Sol1|T],BVal) :- !,
148 add_b2asp_warning('Unexpected multiple solutions for clingo scalar: ',[Sol1|T]),
149 translate_clingo_scalar(BaseType,Sol1,BVal).
150 translate_clingo_value(set,BaseType,Sols,BValSetAsList) :- !,
151 maplist(translate_clingo_arg(BaseType),Sols,BValSetAsList).
152 translate_clingo_value(Kind,_,_,_) :-
153 add_b2asp_error('Unexpected Kind for Clingo ID: ',Kind), fail.
154
155 translate_clingo_arg(BaseType,[ClingoVal],BVal) :- translate_clingo_scalar(BaseType,ClingoVal,BVal).
156 % translate_clingo_arg(BaseType,[ClingoVal1,ClingoVal2],BVal) :- ... convert to B pairs
157
158 % translate a solution for a clingo scalar back to a B value
159 translate_clingo_scalar(integer,Nr,BV) :- integer(Nr),!, BV=int(Nr).
160 translate_clingo_scalar(interval(_,_),Nr,BV) :- integer(Nr),!, BV=int(Nr).
161 translate_clingo_scalar(boolean,pred_false,BV) :- !, BV=pred_false.
162 translate_clingo_scalar(boolean,pred_true,BV) :- !, BV=pred_true.
163 translate_clingo_scalar(couple(TA,TB),(CA,CB),(BA,BB)) :- !,
164 translate_clingo_scalar(TA,CA,BA),
165 translate_clingo_scalar(TB,CB,BB).
166 %translate_clingo_scalar(global(_GS),ID,FDVAL) :- atom(ID),!, lookup_global_constant(ID,FDVAL).
167 translate_clingo_scalar(global(GS),Nr,FDVAL) :- integer(Nr),!, FDVAL=fd(Nr,GS).
168 translate_clingo_scalar(T,V,term(V)) :- add_b2asp_warning('Unknown clingo scalar: ',T:V).
169
170 % PARSING CODE for clingo OUTPUT
171 % ---------------------
172 % detect line like Answer: 1 (Time: 0.003s)
173 clingo_answer_line(Nr) --> "Answer: ",clingo_number(Nr), anything.
174
175 clingo_number(Nr) --> digit(X), !, answer_nr_rest(R), {number_codes(Nr,[X|R])}.
176 clingo_number(MinusNr) --> "-", digit(X), !, answer_nr_rest(R), {number_codes(Nr,[X|R]),MinusNr is -Nr}.
177 answer_nr_rest([X|T]) --> digit(X), !, answer_nr_rest(T).
178 answer_nr_rest([]) --> "".
179
180 anything --> [_],!,anything.
181 anything --> "".
182
183 % a clingo identifier (TODO check that this conforms to clingo syntax)
184 clingo_identifier(ID) --> letter(H), !, id2(T), {atom_codes(ID,[H|T])}.
185 id2([H|T]) --> letter(H),!, id2(T).
186 id2([H|T]) --> digit(H),!, id2(T).
187 id2([95|T]) --> "_",!, id2(T).
188 id2([]) --> "".
189
190 % a single stable model generated by clingo, a list of ground atoms separated by single whitespace
191 clingo_model(M) --> " ", !, clingo_model(M).
192 clingo_model(Model) --> clingo_atom(Pred,Args),!,
193 %{format(user_output,' model atom --> ~w ~w~n',[Pred,Args])},
194 {(clingo_generated_id(Pred,_,_,_) -> Model = [Pred-Args|T] ; Model = T)},
195 clingo_model(T).
196 clingo_model([]) --> "".
197 %clingo_model(In,_Out) :- format(user_error,'Cannot parse: ~s~n',[In]),fail.
198
199 % a single clingo atom either a ground predicate p(2), p((2,3)), or p(2,3) or a proposition p
200 clingo_atom(Pred,Args) --> clingo_identifier(Pred), clingo_opt_args(Args).
201 clingo_opt_args(Args) --> "(", !, clingo_args(Args),")".
202 clingo_opt_args([]) --> "". % for propositions without arguments
203 clingo_args([A|T]) --> clingo_constant(A),!, clingo_args2(T).
204 clingo_args([(A,B)|T]) --> clingo_pair(A,B),!, clingo_args2(T).
205
206 clingo_constant(A) --> clingo_number(A).
207 clingo_constant(A) --> clingo_identifier(A).
208
209 clingo_args2(T) --> ",", clingo_args(T).
210 clingo_args2([]) --> "".
211
212 clingo_pair(A,B) --> "(", clingo_cst_or_pair(A),!, ",", clingo_cst_or_pair(B),")".
213
214 clingo_cst_or_pair(A) --> clingo_constant(A),!.
215 clingo_cst_or_pair((A,B)) --> "(", clingo_cst_or_pair(A),",", clingo_cst_or_pair(B),")".
216
217 letter(X) --> [X], {letter(X)}.
218 digit(X) --> [X], {digit(X)}.
219 letter(X) :- (X >= 97, X =< 122) ; (X >= 65, X=< 90). % underscore = 95, minus = 45
220 digit(X) :- X >= 48, X =< 57.
221
222 % ---------
223
224 % read all characters from a stream
225 read_all(S,Command,Pipe,Lines) :-
226 call_cleanup(read_all1(S,Command,Pipe,Lines),
227 close(S)).
228 read_all1(S,Command,Pipe,Lines) :-
229 catch(read_all2(S,Lines), error(_,E), ( % E could be system_error('SPIO_E_ENCODING_INVALID')
230 ajoin(['Error reading ',Pipe,' for "',Command,'" due to exception: '],Msg),
231 add_error(system_call,Msg,E),
232 fail
233 )).
234 read_all2(S,Text) :-
235 read_line(S,Line),
236 ( Line==end_of_file -> Text=[[]]
237 ;
238 Text = [Line, [0'\n] | Rest],
239 read_all2(S,Rest)).
240
241 % ------------
242
243
244 :- dynamic clingo_generated_id/4.
245
246 % register that Clingo predicate Pred represents a solution for a B variable ID
247 % Kind is set or scalar, BaseType is B type term
248 register_clingo_generated_id(Pred,Kind,BaseType,ID) :-
249 assertz(clingo_generated_id(Pred,Kind,BaseType,ID)).
250
251 reset_clingo_interface :-
252 retractall(clingo_generated_id(_,_,_,_)).