1 % (c) 2012-2026 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(b2sat, [init_satsolver/0, bt_sat/2,
6 solve_predicate_with_satsolver_free/2,
7 solve_predicate_with_satsolver_free/4,
8 solve_predicate_with_satsolver_in_state/4,
9 solve_predicate_with_satsolver/2,
10 generate_cnf_vig_graph/1, cnf_vig_graph_available/0]).
11
12 :- use_module('../../src/module_information.pl').
13 :- module_info(group,satsolver).
14 :- module_info(description,'This is the interface for ProB to use various SAT solvers (glucose, Z3)').
15
16 :- use_module(probsrc(tools),[start_ms_timer/1, stop_ms_timer_with_msg/2,
17 stop_ms_timer_with_debug_msg/2, get_elapsed_walltime/2]).
18 :- use_module(probsrc(debug),[debug_format/3]).
19 :- use_module(probsrc(error_manager),[add_error/3, add_internal_error/2]).
20 :- use_module(b_to_cnf).
21
22 :- use_module(library(lists), [maplist/2,maplist/3,exclude/3]).
23
24 :- use_module(satsolver). % Glucose API
25
26
27 :- use_module(probsrc(bsyntaxtree), [find_typed_identifier_uses/2, def_get_texpr_id/2]).
28 :- use_module(probsrc(solver_interface), [set_up_typed_localstate_for_pred/4]).
29 :- use_module(probsrc(b_compiler),[b_optimize/6]).
30
31 % call to solve a predicate with sat solver assuming all variables are free:
32 solve_predicate_with_satsolver_free(BFormula,Result) :-
33 solve_predicate_with_satsolver_free(BFormula,_,Result,[]).
34 solve_predicate_with_satsolver_free(BFormula,LocalState,Result,Options) :-
35 find_typed_identifier_uses(BFormula,UsedIdentifiers),
36 set_up_typed_localstate_for_pred(UsedIdentifiers,BFormula,TypedVals,LocalState),
37 b_optimize(BFormula,[],LocalState,[],NewTyped,no_wf_available),
38 solve_predicate_with_satsolver(NewTyped,TypedVals,LocalState,Result,Options).
39
40
41 % call to solve a predicate with sat solver with a provided state with variable/constant values:
42 solve_predicate_with_satsolver_in_state(BFormula,State,Result,Options) :-
43 find_typed_identifier_uses(BFormula,UsedIdentifiers),
44 exclude(is_already_declared_in_state(State),UsedIdentifiers,FilteredIdentifiers),
45 set_up_typed_localstate_for_pred(FilteredIdentifiers,BFormula,TypedVals,LocalState),
46 b_optimize(BFormula,[],LocalState,State,NewTyped,no_wf_available),
47 append(LocalState,State,State2),
48 solve_predicate_with_satsolver(NewTyped,TypedVals,State2,Result,Options).
49 is_already_declared_in_state(State,TID) :- def_get_texpr_id(TID,ID), memberchk(bind(ID,_),State).
50
51 solve_predicate_with_satsolver(BFormula,State) :-
52 solve_predicate_with_satsolver(BFormula,[],State,Result,[]),
53 Result = solution(_).
54
55 solve_predicate_with_satsolver(BFormula,TypedVals,State,Result,Options) :-
56 %write(' :sat '),nl, translate:nested_print_bexpr(BFormula),nl,
57 init_satsolver,!,
58 catch(if(solve_pred2(BFormula,TypedVals,State,Result,Options),true,Result=error),
59 smt_cnf_no_result(Reason), % thrown by smt_solvers_interface when using Z3 as SAT solver
60 cnf_no_result(Reason,Result)).
61 solve_predicate_with_satsolver(_,_,_,error,_).
62
63 cnf_no_result(time_out,Res) :- !, Res=time_out.
64 cnf_no_result(unknown,Res) :- !, Res=no_solution_found(solver_answered_unknown).
65 cnf_no_result(Reason,no_solution_found(Reason)).
66
67 :- use_module(probsrc(b_enumerate), [b_tighter_enumerate_all_values/2]).
68 :- use_module(probsrc(kernel_waitflags),
69 [init_wait_flags_with_call_stack/2,ground_wait_flags/1,
70 ground_det_wait_flag/1]).
71
72 solve_pred2(BFormula,TypedVals,State,Result,Options) :-
73 init_wait_flags_with_call_stack(WF,[prob_command_context(sat_solving,unknown)]),
74 if(solve_pred3(BFormula,State,Result,Options,WF),
75 (b_tighter_enumerate_all_values(TypedVals,WF),
76 ground_wait_flags(WF)),
77 Result=contradiction_found).
78
79 solve_pred3(BFormula,State,Result,Options,WF) :-
80 start_ms_timer(T1),
81 % Note: b_to_cnf will also look up all identifiers
82 (b_to_cnf_wf(BFormula,State,CNF,WF)
83 -> stop_ms_timer_with_profile(T1,b_to_cnf_walltime,'Converting B to CNF'),
84 ground_det_wait_flag(WF),
85 start_ms_timer(T2),
86 %portray_cnf(CNF),
87 %translate:print_bstate(State),nl,
88 solve_cnf(T2,CNF,State,Result,Options)
89 ; Result=error
90 ).
91
92 solve_cnf(T2,CNF,State,Result,Options) :-
93 bt_sat(CNF,Options),
94 stop_ms_timer_with_profile(T2,sat_walltime,'Formula is SATisfiable'),
95 Result = solution(State).
96 solve_cnf(T2,_,_,_Result,_Options) :-
97 stop_ms_timer_with_profile(T2,sat_walltime,'Formula is UNSATisfiable'),
98 fail. % fail to avoid pending co-routines of b_to_cnf
99
100 :- public portray_cnf/1.
101 portray_cnf(CNF) :- write('CNF:'),nl,maplist(portray_cl,CNF).
102 portray_cl(Clause) :- format(' ~w~n',[Clause]).
103
104
105 :- use_module(library(system),[ datime/1]).
106 :- use_module(probsrc(version),[version_str/1]).
107 :- use_module(probsrc(tools_strings),[number_codes_min_length/3]).
108 :- use_module(probsrc(error_manager), [add_warning/3]).
109 portray_cnf_in_dimacs(Stream,CNF,ClNr,NrVars) :-
110 Offset=2, % assumes that variables start at 3, variable 1 is truth, variable 2 falsity
111 format(Stream,'c Dimacs export by ProB~n',[]),
112 version_str(Str),datime(datime(Yr,Mon,Day,Hr,Min,_Sec)),
113 number_codes_min_length(Min,2,MC),
114 format(Stream,'c generated on ~w/~w/~w at ~w:~s using ProB version ~w~n',[Day,Mon,Yr,Hr,MC,Str]),
115 format(Stream,'p cnf ~w ~w~n',[NrVars,ClNr]),
116 maplist(portray_dimacs_clause(Stream,Offset),CNF).
117 portray_dimacs_clause(Stream,Offset,Clause) :- portray_dimacs_cl(Clause,Offset,Stream),format(Stream,'0~n',[]).
118 portray_dimacs_cl([],_,_).
119 portray_dimacs_cl([neg(H)|T],Offset,Stream) :- !, H1 is H-Offset,
120 (H1 < 1 -> add_warning(b2sat,'CNF variable too small: ',H) ; true),
121 format(Stream,'-~w ',H1),
122 portray_dimacs_cl(T,Offset,Stream).
123 portray_dimacs_cl([H|T],Offset,Stream) :- H1 is H-Offset,
124 (H1 < 1 -> add_warning(b2sat,'CNF variable too small: ',H) ; true),
125 format(Stream,'~w ',H1),
126 portray_dimacs_cl(T,Offset,Stream).
127
128 :- use_module(library(between),[between/3]).
129 :- use_module(probsrc(tools_strings),[ajoin/2,ajoin_with_sep/3]).
130 :- use_module(library(lists),[nth1/3]).
131 :- use_module(probsrc(translate),[translate_span/2]).
132
133 :- public cnf_node_predicate/7.
134 % predicates for dot_graph_generator
135 % variable nodes: coloured by their value in the model (if a model was found); clause nodes: list of literals
136 cnf_node_predicate(_CNF,_ClNr,NrVars,Model,NodeID,SubGraph,[label/htmllabel(Label),tooltip/Tooltip|Attrs]) :- SubGraph=none,
137 between(1,NrVars,NodeID), ModelID is NodeID+2,
138 (b2sat_cnf_literal_info(ModelID,Name,Info)
139 -> translate_span(Info,TIP),
140 (Name \= unknown -> true ; Name='')
141 ; TIP = 'Unknown source', Name=''
142 ),
143 tools:html_escape(Name,EName),
144 (Name='' -> ajoin(['<<b>x',NodeID,'</b>>'],Label)
145 ; ajoin(['<<font point-size="9" color="#707070">x',NodeID,'</font><br/><b>',EName,'</b>>'],Label)),
146 (Model=[] -> Val=unknown, Attrs0=[fillcolor/white, color/gray45]
147 ; member(ModelID,Model) -> Val='TRUE', Attrs0=[fillcolor/'#C8E6C9', color/'#2E7D32']
148 ; Val='FALSE', Attrs0=[fillcolor/'#FFCDD2', color/'#C62828']),
149 ajoin(['SAT variable x',NodeID,' ',Name,' ',TIP,', value: ',Val],Tooltip),
150 (Val=unknown -> LText='SAT variable' ; ajoin(['SAT variable = ',Val],LText)),
151 vig_legend(LText,10,Legend), append(Attrs0,[shape/ellipse|Legend],Attrs).
152 cnf_node_predicate(CNF,ClNr,NrVars,_Model,NodeID,SubGraph,[label/htmllabel(Label),tooltip/Tooltip,
153 fillcolor/'#E3EDF7',color/'#1F5F99'|Legend]) :- SubGraph=none,
154 between(1,ClNr,CID), NodeID is CID+NrVars,
155 nth1(CID,CNF,Clause),
156 convert_clause(Clause,CAtoms,[]),
157 ajoin(CAtoms,ClauseTxt),
158 ajoin(['<<font point-size="9" color="#707070">clause ',CID,'</font><br/>',ClauseTxt,'>'],Label),
159 ajoin(['Clause ',CID],Tooltip),
160 vig_legend('clause',20,Legend).
161
162 vig_legend(Text,Order,[legend/Text, legend_order/Order]) :- get_preference(dot_print_legend,true), !.
163 vig_legend(_,_,[]).
164
165 convert_clause([A]) --> !, convert_lit(A).
166 convert_clause([A|T]) --> convert_lit(A), [' \x2228\ '], convert_clause(T).
167
168 convert_lit(neg(A)) --> !,['\xAC\'],
169 convert_lit(A).
170 convert_lit(A) --> [x],{A1 is A-2},[A1].
171
172
173 % edges: blue for positive, purple for negative literals; dotted if the literal is false in the model
174 :- public cnf_trans_predicate/7.
175 cnf_trans_predicate(CNF,_ClNr,NrVars,Model,RealNodeID,SuccID,[dir/none,color/COL,style/STY,label/LBL,fontcolor/COL|Legend]) :-
176 nth1(CID,CNF,Clause), SuccID is CID+NrVars,
177 member(Lit,Clause),
178 (Lit = neg(NodeID)
179 -> LBL='\xAC\', COL='#6A1B9A', Sign=negative,
180 (member(NodeID,Model) -> Truth=false ; Truth=true)
181 ; NodeID=Lit, LBL='', COL='#1F5F99', Sign=positive,
182 (member(NodeID,Model) -> Truth=true ; Truth=false)
183 ), RealNodeID is NodeID-2, % literals 1 and 2 are virtual
184 (Model=[] -> STY=solid, ajoin([Sign,' literal'],LText), Order=30
185 ; Truth=true -> STY=solid, ajoin([Sign,' literal, true in model'],LText), Order=30
186 ; STY=dotted, ajoin([Sign,' literal, false in model'],LText), Order=31),
187 vig_legend(LText,Order,Legend).
188
189 :- use_module(covsrc(hit_profiler),[add_to_profile_stats/2]).
190 stop_ms_timer_with_profile(Timer,Category,Msg) :-
191 get_elapsed_walltime(Timer,WT),
192 add_to_profile_stats(Category,WT),
193 stop_ms_timer_with_msg(Timer,Msg),
194 flush_output.
195
196
197 % --------------
198
199
200 % backtracking solving:
201 bt_sat(CNF,Options) :-
202 get_new_solver(SolverID,Options),
203 call_cleanup(bt_sat_aux(SolverID,CNF),
204 reset_solver(SolverID)).
205
206 bt_sat_aux(SolverID,CNF) :-
207 addCnf2Solver(SolverID,CNF,FVars,NrVars),!,
208 %write_c_solver_dimacs_file_if_requested(SolverID),
209 debug_format(19,'Solving for ~w sat variables~n',[NrVars]),
210 flush_output,
211 solve_and_get_model_from_solver(SolverID,Model),
212 debug_format(19,'Model = ~w~n',[Model]),
213 bt_sat3(SolverID,FVars,Model).
214 bt_sat_aux(SolverID,_) :-
215 debug_format(19,'Inconsistency detected while adding clauses to SAT Solver ~w~n',[SolverID]),
216 fail.
217
218 :- use_module(probsrc(bmachine),[bmachine_is_precompiled/0, b_absolute_file_name_relative_to_main_machine/2]).
219 :- use_module(probsrc(preferences), [get_preference/2]).
220 %write_c_solver_dimacs_file_if_requested(SolverID) :-
221 % get_preference(path_to_intermediate_output,Path), Path \= '', !,
222 % % TODO: if path is folder, append satsolver_dimacs.cnf
223 % (bmachine_is_precompiled, b_absolute_file_name_relative_to_main_machine(Path,AbsPath) -> true
224 % ; AbsPath=Path),
225 % format('% Writing CNF in Dimacs format for B2SAT solver ~w to file: ~w~n',[SolverID,AbsPath]),
226 % toDimacs(SolverID,AbsPath). % export CNF to Dimacs format, satsolver_dimacs.cnf
227 % % Note: sometimes Glucose simply writes p cnf 0 0 if the solver state is contradictory?!
228 %write_c_solver_dimacs_file_if_requested(_).
229
230
231 :- use_module(probsrc(tools_io),[safe_intelligent_open_file/4]).
232 write_dimacs_file_if_requested(CNF,NrVars) :-
233 get_preference(path_to_intermediate_output,Path), Path \= '', !,
234 length(CNF,ClNr), % the number of clauses after simplification
235 % TODO: if path is folder, append satsolver_dimacs.cnf
236 (bmachine_is_precompiled, b_absolute_file_name_relative_to_main_machine(Path,AbsPath) -> true
237 ; AbsPath=Path),
238 format('% Writing CNF in Dimacs format for B2SAT solver to file: ~w~n',[AbsPath]),
239 safe_intelligent_open_file(AbsPath, write, Stream,[encoding(utf8)]),
240 call_cleanup(portray_cnf_in_dimacs(Stream,CNF,ClNr,NrVars),close(Stream)),
241 store_cnf_for_dot(CNF,NrVars). %write_vig_graph_if_requested(CNF,ClNr,NrVars,[]).
242 write_dimacs_file_if_requested(_,_).
243
244 :- dynamic b2sat_model_for_dot/1, b2sat_cnf_for_dot/3.
245
246 :- use_module(probsrc(eventhandling),[register_event_listener/3]).
247 :- register_event_listener(clear_specification,reset_b2sat,
248 'Reset B2SAT.').
249 reset_b2sat :- retractall(b2sat_model_for_dot(_)),
250 retractall(b2sat_cnf_for_dot(_,_,_)).
251
252 store_model_for_dot(Model) :- get_preference(path_to_intermediate_output,Path), Path \= '',!,
253 retractall(b2sat_model_for_dot(_)),
254 assert(b2sat_model_for_dot(Model)). % model will be something like [-2,3,-4]
255 store_model_for_dot(_).
256
257 store_cnf_for_dot(CNF,NrVars) :- get_preference(path_to_intermediate_output,Path), Path \= '',!,
258 retractall(b2sat_cnf_for_dot(_,_,_)),
259 advanced_simplify_cnf(CNF,SCNF),!,
260 length(SCNF,ClNr),
261 assert(b2sat_cnf_for_dot(SCNF,ClNr,NrVars)).
262 store_cnf_for_dot(_,_).
263
264 % generate variable incidence graph if we have stored the infos
265 generate_cnf_vig_graph(File) :- b2sat_cnf_for_dot(CNF,ClNr,NrVars), !,
266 (b2sat_model_for_dot(Model) -> true ; Model = []),
267 gen_cnf_vig_graph(File,CNF,ClNr,NrVars,Model).
268 generate_cnf_vig_graph(_File) :-
269 add_warning(b2sat,'No CNF stored, be sure to set path_to_intermediate_output preference','').
270
271 cnf_vig_graph_available :- b2sat_cnf_for_dot(_,_,_).
272
273 %write_vig_graph_if_requested(CNF,ClNr,NrVars,Model) :- fail,
274 % get_preference(path_to_intermediate_output,Path), Path \= '',
275 % bmachine_is_precompiled, b_absolute_file_name_relative_to_main_machine('cnf_vig_graph.dot',AbsPath),
276 % advanced_simplify_cnf(CNF,SCNF),!,
277 % gen_cnf_vig_graph(AbsPath,SCNF,ClNr,NrVars,Model).
278 %write_vig_graph_if_requested(_,_,_,_).
279
280 % Variable Incidence Graph (VIG)
281 :- use_module(dotsrc(dot_graph_generator), [gen_dot_graph/6,use_new_dot_attr_pred/7,dot_no_same_rank/1, dot_no_subgraph/3]).
282 gen_cnf_vig_graph(File,CNF,ClNr,NrVars,Model) :-
283 (get_preference(dot_print_graph_title,true)
284 -> (Model=[] -> MTxt='' ; MTxt=', colours show the model found'),
285 ajoin(['CNF variable incidence graph: ',NrVars,' variables, ',ClNr,' clauses',MTxt],Title),
286 TitleAttrs=[label/Title, labelloc/t, fontsize/14]
287 ; TitleAttrs=[]),
288 GraphAttrs=[graph_name/cnf_vig, no_page_size, fontname/'Helvetica', nodesep/0.3, ranksep/0.8,
289 node_defaults/[fontname/'Helvetica', fontsize/11, shape/box, style/'rounded,filled', margin/'0.1,0.04'],
290 edge_defaults/[fontname/'Helvetica', fontsize/10, penwidth/1.5]
291 | TitleAttrs],
292 gen_dot_graph(File,GraphAttrs,
293 use_new_dot_attr_pred(b2sat:cnf_node_predicate(CNF,ClNr,NrVars,Model)),
294 use_new_dot_attr_pred(b2sat:cnf_trans_predicate(CNF,ClNr,NrVars,Model)),
295 dot_no_same_rank,dot_no_subgraph).
296
297
298 bt_sat3(SolverID,FVars,Model) :-
299 debug_format(19,'Assigning Model~n',[]),
300 assign_model_from_solver(SolverID,FVars,Model),
301 store_model_for_dot(Model).
302 bt_sat3(SolverID,FVars,Model) :-
303 debug_format(19,'Adding negated model to find another solution~n',[]),
304 add_negated_model(SolverID,Model),
305 solve_and_get_model_from_solver(SolverID,NewModel),
306 bt_sat3(SolverID,FVars,NewModel).
307
308 add_negated_model(SolverID,Model):-
309 maplist(neg,Model,NoAsgn),
310 add_extra_clause_to_solver(SolverID,NoAsgn).
311
312 neg(V,VN) :- VN is -V.
313
314 % -----------------
315
316 addCnf2Solver(SolverID,Cnf,FVars,NrVars):-
317 term_variables(Cnf,FVars),!,
318 length(FVars,NrVars), length(Cnf,ClNr),
319 format('Clauses: ~w, SAT Variables: ~w, Solver ID: ~w ~n',[ClNr,NrVars,SolverID]),
320 add_to_profile_stats(sat_clauses,ClNr),
321 add_to_profile_stats(sat_vars,NrVars),
322 \+ \+ (bind2index(FVars,3,FN),
323 %portray_cnf(Cnf),
324 simplify_cnf(Cnf,SCnf),
325 AllCnf = [[1],[-2]|SCnf], % add true literal 1 and false literal 2
326
327 %nl,portray_cnf(AllCnf),
328 write_dimacs_file_if_requested(SCnf,NrVars),
329 add_cnf_clauses_to_solver(SolverID,[1,2|FVars],FN,AllCnf)
330 ).
331
332 % simplify CNF in case ProB propagation now has instantiated some of the SAT variables to pred_true/pred_false/...
333 simplify_cnf([],[]).
334 simplify_cnf([Clause|T],Res) :-
335 (simplify_clause(Clause,SC) % advanced_simplify_clause
336 -> Res=[SC|TR]
337 ; Res=TR), % useless clause
338 simplify_cnf(T,TR).
339
340 simplify_clause([],[]).
341 simplify_clause([FALSE|T],Res) :- false_lit(FALSE),!, simplify_clause(T,Res).
342 simplify_clause([TRUE|_],_Res) :- true_lit(TRUE),!,fail. % clause useless, it is true
343 simplify_clause([Lit|T],[Lit|Res]) :- simplify_clause(T,Res).
344
345 true_lit(1).
346 true_lit(pred_true).
347 true_lit(neg(L)) :- false_lit(L).
348 false_lit(2).
349 false_lit(pred_false).
350 false_lit(neg(L)) :- true_lit(L).
351
352 advanced_simplify_cnf([],[]).
353 advanced_simplify_cnf([Clause|T],Res) :-
354 (advanced_simplify_clause(Clause,SC)
355 -> Res=[SC|TR]
356 ; Res=TR), % useless clause
357 advanced_simplify_cnf(T,TR).
358
359 :- use_module(library(lists),[remove_dups/2]).
360 % use instead of simplify_clause if you wish to remove some tautologies or duplicate literals before sending them off:
361 advanced_simplify_clause(Clause,SC3) :-
362 simplify_clause(Clause,SC1),
363 sort(SC1,SC2),
364 remove_dups(SC2,SC3),
365 \+ tautology(SC3).
366
367 tautology(SC) :- split_clause(SC,Pos,Neg),
368 member(P,Pos),
369 member(neg(P),Neg). % TODO: advance in Pos and Neg at the same time to obtain linear algorithm
370
371 split_clause([neg(H)|T],[],NegT) :-!, NegT=[neg(H)|T].
372 split_clause([H|T],[H|PosT],NegT) :- split_clause(T,PosT,NegT).
373
374 % ------------------
375
376 % dispatching code: chooses between Glucose and Z3
377
378 :- use_module(smt_solvers_interface(smt_solvers_interface),[smt_add_cnf/3, smt_add_extra_clause_cnf/2,
379 smt_solve_cnf/2, smt_reset_cnf/1]).
380 :- use_module(smt_solvers_interface(solver_dispatcher),[init_interface/1]).
381
382 get_new_solver(z3,Options) :- member(use_satsolver(z3),Options),!,
383 (init_interface(z3) -> true
384 ; throw(smt_cnf_no_result(solver_not_available))). % failing would mean the CNF is unsatisfiable
385 get_new_solver(SolverID,_) :- % use glucose
386 new_solver(SolverID).
387
388 % reset_solver is used as cleanup in bt_sat: it must not fail, as SICStus then drops
389 % a pending exception (e.g., smt_cnf_no_result) and call_cleanup fails
390 reset_solver(z3) :- !, (smt_reset_cnf(z3) -> true ; true).
391 reset_solver(SolverID) :- delete_solver(SolverID).
392
393 add_cnf_clauses_to_solver(z3,FVars,_,AllCnf) :- !,
394 smt_add_cnf(z3,[1,2|FVars],AllCnf).
395 add_cnf_clauses_to_solver(SolverID,_,FN,AllCnf) :-
396 % The tautology FN or not(FN) makes Glucose create all variables up to the last literal FN,
397 % even if some of them no longer occur in AllCnf after simplify_cnf.
398 % Otherwise the model would be too short for assign_model, and solutions differing only
399 % in these unconstrained variables would not be enumerated.
400 neg(FN,FNeg),
401 add_clause(SolverID,[FN,FNeg]),
402 add_cnf_clauses(AllCnf,SolverID).
403
404 add_extra_clause_to_solver(z3,MiniSatCl) :- !,
405 smt_add_extra_clause_cnf(z3,MiniSatCl).
406 add_extra_clause_to_solver(SolverID,MiniSatCl) :-
407 add_clause(SolverID,MiniSatCl).
408
409 solve_and_get_model_from_solver(z3,AVLModel) :- !,
410 smt_solve_cnf(z3,AVLModel).
411 solve_and_get_model_from_solver(SolverID,Model) :-
412 solve(SolverID),
413 debug_format(19,'Get Model~n',[]),
414 get_model(SolverID,[_|Model]). % model will be something like [-2,3,-4]
415
416
417 assign_model_from_solver(z3,FVars,Model) :- !,
418 debug:debug_println(19,assign_z3_model(FVars,Model)),
419 assign_z3_model(FVars,Model).
420 %assign_model_from_solver(_,FVars,Model) :- !,
421 % %write(fvars(FVars)),nl, observe_fvars(FVars),trace,
422 % assign_z3_model(FVars,[1|Model]). % this does the binding in Prolog, TODO: check performance wrt C call below
423 assign_model_from_solver(SolverID,FVars,_Model) :-
424 assign_model(SolverID,FVars). % FVars correspond to the literals 3, 4, ...
425 % Note: assign model calls SP_unify one by one, and can fail when ProB triggers co-routines
426 % Co-routines are, however, only triggered once the full model has been assigned
427
428 % debugging code to observe instantiations:
429 %observe_fvars(FVars) :- observe_fvars(FVars,1,FVars).
430 %observe_fvars([],_,_).
431 %observe_fvars([H|T],I,FVars) :- when(nonvar(H),format('Bound sat var nr. ~w to ~w : ~w~n',[I,H,FVars])), I1 is I+1,
432 % observe_fvars(T,I1,FVars).
433
434 assign_z3_model(VarsList,[1,-2|Model]) :- !, % for z3
435 assign_z3_aux(VarsList,3,Model).
436 assign_z3_model(VarsList,[-2|Model]) :- !, % for glucose, minisat, ...
437 assign_z3_aux(VarsList,3,Model).
438 assign_z3_model(_,Model) :- add_internal_error('Z3 solution incorrect:',assign_z3_model(_,Model)), fail.
439
440 assign_z3_aux([],_,TM) :- !,
441 (TM=[] -> true ; add_internal_error('Too many literals in model:',assign_z3_aux([],_,TM))).
442 assign_z3_aux([H|T],Nr,[Model|TM]) :- !,
443 % format('Assigning ~w VAR to ~w~n',[Nr,Model]),
444 (Model=Nr -> H=pred_true
445 ; Model is -Nr -> H=pred_false
446 ; add_internal_error('Unexpected literal:',assign_z3_aux([H|T],Nr,[Model|TM])),
447 fail
448 ),
449 N1 is Nr+1,
450 assign_z3_aux(T,N1,TM).
451 assign_z3_aux(V,Nr,TM) :- add_internal_error('Model mismatch:',assign_z3_aux(V,Nr,TM)).
452
453 % ------------------
454
455
456 add_cnf_clauses([Cl|Cls],SolverID):-!,
457 to_minisat_cl(Cl,MiniSatCl),
458 %format('Adding clause to solver ~w: ~w~n',[SolverID,MiniSatCl]),
459 add_clause(SolverID,MiniSatCl), % add_clause can fail when SAT solver detects inconsistency directly
460 add_cnf_clauses(Cls,SolverID).
461 add_cnf_clauses([],_):-!.
462
463 to_minisat_cl([],[]).
464 to_minisat_cl([Lit1|TL],[ML1|TM]) :- to_minisat_lit(Lit1,ML1), to_minisat_cl(TL,TM).
465
466 % pred_true/pred_false should be eliminated in simplify_cnf above
467 to_minisat_lit(pred_true,1) :- !.
468 to_minisat_lit(pred_false,2) :- !.
469 to_minisat_lit(neg(NL),MSLit) :- !, to_minisat_neg_lit(NL,MSLit).
470 to_minisat_lit(X,R) :- integer(X),!, R=X. % a Prolog variable that has been bound by bind2index to a number
471 to_minisat_lit(X,R) :- add_internal_error('Illegal literal: ',to_minisat_lit(X,R)), R=X.
472
473 to_minisat_neg_lit(pred_false,1) :- !.
474 to_minisat_neg_lit(pred_true,2) :- !.
475 to_minisat_neg_lit(X,R) :- integer(X),!, R=neg(X). % a Prolog variable that has been bound by bind2index to a number
476 to_minisat_neg_lit(X,R) :- add_internal_error('Illegal literal: ',to_minisat_neg_lit(X,R)), R=neg(X).
477
478 % bind a list of variables to numbers (representing literals in .cnf)
479 bind2index([N|Ns],N,FN) :- N1 is N+1, bind2index(Ns,N1,FN).
480 bind2index([],N,FN):-!, FN is N - 1.