Class: Udb::LogicNode
- Inherits:
-
Object
- Object
- Udb::LogicNode
- Extended by:
- T::Sig
- Defined in:
- lib/udb/logic.rb,
lib/udb/eqn.rb
Overview
Abstract syntax tree of the condition logic
Defined Under Namespace
Classes: CanonicalizationType, ConditionalEndterm, EqntottResult, LogicSymbolFormat, MemoizedState, PairMintermsResult, PrimeImplicantsResult, SizeExplosion
Constant Summary collapse
- ChildType =
T.type_alias { T.any(LogicNode, TermType) }
- True =
LogicNode.new(LogicNodeType::True, [])
- False =
LogicNode.new(LogicNodeType::False, [])
- Xlen32 =
LogicNode.new(LogicNodeType::Term, [XlenTerm.new(32).freeze]).freeze
- Xlen64 =
LogicNode.new(LogicNodeType::Term, [XlenTerm.new(64).freeze]).freeze
- EvalCallbackType =
T.type_alias { T.proc.params(arg0: TermType).returns(SatisfiedResult) }
- ReplaceCallbackType =
T.type_alias { T.proc.params(arg0: LogicNode).returns(LogicNode) }
- LOGIC_SYMBOLS =
{ LogicSymbolFormat::C => { TRUE: "1", FALSE: "0", NOT: "!", AND: "&&", OR: "||", XOR: "^", IMPLIES: "->" # making this up; there is no implication operator in C }, LogicSymbolFormat::Eqn => { TRUE: "ONE", FALSE: "ZERO", NOT: "!", AND: "&", OR: "|", XOR: "DOES NOT EXIST", IMPLIES: "DOES NOT EXIST" }, LogicSymbolFormat::English => { TRUE: "true", FALSE: "false", NOT: "NOT ", AND: "AND", OR: "OR", XOR: "XOR", IMPLIES: "IMPLIES" }, LogicSymbolFormat::Predicate => { TRUE: "true", FALSE: "false", NOT: "\u00ac", AND: "\u2227", OR: "\u2228", XOR: "\u2295", IMPLIES: "\u2192" } }
Instance Attribute Summary collapse
- #children ⇒ Array<ChildType> readonly
-
#memo ⇒ Object
Returns the value of attribute memo.
- #type ⇒ LogicNodeType readonly
Class Method Summary collapse
-
.find_prime_implicants(mterms, group_by) ⇒ PrimeImplicantsResult
given a list of minterms/maxterms, each represented by a string of “0” and “1”, return the prime implicants, represented by a string of “0”, “1”, and “-”.
- .group_mterms(mterms, group_by) ⇒ Hash{Integer => Array<String>}
- .inc_brute_force_sat_solves ⇒ Object
- .inc_z3_cache_hits ⇒ Object
- .inc_z3_sat_solves ⇒ Object
- .make_eval_cb(&blk) ⇒ EvalCallbackType
- .make_replace_cb(&blk) ⇒ ReplaceCallbackType
- .num_brute_force_sat_solves ⇒ Object
- .num_z3_cache_hits ⇒ Object
- .num_z3_sat_solves ⇒ Object
- .pair_mterms(group1, group2) ⇒ PairMintermsResult
- .prime_implicant_covers_mterm?(implicant, minterm) ⇒ Boolean
-
.reset_stats ⇒ Object
statistics counters.
Instance Method Summary collapse
-
#cnf? ⇒ Boolean
returns true iff tree is in Conjunctive Normal Form.
-
#cnf_conjunction_term? ⇒ Boolean
private
returns true iff tree is a valid term in a cnf conjunction.
- #collect_tseytin(subformulae) private
- #distribute_not ⇒ LogicNode private
-
#dnf? ⇒ Boolean
returns true iff tree is in Disjunctive Normal Form.
-
#dnf_disjunctive_term? ⇒ Boolean
private
returns true iff tree is a valid term in a dnf disjunction.
- #do_to_eqntott(tree, term_map) ⇒ String
- #eql?(other) ⇒ Boolean
-
#equisat_cnf ⇒ LogicNode
coverts self to an equisatisfiable formula in Conjunctive Normal Form and returns it as a new formula (self is unmodified).
- #equisatisfiable?(other, cfg_arch) ⇒ Boolean
-
#equiv_cnf(raise_on_explosion: true) ⇒ LogicNode
coverts self to an equivalent formula in Conjunctive Normal Form and returns it as a new formula (self is unmodified).
-
#equivalent?(other, cfg_arch) ⇒ Boolean
True iff self and other are logically equivalent (identical truth tables).
-
#espresso(result_type, exact) ⇒ LogicNode
minimize the function using espresso.
- #eval_cb(callback) ⇒ SatisfiedResult
- #from_dimacs(dimacs) ⇒ LogicNode
-
#group_by_2 ⇒ LogicNode
Rewrites the tree so that no node has more than 2 children.
-
#grouped_by_2?(node) ⇒ Boolean
does each node have at most two children?.
- #hash ⇒ Integer private
- #initialize(type, children) constructor
-
#literals ⇒ Array<TermType>
unlike #terms, this list will include leaves that are equivalent.
-
#minimal_unsat_subsets ⇒ Array<LogicNode>
return minimally unsatisfiable subsets of the unstatisfiable formula.
-
#minimize(result_type) ⇒ LogicNode
convert to either sum-of-products form or product-of-sums form and minimize the result.
-
#nested_cnf? ⇒ Boolean
returns true iff tree, if flattened, would be cnf allows nested ANDs as long as there is no ancestor OR allows nested ORs as long as there is no decendent AND.
-
#nested_cnf_conjunction_term?(ancestor_or) ⇒ Boolean
private
returns true iff tree is a valid term in a nested cnf conjunction.
-
#nnf ⇒ LogicNode
Self, converted to Negation Normal Form.
-
#nnf? ⇒ Boolean
True iff self is in Negation Normal Form.
- #node_children ⇒ Array<LogicNode> private
-
#partial_evaluate(cb) ⇒ LogicNode
partially evalute – replace anything known with true/false, and otherwise leave it alone.
-
#reduce ⇒ LogicNode
reduce the equation by removing easy identities:.
- #replace_terms(callback) ⇒ LogicNode
-
#satisfiability_depends_on_ext_req?(ext_req) ⇒ Boolean
If ext_req is false, can this logic tree be satisfied?.
-
#satisfiable?(cfg_arch) ⇒ Boolean
True iff self is satisfiable (possible to be true for some combination of term values).
-
#terms ⇒ Array<TermType>
The unique terms (leafs) of this tree.
-
#terms_no_antecendents ⇒ Array<TermType>
The unique terms (leafs) of this tree, exculding antecendents of an IF.
- #to_asciidoc(include_versions:) ⇒ String
- #to_dimacs ⇒ String
-
#to_eqntott ⇒ EqntottResult
return equation suitable for
eqntottinput. -
#to_h(term_determined = false) ⇒ Boolean, Hash{String => T.untyped}
convert to a UDB schema.
- #to_idl(cfg_arch) ⇒ String
- #to_s(format: LogicSymbolFormat::Predicate) ⇒ String
-
#to_s_pretty ⇒ String
return a nice, human-readable form that may gloss over details.
- #to_s_with_value(callback, format: LogicSymbolFormat::Predicate) ⇒ String
- #to_z3(cfg_arch, solver = Z3Solver.new) ⇒ Z3::BoolExpr
- #tseytin ⇒ LogicNode private
-
#tseytin_prop ⇒ LogicNode
a free variable representing this formula.
-
#unsatisfiable?(cfg_arch) ⇒ Boolean
True iff self is unsatisfiable (not possible to be true for any combination of term values).
Constructor Details
#initialize(type, children)
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 |
# File 'lib/udb/logic.rb', line 1254 def initialize(type, children) if [LogicNodeType::Term, LogicNodeType::Not].include?(type) && children.size != 1 raise ArgumentError, "Children must be singular" end if [LogicNodeType::And, LogicNodeType::Or, LogicNodeType::Xor, LogicNodeType::None, LogicNodeType::If].include?(type) && children.size < 2 raise ArgumentError, "Children must have at least two elements" end @children = children @children.freeze @node_children = (@type == LogicNodeType::Term) ? nil : T.cast(@children, T::Array[LogicNode]) if [LogicNodeType::True, LogicNodeType::False].include?(type) && !children.empty? raise ArgumentError, "Children must be empty" elsif type == LogicNodeType::Term # ensure the children are TermType children.each { |child| T.assert_type!(T.cast(child, TermType), TermType) } else # raise ArgumentError, "All Children must be LogicNodes" unless children.all? { |child| child.is_a?(LogicNode) } end @type = type @type.freeze # used for memoization in transformation routines @memo = MemoizedState.new( is_cnf: nil, is_nested_cnf: nil, is_reduced: nil, terms: nil, literals: nil, is_satisfiable: nil, equisat_cnf: nil, equiv_cnf: nil ) end |
Instance Attribute Details
#children ⇒ Array<ChildType> (readonly)
1213 1214 1215 |
# File 'lib/udb/logic.rb', line 1213 def children @children end |
#memo ⇒ Object
Returns the value of attribute memo.
1251 1252 1253 |
# File 'lib/udb/logic.rb', line 1251 def memo @memo end |
#type ⇒ LogicNodeType (readonly)
1210 1211 1212 |
# File 'lib/udb/logic.rb', line 1210 def type @type end |
Class Method Details
.find_prime_implicants(mterms, group_by) ⇒ PrimeImplicantsResult
given a list of minterms/maxterms, each represented by a string of “0” and “1”, return the prime implicants, represented by a string of “0”, “1”, and “-”
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 |
# File 'lib/udb/logic.rb', line 1438 def self.find_prime_implicants(mterms, group_by) groups = group_mterms(mterms, group_by) # Pair mterms until no further simplification is possible prime_implicants = T.let([], T::Array[String]) matched = T.let(Set.new, T::Set[String]) while groups.size > 1 new_groups = Hash.new { |h, k| h[k] = [] } matched.clear groups.keys.sort.each_cons(2) do |k1, k2| res = pair_mterms(T.must(groups[T.must(k1)]), T.must(groups[T.must(k2)])) matched.merge(res.matched_mterms) new_group = res.new_group new_groups[k1] += new_group unless new_group.empty? end prime_implicants += groups.values.flatten.reject { |mterm| matched.include?(mterm) } groups = new_groups end prime_implicants += groups.values.flatten.reject { |mterm| matched.include?(mterm) } prime_implicants.uniq! coverage = Hash.new { |h, k| h[k] = [] } mterms.each do |minterm| prime_implicants.each_with_index do |implicant, idx| if prime_implicant_covers_mterm?(implicant, minterm) coverage[minterm] << idx end end end essential_indices = [] uncovered = mterms.dup # Find essential prime implicants coverage.each do |mterm, implicant_indices| if implicant_indices.size == 1 idx = implicant_indices.first unless essential_indices.include?(idx) essential_indices << idx # Remove all minterms covered by this implicant uncovered.reject! { |m| prime_implicant_covers_mterm?(prime_implicants.fetch(idx), m) } end end end minimal_indices = essential_indices.dup # Greedy selection for remaining minterms while uncovered.any? best_idx = T.cast(prime_implicants.each_with_index.max_by do |implicant, idx| uncovered.count { |m| prime_implicant_covers_mterm?(implicant, m) } end, T::Array[Integer]).last minimal_indices << best_idx uncovered.reject! { |m| prime_implicant_covers_mterm?(prime_implicants.fetch(T.must(best_idx)), m) } end PrimeImplicantsResult.new( essential: essential_indices.map { |i| prime_implicants.fetch(i) }, minimal: minimal_indices.map { |i| prime_implicants.fetch(i) } ) end |
.group_mterms(mterms, group_by) ⇒ Hash{Integer => Array<String>}
1380 1381 1382 1383 1384 1385 1386 1387 1388 |
# File 'lib/udb/logic.rb', line 1380 def self.group_mterms(mterms, group_by) groups = T.let({}, T::Hash[Integer, T::Array[String]]) mterms.each do |mterm| n = mterm.count(group_by) groups[n] ||= [] groups.fetch(n) << mterm end groups end |
.inc_brute_force_sat_solves ⇒ Object
1186 1187 1188 |
# File 'lib/udb/logic.rb', line 1186 def self.inc_brute_force_sat_solves @num_brute_force_sat_solves += 1 end |
.inc_z3_cache_hits ⇒ Object
1202 1203 1204 |
# File 'lib/udb/logic.rb', line 1202 def self.inc_z3_cache_hits @num_z3_cache_hits += 1 end |
.inc_z3_sat_solves ⇒ Object
1194 1195 1196 |
# File 'lib/udb/logic.rb', line 1194 def self.inc_z3_sat_solves @num_z3_sat_solves += 1 end |
.make_eval_cb(&blk) ⇒ EvalCallbackType
1653 1654 1655 |
# File 'lib/udb/logic.rb', line 1653 def self.make_eval_cb(&blk) blk end |
.make_replace_cb(&blk) ⇒ ReplaceCallbackType
1659 1660 1661 |
# File 'lib/udb/logic.rb', line 1659 def self.make_replace_cb(&blk) blk end |
.num_brute_force_sat_solves ⇒ Object
1182 1183 1184 |
# File 'lib/udb/logic.rb', line 1182 def self.num_brute_force_sat_solves @num_brute_force_sat_solves end |
.num_z3_cache_hits ⇒ Object
1198 1199 1200 |
# File 'lib/udb/logic.rb', line 1198 def self.num_z3_cache_hits @num_z3_cache_hits end |
.num_z3_sat_solves ⇒ Object
1190 1191 1192 |
# File 'lib/udb/logic.rb', line 1190 def self.num_z3_sat_solves @num_z3_sat_solves end |
.pair_mterms(group1, group2) ⇒ PairMintermsResult
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 |
# File 'lib/udb/logic.rb', line 1396 def self.pair_mterms(group1, group2) new_group = [] matched = Set.new group1.each do |m1| group2.each do |m2| diff_count = 0 diff_index = -1 loop_index = 0 m1.each_char do |bit| if bit != m2[loop_index] diff_count += 1 diff_index = loop_index end loop_index += 1 end if diff_count == 1 new_mterm = m1.dup new_mterm[diff_index] = "-" new_group << new_mterm matched.add(m1) matched.add(m2) end end end PairMintermsResult.new(new_group: new_group.uniq, matched_mterms: matched) end |
.prime_implicant_covers_mterm?(implicant, minterm) ⇒ Boolean
1424 1425 1426 1427 1428 |
# File 'lib/udb/logic.rb', line 1424 def self.prime_implicant_covers_mterm?(implicant, minterm) implicant.chars.zip(minterm.chars).all? do |i_bit, m_bit| i_bit == "-" || i_bit == m_bit end end |
.reset_stats ⇒ Object
statistics counters
1172 1173 1174 1175 1176 1177 1178 |
# File 'lib/udb/logic.rb', line 1172 def self.reset_stats @num_brute_force_sat_solves = 0 @time_brute_force_sat_solves = 0 @num_z3_sat_solves = 0 @time_z3_sat_solves = 0 @num_z3_cache_hits = 0 end |
Instance Method Details
#cnf? ⇒ Boolean
returns true iff tree is in Conjunctive Normal Form
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 |
# File 'lib/udb/logic.rb', line 2796 def cnf? unless @memo.is_cnf.nil? return @memo.is_cnf end ret = case @type when LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False true when LogicNodeType::Not node_children.fetch(0).type == LogicNodeType::Term when LogicNodeType::Or node_children.all? do |child| [ child.type == LogicNodeType::True, child.type == LogicNodeType::False, child.type == LogicNodeType::Term, child.type == LogicNodeType::Not && \ child.node_children.fetch(0).type == LogicNodeType::Term ].any? end when LogicNodeType::Xor, LogicNodeType::If, LogicNodeType::None false when LogicNodeType::And node_children.all? { |child| child.cnf_conjunction_term? } else T.absurd(@type) end @memo.is_cnf = ret end |
#cnf_conjunction_term? ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
returns true iff tree is a valid term in a cnf conjunction
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 |
# File 'lib/udb/logic.rb', line 2858 def cnf_conjunction_term? case @type when LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False true when LogicNodeType::Not node_children.fetch(0).type == LogicNodeType::Term when LogicNodeType::Or # or is only valid if only contains literals node_children.all? do |child| [ child.type == LogicNodeType::True, child.type == LogicNodeType::False, child.type == LogicNodeType::Term, ((child.type == LogicNodeType::Not) && \ child.node_children.fetch(0).type == LogicNodeType::Term) ].any? end when LogicNodeType::And, LogicNodeType::Xor, LogicNodeType::If, LogicNodeType::None false else T.absurd(@type) end end |
#collect_tseytin(subformulae)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 |
# File 'lib/udb/logic.rb', line 3243 def collect_tseytin(subformulae) case @type when LogicNodeType::And # (¬A ∨ ¬B ∨ p) ∧ (A ∨ ¬p) ∧ (B ∨ ¬p) a = node_children.fetch(0).tseytin_prop b = node_children.fetch(1).tseytin_prop subformulae << LogicNode.new( LogicNodeType::And, [ LogicNode.new(LogicNodeType::Or, [ LogicNode.new(LogicNodeType::Not, [a]), LogicNode.new(LogicNodeType::Not, [b]), tseytin_prop ] ), LogicNode.new(LogicNodeType::Or, [ a, LogicNode.new(LogicNodeType::Not, [tseytin_prop]) ] ), LogicNode.new(LogicNodeType::Or, [ b, LogicNode.new(LogicNodeType::Not, [tseytin_prop]) ] ) ] ) node_children.fetch(0).collect_tseytin(subformulae) node_children.fetch(1).collect_tseytin(subformulae) when LogicNodeType::Or # (A ∨ B ∨ ¬p) ∧ (¬A ∨ p) ∧ (¬B ∨ p) a = node_children.fetch(0).tseytin_prop b = node_children.fetch(1).tseytin_prop subformulae << LogicNode.new( LogicNodeType::And, [ LogicNode.new(LogicNodeType::Or, [a, b, LogicNode.new(LogicNodeType::Not, [tseytin_prop])]), LogicNode.new(LogicNodeType::Or, [LogicNode.new(LogicNodeType::Not, [a]), tseytin_prop]), LogicNode.new(LogicNodeType::Or, [LogicNode.new(LogicNodeType::Not, [b]), tseytin_prop]) ] ) node_children.fetch(0).collect_tseytin(subformulae) node_children.fetch(1).collect_tseytin(subformulae) when LogicNodeType::Not # (A ∨ p) ∧ (¬A ∨ ¬p) a = node_children.fetch(0).tseytin_prop subformulae << LogicNode.new( LogicNodeType::And, [ LogicNode.new(LogicNodeType::Or, [a, tseytin_prop]), LogicNode.new(LogicNodeType::Or, [ LogicNode.new(LogicNodeType::Not, [a]), LogicNode.new(LogicNodeType::Not, [tseytin_prop]), ]) ] ) node_children.fetch(0).collect_tseytin(subformulae) when LogicNodeType::True, LogicNodeType::False # pass when LogicNodeType::Term # pass else raise "? #{@type}" end end |
#distribute_not ⇒ LogicNode
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
3230 3231 3232 3233 3234 3235 |
# File 'lib/udb/logic.rb', line 3230 def distribute_not # recursively apply demorgan until we get to terms raise "Not a negation" unless @type == LogicNodeType::Not distribute_not_helper(self) end |
#dnf? ⇒ Boolean
returns true iff tree is in Disjunctive Normal Form
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 |
# File 'lib/udb/logic.rb', line 2830 def dnf? case @type when LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False true when LogicNodeType::Not node_children.fetch(0).type == LogicNodeType::Term when LogicNodeType::Or node_children.all? { |child| child.dnf_disjunctive_term? } when LogicNodeType::And node_children.all? do |child| [ child.type == LogicNodeType::True, child.type == LogicNodeType::False, child.type == LogicNodeType::Term, child.type == LogicNodeType::Not && \ child.node_children.fetch(0).type == LogicNodeType::Term ].any? end when LogicNodeType::Xor, LogicNodeType::If, LogicNodeType::None false else T.absurd(@type) end end |
#dnf_disjunctive_term? ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
returns true iff tree is a valid term in a dnf disjunction
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 |
# File 'lib/udb/logic.rb', line 2885 def dnf_disjunctive_term? case @type when LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False true when LogicNodeType::Not node_children.fetch(0).type == LogicNodeType::Term when LogicNodeType::And # and is only valid if only contains literals node_children.all? do |child| [ child.type == LogicNodeType::True, child.type == LogicNodeType::False, child.type == LogicNodeType::Term, ((child.type == LogicNodeType::Not) && \ child.node_children.fetch(0).type == LogicNodeType::Term) ] end when LogicNodeType::Or, LogicNodeType::Xor, LogicNodeType::If, LogicNodeType::None false else T.absurd(@type) end end |
#do_to_eqntott(tree, term_map) ⇒ String
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 |
# File 'lib/udb/logic.rb', line 3151 def do_to_eqntott(tree, term_map) t = tree.type case t when LogicNodeType::True "1" when LogicNodeType::False "0" when LogicNodeType::And "(#{tree.node_children.map { |child| do_to_eqntott(child, term_map) }.join(" & ")})" when LogicNodeType::Or "(#{tree.node_children.map { |child| do_to_eqntott(child, term_map) }.join(" | ")})" when LogicNodeType::Xor do_to_eqntott(tree.nnf, term_map) when LogicNodeType::None do_to_eqntott(LogicNode.new(LogicNodeType::Not, [LogicNode.new(LogicNodeType::Or, tree.children)]), term_map) when LogicNodeType::Term term_map.fetch(T.cast(tree.children.fetch(0), TermType)) when LogicNodeType::Not "!(#{do_to_eqntott(tree.node_children.fetch(0), term_map)})" when LogicNodeType::If do_to_eqntott(tree.nnf, term_map) else T.absurd(t) end end |
#eql?(other) ⇒ Boolean
3625 3626 3627 3628 3629 |
# File 'lib/udb/logic.rb', line 3625 def eql?(other) return false unless other.is_a?(LogicNode) to_h.eql?(other.to_h) end |
#equisat_cnf ⇒ LogicNode
coverts self to an equisatisfiable formula in Conjunctive Normal Form and returns it as a new formula (self is unmodified)
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 |
# File 'lib/udb/logic.rb', line 2769 def equisat_cnf return @memo.equisat_cnf unless @memo.equisat_cnf.nil? return self if @type == LogicNodeType::True return self if @type == LogicNodeType::False # strategy: try conversion using Demorgan's laws first. If that appears to be getting too # large (exponential in the worst case), fall back on the tseytin transformation @memo.equisat_cnf = if @memo.equiv_cnf.nil? if terms.count > 4 || literals.count > 10 tseytin else # try demorgan first, then fall back if it gets too big begin equiv_cnf rescue SizeExplosion tseytin end end else # we already calculated an equivalent cnf, which is also equisatisfiable @mem.equiv_cnf end end |
#equisatisfiable?(other, cfg_arch) ⇒ Boolean
3094 3095 3096 3097 3098 3099 3100 |
# File 'lib/udb/logic.rb', line 3094 def equisatisfiable?(other, cfg_arch) if satisfiable?(cfg_arch) other.satisfiable?(cfg_arch) else !other.satisfiable?(cfg_arch) end end |
#equiv_cnf(raise_on_explosion: true) ⇒ LogicNode
coverts self to an equivalent formula in Conjunctive Normal Form and returns it as a new formula (self is unmodified)
iteratively uses Demorgan’s Laws. May explode since the worst case is exponential in the number of clauses
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 |
# File 'lib/udb/logic.rb', line 2745 def equiv_cnf(raise_on_explosion: true) @memo.equiv_cnf ||= begin r = reduce return r if r.type == LogicNodeType::True || r.type == LogicNodeType::False n = r.nnf candidate = n.reduce candidate = n.group_by_2 unflattened = do_equiv_cnf(candidate, raise_on_explosion:) result = flatten_cnf(unflattened).reduce if result.frozen? raise "?" unless result.memo.is_cnf == true else result.memo.is_cnf = true end result end end |
#equivalent?(other, cfg_arch) ⇒ Boolean
Returns true iff self and other are logically equivalent (identical truth tables).
3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 |
# File 'lib/udb/logic.rb', line 3104 def equivalent?(other, cfg_arch) # equivalent (A <=> B) if the biconditional is true: # (A -> B) && (B -> A) # or, expressed without implication: # (!A || B) && (!B || A) # equivalence is a tautology iff ~(A <=> B) is a contradiction, # i.e., !(A <=> B) is UNSATISFIABLE # !((!A || B) && (!B || A)) is UNSATISFIABLE r = self other = other contradiction = LogicNode.new( LogicNodeType::Not, [ LogicNode.new( LogicNodeType::And, [ LogicNode.new( LogicNodeType::Or, [ LogicNode.new(LogicNodeType::Not, [r]), other ] ), LogicNode.new( LogicNodeType::Or, [ LogicNode.new(LogicNodeType::Not, [r]), self ] ) ] ) ] ) contradiction.unsatisfiable?(cfg_arch) end |
#espresso(result_type, exact) ⇒ LogicNode
minimize the function using espresso
3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 |
# File 'lib/udb/logic.rb', line 3478 def espresso(result_type, exact) nterms = terms.size pla = if nterms > 4 || literals.size >= 32 eqn_result = if result_type == CanonicalizationType::SumOfProducts to_eqntott elsif result_type == CanonicalizationType::ProductOfSums LogicNode.new(LogicNodeType::Not, [self]).to_eqntott else T.absurd(result_type) end tt = T.let(nil, T.nilable(String)) Tempfile.open do |f| f.write <<~FILE NAME=f; #{eqn_result.eqn}; FILE f.flush tt = `eqntott -l #{f.path}` unless $?.success? raise "eqntott failure" end end if T.must(tt).lines.any? { |l| l =~ /^\.p 0/ } if result_type == CanonicalizationType::SumOfProducts # short circuit here, it's trivially false return LogicNode.new(LogicNodeType::False, []) else # short circuit here, it's trivially true return LogicNode.new(LogicNodeType::True, []) end end tt else term_idx = T.let({}, T::Hash[TermType, Integer]) terms.each_with_index do |term, idx| term_idx[term] = idx end # define the callback outside the loop to avoid allocating a new block on every iteration val_out_of_loop = 0 cb = LogicNode.make_eval_cb do |term| ((val_out_of_loop >> term_idx.fetch(term)) & 1).zero? ? SatisfiedResult::No : SatisfiedResult::Yes end tt = T.let([], T::Array[T::Array[String]]) (1 << nterms).times do |val| val_out_of_loop = val if result_type == CanonicalizationType::SumOfProducts if eval_cb(cb) == SatisfiedResult::Yes tt << [val.to_s(2).rjust(nterms, "0").reverse, "1"] else tt << [val.to_s(2).rjust(nterms, "0").reverse, "0"] end elsif result_type == CanonicalizationType::ProductOfSums if eval_cb(cb) == SatisfiedResult::Yes tt << [val.to_s(2).rjust(nterms, "0").reverse, "0"] else tt << [val.to_s(2).rjust(nterms, "0").reverse, "1"] end end end <<~INFILE .i #{nterms} .o 1 .na f .ob out .p #{tt.size} #{tt.map { |t| t.join(" ") }.join("\n")} INFILE end Tempfile.open do |f| f.write pla f.flush cmd = if exact "espresso -Dsignature #{f.path}" else "espresso -efast #{f.path}" end result = `#{cmd} 2>&1` unless $?.success? raise "espresso failure\n#{result}" end sop_terms = [] always_true = T.let(false, T::Boolean) result.lines.each_with_index do |line, idx| next if line[0] == "." next if line[0] == "#" if line =~ /^([01\-]{#{terms.size}}) 1/ term = $1 conjunction_kids = [] terms.size.times do |i| if term[i] == "1" conjunction_kids << LogicNode.new(LogicNodeType::Term, [terms.fetch(i)]) elsif term[i] == "0" conjunction_kids << LogicNode.new(LogicNodeType::Not, [LogicNode.new(LogicNodeType::Term, [terms.fetch(i)])]) else raise "unexpected" unless term[i] == "-" end end if conjunction_kids.size == 1 sop_terms << conjunction_kids.fetch(0) elsif conjunction_kids.size > 0 sop_terms << LogicNode.new(LogicNodeType::And, conjunction_kids) else # always true always_true = true end end end sop = if sop_terms.size == 1 sop_terms.fetch(0) elsif sop_terms.size > 0 LogicNode.new(LogicNodeType::Or, sop_terms) else always_true ? LogicNode.new(LogicNodeType::True, []) : LogicNode.new(LogicNodeType::False, []) end if result_type == CanonicalizationType::SumOfProducts sop else # result is actually !result, so negate it and then distribute LogicNode.new(LogicNodeType::Not, [sop]).distribute_not end end end |
#eval_cb(callback) ⇒ SatisfiedResult
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 |
# File 'lib/udb/logic.rb', line 1682 def eval_cb(callback) case @type when LogicNodeType::True SatisfiedResult::Yes when LogicNodeType::False SatisfiedResult::No when LogicNodeType::Term child = T.cast(@children.fetch(0), TermType) callback.call(child) when LogicNodeType::If cond_ext_ret = node_children.fetch(0) res = cond_ext_ret.eval_cb(callback) if res == SatisfiedResult::Yes node_children.fetch(1).eval_cb(callback) elsif res == SatisfiedResult::Maybe ## if "then" is true, then res doesn't matter.... node_children.fetch(1).eval_cb(callback) == SatisfiedResult::Yes \ ? SatisfiedResult::Yes : SatisfiedResult::Maybe else # if antecedent is false, implication is true SatisfiedResult::Yes end when LogicNodeType::Not res = node_children.fetch(0).eval_cb(callback) case res when SatisfiedResult::Yes SatisfiedResult::No when SatisfiedResult::No SatisfiedResult::Yes when SatisfiedResult::Maybe SatisfiedResult::Maybe else T.absurd(res) end when LogicNodeType::And yes_cnt = T.let(0, Integer) node_children.each do |child| res1 = child.eval_cb(callback) if res1 == SatisfiedResult::No return SatisfiedResult::No end if res1 == SatisfiedResult::Yes yes_cnt += 1 end end if yes_cnt == node_children.size SatisfiedResult::Yes else SatisfiedResult::Maybe end when LogicNodeType::Or no_cnt = 0 node_children.each do |child| res1 = child.eval_cb(callback) return SatisfiedResult::Yes if res1 == SatisfiedResult::Yes no_cnt += 1 if res1 == SatisfiedResult::No end if no_cnt == node_children.size SatisfiedResult::No else SatisfiedResult::Maybe end when LogicNodeType::None no_cnt = 0 node_children.each do |child| res1 = child.eval_cb(callback) return SatisfiedResult::No if res1 == SatisfiedResult::Yes no_cnt += 1 if res1 == SatisfiedResult::No end if no_cnt == node_children.size SatisfiedResult::Yes else SatisfiedResult::Maybe end when LogicNodeType::Xor yes_cnt = T.let(0, Integer) has_maybe = T.let(false, T::Boolean) node_children.each do |child| res1 = child.eval_cb(callback) has_maybe ||= (res1 == SatisfiedResult::Maybe) yes_cnt += 1 if res1 == SatisfiedResult::Yes if yes_cnt > 1 return SatisfiedResult::No end end if yes_cnt == 1 && !has_maybe SatisfiedResult::Yes elsif has_maybe SatisfiedResult::Maybe else SatisfiedResult::No end else T.absurd(@type) end end |
#from_dimacs(dimacs) ⇒ LogicNode
3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 |
# File 'lib/udb/logic.rb', line 3389 def from_dimacs(dimacs) nodes = dimacs.each_line.map do |line| if line =~ /^(((-?\d+) )+)0/ ts = T.let($1.strip.split(" "), T::Array[String]) if ts.size == 1 t = ts.fetch(0) if t[0] == "-" index = t[1..].to_i - 1 LogicNode.new( LogicNodeType::Not, [LogicNode.new(LogicNodeType::Term, [terms.fetch(index)])] ) else index = t.to_i - 1 LogicNode.new(LogicNodeType::Term, [terms.fetch(index)]) end else LogicNode.new(LogicNodeType::Or, ts.map do |t| if t[0] == "-" i = t[1..].to_i - 1 LogicNode.new( LogicNodeType::Not, [LogicNode.new(LogicNodeType::Term, [terms.fetch(i)])] ) else i = t.to_i - 1 LogicNode.new(LogicNodeType::Term, [terms.fetch(i)]) end end ) end else nil end end.compact if nodes.size == 1 nodes.fetch(0) else LogicNode.new(LogicNodeType::And, nodes) end end |
#group_by_2 ⇒ LogicNode
Returns rewrites the tree so that no node has more than 2 children.
2366 2367 2368 |
# File 'lib/udb/logic.rb', line 2366 def group_by_2 do_group_by_2(self) end |
#grouped_by_2?(node) ⇒ Boolean
does each node have at most two children?
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 |
# File 'lib/udb/logic.rb', line 2341 def grouped_by_2?(node) t = node.type case t when LogicNodeType::And, LogicNodeType::Or node.children.size == 2 && \ grouped_by_2?(node.node_children.fetch(0)) && \ grouped_by_2?(node.node_children.fetch(1)) when LogicNodeType::Not grouped_by_2?(node.node_children.fetch(0)) when LogicNodeType::Term true when LogicNodeType::None, LogicNodeType::If, LogicNodeType::Xor raise "?" when LogicNodeType::True, LogicNodeType::False true else T.absurd(t) end end |
#hash ⇒ Integer
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 |
# File 'lib/udb/logic.rb', line 1877 def hash if @type == LogicNodeType::True true.hash elsif @type == LogicNodeType::False false.hash elsif @type == LogicNodeType::Term @children[0].to_s.hash elsif @type == LogicNodeType::Not [:not, node_children.fetch(0).hash].hash elsif @type == LogicNodeType::And [:and, node_children.map(&:hash)].hash elsif @type == LogicNodeType::Or [:or, node_children.map(&:hash)].hash elsif @type == LogicNodeType::Xor [:xor, node_children.map(&:hash)].hash elsif @type == LogicNodeType::None [:none, node_children.map(&:hash)].hash elsif @type == LogicNodeType::If [:if, node_children.map(&:hash)].hash else T.absurd(@type) end end |
#literals ⇒ Array<TermType>
unlike #terms, this list will include leaves that are equivalent
1369 1370 1371 1372 1373 1374 1375 1376 |
# File 'lib/udb/logic.rb', line 1369 def literals @memo.literals ||= if @type == LogicNodeType::Term [@children.fetch(0)] else node_children.map { |child| child.literals }.flatten end end |
#minimal_unsat_subsets ⇒ Array<LogicNode>
return minimally unsatisfiable subsets of the unstatisfiable formula
3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 |
# File 'lib/udb/logic.rb', line 3435 def minimal_unsat_subsets r = reduce c = r.equiv_cnf(raise_on_explosion: false) Tempfile.create(%w/formula .cnf/) do |f| f.write c.to_dimacs f.flush Tempfile.create do |rf| # run must, re-use the tempfile for the result `must -o #{rf.path} #{f.path}` unless $?.success? raise "could not find minimal subsets" end rf.rewind result = rf.read mus_dimacs = T.let([], T::Array[String]) cur_dimacs = T.let(nil, T.nilable(String)) result.each_line do |line| if line =~ /MUS #\d+/ mus_dimacs << cur_dimacs unless cur_dimacs.nil? cur_dimacs = "" else cur_dimacs = T.must(cur_dimacs) + line end end mus_dimacs << T.must(cur_dimacs) return mus_dimacs.map { |d| c.from_dimacs(d) } end end end |
#minimize(result_type) ⇒ LogicNode
convert to either sum-of-products form or product-of-sums form and minimize the result
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 |
# File 'lib/udb/logic.rb', line 1632 def minimize(result_type) if terms.size <= 4 quine_mccluskey(result_type) else # special-case check for when the formula is large but obviously already minimized # added this because espresso runtime for Shcounterenw requirements was painfully long if result_type == CanonicalizationType::ProductOfSums && terms.size > 32 && nnf.nested_cnf? && terms.size == literals.size equiv_cnf else espresso(result_type, true) end end end |
#nested_cnf? ⇒ Boolean
returns true iff tree, if flattened, would be cnf allows nested ANDs as long as there is no ancestor OR allows nested ORs as long as there is no decendent AND
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 |
# File 'lib/udb/logic.rb', line 2956 def nested_cnf? unless @memo.is_nested_cnf.nil? return @memo.is_nested_cnf end ret = case @type when LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False true when LogicNodeType::Not node_children.fetch(0).type == LogicNodeType::Term when LogicNodeType::And node_children.all? do |child| child.nested_cnf_conjunction_term?(false) end when LogicNodeType::Or # or is only valid if only it recursively contains only literals or disjunctions node_children.all? do |child| [ child.type == LogicNodeType::True, child.type == LogicNodeType::False, child.type == LogicNodeType::Term, ((child.type == LogicNodeType::Not) && \ child.node_children.fetch(0).type == LogicNodeType::Term), child.type == LogicNodeType::Or && \ child.node_children.all? { |grandchild| grandchild.nested_cnf_conjunction_term?(true) } ].any? end when LogicNodeType::Xor, LogicNodeType::If, LogicNodeType::None false else T.absurd(@type) end @memo.is_nested_cnf = ret end |
#nested_cnf_conjunction_term?(ancestor_or) ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
returns true iff tree is a valid term in a nested cnf conjunction
2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 |
# File 'lib/udb/logic.rb', line 2912 def nested_cnf_conjunction_term?(ancestor_or) case @type when LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False true when LogicNodeType::Not node_children.fetch(0).type == LogicNodeType::Term when LogicNodeType::Or node_children.all? do |child| [ child.type == LogicNodeType::True, child.type == LogicNodeType::False, child.type == LogicNodeType::Term, ((child.type == LogicNodeType::Not) && \ child.node_children.fetch(0).type == LogicNodeType::Term), child.type == LogicNodeType::Or && child.nested_cnf_conjunction_term?(true) ].any? end when LogicNodeType::And return false if ancestor_or node_children.all? do |child| [ child.type == LogicNodeType::True, child.type == LogicNodeType::False, child.type == LogicNodeType::Term, ((child.type == LogicNodeType::Not) && \ child.node_children.fetch(0).type == LogicNodeType::Term), (child.type == LogicNodeType::Or && \ child.nested_cnf_conjunction_term?(true)), (child.type == LogicNodeType::And && \ child.nested_cnf_conjunction_term?(ancestor_or)) ].any? end when LogicNodeType::Xor, LogicNodeType::If, LogicNodeType::None false else T.absurd(@type) end end |
#nnf ⇒ LogicNode
Returns self, converted to Negation Normal Form.
2212 2213 2214 |
# File 'lib/udb/logic.rb', line 2212 def nnf do_nnf(self) end |
#nnf? ⇒ Boolean
Returns true iff self is in Negation Normal Form.
2217 2218 2219 2220 2221 2222 2223 2224 2225 |
# File 'lib/udb/logic.rb', line 2217 def nnf? if @type == LogicNodeType::Not node_children.fetch(0).type == LogicNodeType::Term elsif @type == LogicNodeType::Term true else node_children.all? { |child| child.nnf? } end end |
#node_children ⇒ Array<LogicNode>
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
1294 1295 1296 |
# File 'lib/udb/logic.rb', line 1294 def node_children @node_children end |
#partial_evaluate(cb) ⇒ LogicNode
partially evalute – replace anything known with true/false, and otherwise leave it alone
1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 |
# File 'lib/udb/logic.rb', line 1786 def partial_evaluate(cb) case @type when LogicNodeType::Term res = cb.call(T.cast(@children.fetch(0), TermType)) if res == SatisfiedResult::Yes True elsif res == SatisfiedResult::No False else self end else LogicNode.new(@type, node_children.map { |child| child.partial_evaluate(cb) }) end end |
#reduce ⇒ LogicNode
reduce the equation by removing easy identities:
(A || B || .. || true) => true (A || B || .. || Z || !Z) => true (A && B && .. && false) => false (A && B && .. && Z && !Z) => false NONE(A, B, …, true) => false false -> A => true true -> A => A
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 |
# File 'lib/udb/logic.rb', line 2597 def reduce unless @memo.is_reduced.nil? raise "?" unless @memo.is_reduced == true return self end reduced = case @type when LogicNodeType::And reduced = LogicNode.new(LogicNodeType::And, node_children.map { |child| child.reduce }) # see if there is a false term or a contradiction (a && !a) # if so, reduce to false must_be_false = reduced.node_children.any? do |child| # a false anywhere will make the conjunction false child.type == LogicNodeType::False || # a contradiction (a && !a) will make the conjunction false (child.type == LogicNodeType::Term && reduced.node_children.any? do |other_child| other_child.type == LogicNodeType::Not && \ other_child.node_children.fetch(0).type == LogicNodeType::Term && \ child.children.fetch(0) == other_child.node_children.fetch(0).children.fetch(0) end) end if must_be_false False else # eliminate True true_reduced_children = reduced.node_children.reject { |c| c.type == LogicNodeType::True } if true_reduced_children.size != reduced.children.size reduced = if true_reduced_children.size == 0 True elsif true_reduced_children.size == 1 true_reduced_children.fetch(0) else LogicNode.new(LogicNodeType::And, true_reduced_children) end end reduced end when LogicNodeType::Or reduced = LogicNode.new(LogicNodeType::Or, node_children.map { |child| child.reduce }) # see if there is a true term or a tautology (a || !a) # if so, reduce to true must_be_true = reduced.node_children.any? do |child| # a true anywhere will make the disjunction true child.type == LogicNodeType::True || # a tautology (a || !a) will make the disjunction true (child.type == LogicNodeType::Term && reduced.node_children.any? do |other_child| other_child.type == LogicNodeType::Not && \ other_child.node_children.fetch(0).type == LogicNodeType::Term && \ child.children.fetch(0) == other_child.node_children.fetch(0).children.fetch(0) end) end if must_be_true True else # eliminate False false_reduced_children = reduced.node_children.reject { |c| c.type == LogicNodeType::False } if false_reduced_children.size != reduced.children.size reduced = if false_reduced_children.size == 0 False elsif false_reduced_children.size == 1 false_reduced_children.fetch(0) else LogicNode.new(LogicNodeType::Or, false_reduced_children) end end reduced end when LogicNodeType::Xor reduced = LogicNode.new(LogicNodeType::Xor, node_children.map { |child| child.reduce }) xor_with_self = reduced.children.size == 2 && reduced.node_children.fetch(0).type == LogicNodeType::Term && reduced.node_children.fetch(1).type == LogicNodeType::Term && reduced.node_children.fetch(0).children.fetch(0) == reduced.node_children.fetch(1).children.fetch(0) if xor_with_self # xor with self if always false False else reduced end when LogicNodeType::If reduced = LogicNode.new(LogicNodeType::If, node_children.map { |child| child.reduce }) antecedent = reduced.node_children.fetch(0) consequent = reduced.node_children.fetch(1) if antecedent.type == LogicNodeType::True consequent elsif antecedent.type == LogicNodeType::False return True elsif consequent.type == LogicNodeType::True return True elsif consequent.type == LogicNodeType::False return LogicNode.new(LogicNodeType::Not, [antecedent]) else reduced end when LogicNodeType::Not reduced = LogicNode.new(LogicNodeType::Not, node_children.map { |child| child.reduce }) child = reduced.node_children.fetch(0) if child.type == LogicNodeType::Not # !!a = a reduced.node_children.fetch(0).node_children.fetch(0) elsif child.type == LogicNodeType::False # !false = true return True elsif child.type == LogicNodeType::True # !true = false return False else reduced end when LogicNodeType::None if node_children.any? { |c| c.type == LogicNodeType::True } True else self.dup end when LogicNodeType::True, LogicNodeType::False, LogicNodeType::Term self else T.absurd(@type) end if reduced.memo.is_reduced.nil? reduced.memo.is_reduced = true end reduced end |
#replace_terms(callback) ⇒ LogicNode
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 |
# File 'lib/udb/logic.rb', line 1664 def replace_terms(callback) case @type when LogicNodeType::True, LogicNodeType::False self when LogicNodeType::Term callback.call(self) when LogicNodeType::If, LogicNodeType::Not, LogicNodeType::And, LogicNodeType::Or, LogicNodeType::None, LogicNodeType::Xor LogicNode.new( @type, node_children.map { |c| c.replace_terms(callback) } ) else T.absurd(@type) end end |
#satisfiability_depends_on_ext_req?(ext_req) ⇒ Boolean
If ext_req is false, can this logic tree be satisfied?
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 |
# File 'lib/udb/logic.rb', line 1321 def satisfiability_depends_on_ext_req?(ext_req) # the tree needs something in ext_vers if it is always # unsatisfiable when the corresponding ExtensionTerms are false cb = LogicNode.make_eval_cb do |term| case term when ExtensionTerm ext_req.satisfied_by?(term.to_ext_req(ext_req.cfg_arch)) \ ? SatisfiedResult::No : SatisfiedResult::Maybe when ParameterTerm SatisfiedResult::Maybe when FreeTerm SatisfiedResult::No when XlenTerm SatisfiedResult::Maybe else T.absurd(term) end end eval_cb(cb) == SatisfiedResult::No end |
#satisfiable?(cfg_arch) ⇒ Boolean
Returns true iff self is satisfiable (possible to be true for some combination of term values).
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 |
# File 'lib/udb/logic.rb', line 3041 def satisfiable?(cfg_arch) @memo.is_satisfiable ||= begin nterms = terms.size if nterms < 8 && literals.size <= 128 # just brute force it LogicNode.inc_brute_force_sat_solves term_idx = T.let({}, T::Hash[TermType, Integer]) terms.each_with_index do |term, idx| term_idx[term] = idx end # define the callback outside the loop to avoid allocating a new block on every iteration val_out_of_loop = 0 cb = LogicNode.make_eval_cb do |term| ((val_out_of_loop >> term_idx.fetch(term)) & 1).zero? ? SatisfiedResult::No : SatisfiedResult::Yes end if nterms.zero? return eval_cb(cb) == SatisfiedResult::Yes else (2**nterms).to_i.times do |i| val_out_of_loop = i if eval_cb(cb) == SatisfiedResult::Yes return true end end end return false else # use SAT solver LogicNode.inc_z3_sat_solves @@cache ||= {} cache_key = [hash, cfg_arch.hash].hash if @@cache.key?(cache_key) LogicNode.inc_z3_cache_hits return @@cache[cache_key] end solver = Z3Solver.new solver.assert to_z3(cfg_arch, solver) @@cache[cache_key] = solver.satisfiable? end end end |
#terms ⇒ Array<TermType>
Returns The unique terms (leafs) of this tree.
1345 1346 1347 1348 1349 1350 1351 1352 |
# File 'lib/udb/logic.rb', line 1345 def terms @memo.terms ||= begin t = literals.uniq raise "Problem with parameter hashing\n#{t.map(&:to_s).uniq}\n#{t.map(&:to_s)}" unless t.map(&:to_s).uniq == t.map(&:to_s) t end end |
#terms_no_antecendents ⇒ Array<TermType>
Returns The unique terms (leafs) of this tree, exculding antecendents of an IF.
1356 1357 1358 1359 1360 1361 1362 1363 1364 |
# File 'lib/udb/logic.rb', line 1356 def terms_no_antecendents if @type == LogicNodeType::If node_children.fetch(1).terms_no_antecendents elsif @type == LogicNodeType::Term [T.cast(@children.fetch(0), TermType)] else node_children.map { |child| child.terms_no_antecendents }.flatten.uniq end end |
#to_asciidoc(include_versions:) ⇒ String
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 |
# File 'lib/udb/logic.rb', line 1964 def to_asciidoc(include_versions:) case @type when LogicNodeType::Term term = T.cast(children.fetch(0), TermType) if term.is_a?(ExtensionTerm) if include_versions "`#{term.name}`#{term.comparison}#{term.version.canonical}" else "`#{term.name}`" end elsif term.is_a?(ParameterTerm) term.to_asciidoc elsif term.is_a?(FreeTerm) raise "Should not occur" elsif term.is_a?(XlenTerm) term.to_asciidoc else T.absurd(term) end when LogicNodeType::False "false" when LogicNodeType::True "true" when LogicNodeType::Not if node_children.fetch(0).type == LogicNodeType::Term term = node_children.fetch(0).children.fetch(0) if term.is_a?(ParameterTerm) negation = term.negate unless negation.nil? return negation.to_asciidoc end end end "!#{node_children.fetch(0).to_asciidoc(include_versions:)}" when LogicNodeType::And "++(++#{node_children.map { |c| c.to_asciidoc(include_versions:) }.join(" && ")})" when LogicNodeType::Or "++(++#{node_children.map { |c| c.to_asciidoc(include_versions:) }.join(" pass:[||] ")})" when LogicNodeType::If "++(++#{node_children.fetch(0).to_asciidoc(include_versions:)} -> #{node_children.fetch(1).to_asciidoc(include_versions:)})" when LogicNodeType::Xor "++(++#{node_children.map { |c| c.to_asciidoc(include_versions:) }.join(" ࣷ ")})" when LogicNodeType::None "!++(++#{node_children.map { |c| c.to_asciidoc(include_versions:) }.join(" pass:[||] ")})" else T.absurd(@type) end end |
#to_dimacs ⇒ String
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 |
# File 'lib/udb/logic.rb', line 3348 def to_dimacs if @type == LogicNodeType::Term <<~DIMACS p cnf 1 1 1 0 DIMACS elsif @type == LogicNodeType::Not && node_children.fetch(0).type == LogicNodeType::Term <<~DIMACS p cnf 1 1 -1 0 DIMACS elsif @type == LogicNodeType::True || @type == LogicNodeType::False raise "Cannot represent true/false in DIMACS" elsif @type == LogicNodeType::And lines = ["p cnf #{terms.size} #{@children.size}"] lines += node_children.map do |child| if child.type == LogicNodeType::Or term_line = child.node_children.map do |grandchild| if grandchild.type == LogicNodeType::Not (-(T.must(terms.index(grandchild.node_children.fetch(0).node_children.fetch(0))) + 1)).to_s elsif grandchild.type == LogicNodeType::Term (T.must(terms.index(grandchild.node_children.fetch(0))) + 1).to_s end end.join(" ") "#{term_line} 0" elsif child.type == LogicNodeType::Term "#{T.must(terms.index(child.children.fetch(0))) + 1} 0" elsif child.type == LogicNodeType::Not "-#{T.must(terms.index(child.node_children.fetch(0).children.fetch(0))) + 1} 0" else raise "Not CNF" end end lines.join("\n") else raise "Not CNF" end end |
#to_eqntott ⇒ EqntottResult
return equation suitable for eqntott input
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 |
# File 'lib/udb/logic.rb', line 3184 def to_eqntott next_term_name = "a" term_map = T.let({}, T::Hash[TermType, String]) t = terms t.each do |term| unless term_map.key?(term) term_map[term] = next_term_name next_term_name = next_term_name.next end end EqntottResult.new(eqn: "out = #{do_to_eqntott(self, term_map)}", term_map: term_map.invert) end |
#to_h(term_determined = false) ⇒ Boolean, Hash{String => T.untyped}
convert to a UDB schema
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 |
# File 'lib/udb/logic.rb', line 2039 def to_h(term_determined = false) if @type == LogicNodeType::True true elsif @type == LogicNodeType::False false elsif @type == LogicNodeType::Term if term_determined @children.fetch(0).to_h else child = T.cast(@children.fetch(0), TermType) case child when ExtensionTerm { "extension" => @children.fetch(0).to_h } when ParameterTerm { "param" => @children.fetch(0).to_h } when FreeTerm { "free" => child.id } # only needed for #hash when XlenTerm @children.fetch(0).to_h else T.absurd(child) end end elsif @type == LogicNodeType::Not child = node_children.fetch(0) if !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ExtensionTerm) } { "extension" => { "not" => child.to_h(true) } } elsif !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ParameterTerm) } { "param" => { "not" => child.to_h(true) } } else { "not" => child.to_h(term_determined) } end elsif @type == LogicNodeType::And if !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ExtensionTerm) } { "extension" => { "allOf" => node_children.map { |child| child.to_h(true) } } } elsif !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ParameterTerm) } { "param" => { "allOf" => node_children.map { |child| child.to_h(true) } } } else { "allOf" => node_children.map { |child| child.to_h(term_determined) } } end elsif @type == LogicNodeType::Or if !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ExtensionTerm) } { "extension" => { "anyOf" => node_children.map { |child| child.to_h(true) } } } elsif !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ParameterTerm) } { "param" => { "anyOf" => node_children.map { |child| child.to_h(true) } } } else { "anyOf" => node_children.map { |child| child.to_h(term_determined) } } end elsif @type == LogicNodeType::Xor if !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ExtensionTerm) } { "extension" => { "oneOf" => node_children.map { |child| child.to_h(true) } } } elsif !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ParameterTerm) } { "param" => { "oneOf" => node_children.map { |child| child.to_h(true) } } } else { "oneOf" => node_children.map { |child| child.to_h(term_determined) } } end elsif @type == LogicNodeType::None if !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ExtensionTerm) } { "extension" => { "noneOf" => node_children.map { |child| child.to_h(true) } } } elsif !term_determined && terms_no_antecendents.all? { |term| term.is_a?(ParameterTerm) } { "param" => { "noneOf" => node_children.map { |child| child.to_h(true) } } } else { "noneOf" => node_children.map { |child| child.to_h(term_determined) } } end elsif @type == LogicNodeType::If { "if" => node_children.fetch(0).to_h(false), "then" => node_children.fetch(1).to_h(term_determined) } else T.absurd(@type) end end |
#to_idl(cfg_arch) ⇒ String
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 |
# File 'lib/udb/logic.rb', line 2014 def to_idl(cfg_arch) case @type when LogicNodeType::True "true" when LogicNodeType::False "false" when LogicNodeType::Term T.cast(@children.fetch(0), TermType).to_idl(cfg_arch) when LogicNodeType::Not "!#{node_children.fetch(0).to_idl(cfg_arch)}" when LogicNodeType::And "(#{node_children.map { |c| c.to_idl(cfg_arch) }.join(" && ") })" when LogicNodeType::Or "(#{node_children.map { |c| c.to_idl(cfg_arch) }.join(" || ")})" when LogicNodeType::Xor, LogicNodeType::None nnf.to_idl(cfg_arch) when LogicNodeType::If "(!(#{node_children.fetch(0).to_idl(cfg_arch)}) || (#{node_children.fetch(1).to_idl(cfg_arch)}))" else T.absurd(@type) end end |
#to_s(format: LogicSymbolFormat::Predicate) ⇒ String
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 |
# File 'lib/udb/logic.rb', line 1902 def to_s(format: LogicSymbolFormat::Predicate) if @type == LogicNodeType::True LOGIC_SYMBOLS[format][:TRUE] elsif @type == LogicNodeType::False LOGIC_SYMBOLS[format][:FALSE] elsif @type == LogicNodeType::Term @children[0].to_s elsif @type == LogicNodeType::Not "#{LOGIC_SYMBOLS[format][:NOT]}#{node_children.fetch(0).to_s(format:)}" elsif @type == LogicNodeType::And "(#{node_children.map { |c| c.to_s(format:) }.join(" #{LOGIC_SYMBOLS[format][:AND]} ")})" elsif @type == LogicNodeType::Or "(#{node_children.map { |c| c.to_s(format:) }.join(" #{LOGIC_SYMBOLS[format][:OR]} ")})" elsif @type == LogicNodeType::Xor "(#{node_children.map { |c| c.to_s(format:) }.join(" #{LOGIC_SYMBOLS[format][:XOR]} ")})" elsif @type == LogicNodeType::None "#{LOGIC_SYMBOLS[format][:NOT]}(#{node_children.map { |c| c.to_s(format:) }.join(" #{LOGIC_SYMBOLS[format][:OR]} ")})" elsif @type == LogicNodeType::If "(#{node_children.fetch(0).to_s(format:)} #{LOGIC_SYMBOLS[format][:IMPLIES]} #{node_children.fetch(1).to_s(format:)})" else T.absurd(@type) end end |
#to_s_pretty ⇒ String
return a nice, human-readable form that may gloss over details
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 |
# File 'lib/udb/logic.rb', line 1852 def to_s_pretty if @type == LogicNodeType::True "true" elsif @type == LogicNodeType::False "false" elsif @type == LogicNodeType::Term @children.fetch(0).to_s_pretty elsif @type == LogicNodeType::Not "not #{@children.fetch(0).to_s_pretty}" elsif @type == LogicNodeType::And "(#{node_children.map { |c| c.to_s_pretty }.join(" and ")})" elsif @type == LogicNodeType::Or "(#{node_children.map { |c| c.to_s_pretty }.join(" or ")})" elsif @type == LogicNodeType::Xor "(#{node_children.map { |c| c.to_s_pretty }.join(" xor ")})" elsif @type == LogicNodeType::None "none of (#{node_children.map { |c| c.to_s_pretty }.join(", ")})" elsif @type == LogicNodeType::If "if #{node_children.fetch(0).to_s_pretty} then #{node_children.fetch(1).to_s_pretty})" else T.absurd(@type) end end |
#to_s_with_value(callback, format: LogicSymbolFormat::Predicate) ⇒ String
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 |
# File 'lib/udb/logic.rb', line 1927 def to_s_with_value(callback, format: LogicSymbolFormat::Predicate) if @type == LogicNodeType::True LOGIC_SYMBOLS[format][:TRUE] elsif @type == LogicNodeType::False LOGIC_SYMBOLS[format][:FALSE] elsif @type == LogicNodeType::Term v = callback.call(T.cast(@children.fetch(0), TermType)) str = case v when SatisfiedResult::Yes "{true}" when SatisfiedResult::No "{false}" when SatisfiedResult::Maybe "{unknown}" else T.absurd(v) end "`#{@children.fetch(0)}`#{str}" elsif @type == LogicNodeType::Not "#{LOGIC_SYMBOLS[format][:NOT]}#{node_children.fetch(0).to_s_with_value(callback, format:)}" elsif @type == LogicNodeType::And "(#{node_children.map { |c| c.to_s_with_value(callback, format:) }.join(" #{LOGIC_SYMBOLS[format][:AND]} ")})" elsif @type == LogicNodeType::Or "(#{node_children.map { |c| c.to_s_with_value(callback, format:) }.join(" #{LOGIC_SYMBOLS[format][:OR]} ")})" elsif @type == LogicNodeType::Xor "(#{node_children.map { |c| c.to_s_with_value(callback, format:) }.join(" #{LOGIC_SYMBOLS[format][:XOR]} ")})" elsif @type == LogicNodeType::None "#{LOGIC_SYMBOLS[format][:NOT]}(#{node_children.map { |c| c.to_s_with_value(callback, format:) }.join(" #{LOGIC_SYMBOLS[format][:OR]} ")})" elsif @type == LogicNodeType::If "(#{node_children.fetch(0).to_s_with_value(callback, format:)} #{LOGIC_SYMBOLS[format][:IMPLIES]} #{node_children.fetch(1).to_s_with_value(callback, format:)})" else T.absurd(@type) end end |
#to_z3(cfg_arch, solver = Z3Solver.new) ⇒ Z3::BoolExpr
2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 |
# File 'lib/udb/logic.rb', line 2993 def to_z3(cfg_arch, solver = Z3Solver.new) case @type when LogicNodeType::Term t = @children.fetch(0) if t.is_a?(ParameterTerm) || t.is_a?(ExtensionTerm) t.to_z3(solver, cfg_arch) elsif t.is_a?(FreeTerm) t.to_z3 else raise "unexpected #{self}" if t.is_a?(LogicNode) t.to_z3(solver) end when LogicNodeType::Or T.unsafe(Z3).Or(*node_children.map { |c| c.to_z3(cfg_arch, solver) }) when LogicNodeType::And T.unsafe(Z3).And(*node_children.map { |c| c.to_z3(cfg_arch, solver) }) when LogicNodeType::Xor if node_children.size == 2 T.unsafe(Z3).Xor(*node_children.map { |c| c.to_z3(cfg_arch, solver) }) else # see https://stackoverflow.com/questions/14888174/how-do-i-determine-if-exactly-one-boolean-is-true-without-type-conversion#33268481 uneven_number_is_true = T.unsafe(Z3).Xor(*node_children.map { |c| c.to_z3(cfg_arch, solver) }) max_one_is_true = T.unsafe(Z3).And( *node_children.combination(2).map do |pair| !(pair.fetch(0).to_z3(cfg_arch, solver) & pair.fetch(1).to_z3(cfg_arch, solver)) end ) uneven_number_is_true & max_one_is_true end when LogicNodeType::True Z3.True when LogicNodeType::False Z3.False when LogicNodeType::Not !node_children.fetch(0).to_z3(cfg_arch, solver) when LogicNodeType::None !node_children.map { |c| c.to_z3(cfg_arch, solver) }.reduce(:|) when LogicNodeType::If node_children.fetch(0).to_z3(cfg_arch, solver).implies(node_children.fetch(1).to_z3(cfg_arch, solver)) else T.absurd(@type) end end |
#tseytin ⇒ LogicNode
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 |
# File 'lib/udb/logic.rb', line 3329 def tseytin subformulae = [] r = reduce return r if [LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False].any?(r.type) grouped = r.group_by_2 grouped.collect_tseytin(subformulae) if subformulae.size == 0 raise "? #{r}" elsif subformulae.size == 1 subformulae.fetch(0) else equisatisfiable_formula = LogicNode.new(LogicNodeType::And, subformulae + [grouped.tseytin_prop]) flatten_cnf(equisatisfiable_formula).reduce end end |
#tseytin_prop ⇒ LogicNode
a free variable representing this formula
3317 3318 3319 3320 3321 3322 3323 3324 3325 |
# File 'lib/udb/logic.rb', line 3317 def tseytin_prop case @type when LogicNodeType::Term, LogicNodeType::True, LogicNodeType::False self else @tseytin_prop ||= LogicNode.new(LogicNodeType::Term, [FreeTerm.new]) end end |
#unsatisfiable?(cfg_arch) ⇒ Boolean
Returns true iff self is unsatisfiable (not possible to be true for any combination of term values).
3091 |
# File 'lib/udb/logic.rb', line 3091 def unsatisfiable?(cfg_arch) = !satisfiable?(cfg_arch) |