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