Class: Udb::LogicNode

Inherits:
Object
  • Object
show all
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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, children)

Parameters:



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
1291
1292
1293
1294
# File 'lib/udb/logic.rb', line 1258

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

#childrenArray<ChildType> (readonly)

Returns:



1217
1218
1219
# File 'lib/udb/logic.rb', line 1217

def children
  @children
end

#memoObject

Returns the value of attribute memo.



1255
1256
1257
# File 'lib/udb/logic.rb', line 1255

def memo
  @memo
end

#typeLogicNodeType (readonly)

Returns:



1214
1215
1216
# File 'lib/udb/logic.rb', line 1214

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 “-”

Parameters:

  • mterms (Array<String>)
  • group_by (String)

Returns:



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
1500
1501
1502
1503
# File 'lib/udb/logic.rb', line 1442

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>}

Parameters:

  • mterms (Array<String>)
  • group_by (String)

Returns:

  • (Hash{Integer => Array<String>})


1384
1385
1386
1387
1388
1389
1390
1391
1392
# File 'lib/udb/logic.rb', line 1384

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_solvesObject



1190
1191
1192
# File 'lib/udb/logic.rb', line 1190

def self.inc_brute_force_sat_solves
  @num_brute_force_sat_solves += 1
end

.inc_minisat_cache_hitsObject



1206
1207
1208
# File 'lib/udb/logic.rb', line 1206

def self.inc_minisat_cache_hits
  @num_minisat_cache_hits += 1
end

.inc_minisat_sat_solvesObject



1198
1199
1200
# File 'lib/udb/logic.rb', line 1198

def self.inc_minisat_sat_solves
  @num_minisat_sat_solves += 1
end

.make_eval_cb(&blk) ⇒ EvalCallbackType

Parameters:

Returns:



1657
1658
1659
# File 'lib/udb/logic.rb', line 1657

def self.make_eval_cb(&blk)
  blk
end

.make_replace_cb(&blk) ⇒ ReplaceCallbackType

Parameters:

Returns:



1663
1664
1665
# File 'lib/udb/logic.rb', line 1663

def self.make_replace_cb(&blk)
  blk
end

.num_brute_force_sat_solvesObject



1186
1187
1188
# File 'lib/udb/logic.rb', line 1186

def self.num_brute_force_sat_solves
  @num_brute_force_sat_solves
end

.num_minisat_cache_hitsObject



1202
1203
1204
# File 'lib/udb/logic.rb', line 1202

def self.num_minisat_cache_hits
  @num_minisat_cache_hits
end

.num_minisat_sat_solvesObject



1194
1195
1196
# File 'lib/udb/logic.rb', line 1194

def self.num_minisat_sat_solves
  @num_minisat_sat_solves
end

.pair_mterms(group1, group2) ⇒ PairMintermsResult

Parameters:

  • group1 (Array<String>)
  • group2 (Array<String>)

Returns:



1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
# File 'lib/udb/logic.rb', line 1400

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

Returns:

  • (Boolean)


1428
1429
1430
1431
1432
# File 'lib/udb/logic.rb', line 1428

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_statsObject

statistics counters



1176
1177
1178
1179
1180
1181
1182
# File 'lib/udb/logic.rb', line 1176

def self.reset_stats
  @num_brute_force_sat_solves = 0
  @time_brute_force_sat_solves = 0
  @num_minisat_sat_solves = 0
  @time_minisat_sat_solves = 0
  @num_minisat_cache_hits = 0
end

Instance Method Details

#always_implies?(other) ⇒ Boolean

Parameters:

Returns:

  • (Boolean)


3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
# File 'lib/udb/logic.rb', line 3031

def always_implies?(other)
  # can test that by seeing if the contradiction is satisfiable, i.e.:
  # if self -> other , contradition would be self & not other
  contradiction = LogicNode.new(
    LogicNodeType::And,
    [
      self,
      LogicNode.new(LogicNodeType::Not, [other])
    ]
  )
  !contradiction.satisfiable?
end

#cnf?Boolean

returns true iff tree is in Conjunctive Normal Form

Returns:

  • (Boolean)


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
2827
2828
2829
2830
# File 'lib/udb/logic.rb', line 2800

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

Returns:

  • (Boolean)


2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
# File 'lib/udb/logic.rb', line 2862

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.

Parameters:



3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
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
# File 'lib/udb/logic.rb', line 3315

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_notLogicNode

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:



3302
3303
3304
3305
3306
3307
# File 'lib/udb/logic.rb', line 3302

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

Returns:

  • (Boolean)


2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
# File 'lib/udb/logic.rb', line 2834

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

Returns:

  • (Boolean)


2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
# File 'lib/udb/logic.rb', line 2889

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

Parameters:

Returns:

  • (String)


3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
# File 'lib/udb/logic.rb', line 3223

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

Parameters:

  • other (T.untyped)

Returns:

  • (Boolean)


3697
3698
3699
3700
3701
# File 'lib/udb/logic.rb', line 3697

def eql?(other)
  return false unless other.is_a?(LogicNode)

  to_h.eql?(other.to_h)
end

#equisat_cnfLogicNode

coverts self to an equisatisfiable formula in Conjunctive Normal Form and returns it as a new formula (self is unmodified)

Returns:



2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
# File 'lib/udb/logic.rb', line 2773

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) ⇒ Boolean

Parameters:

Returns:

  • (Boolean)


3166
3167
3168
3169
3170
3171
3172
# File 'lib/udb/logic.rb', line 3166

def equisatisfiable?(other)
  if satisfiable?
    other.satisfiable?
  else
    !other.satisfiable?
  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

Parameters:

  • raise_on_explosion (Boolean) (defaults to: true)

Returns:



2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
# File 'lib/udb/logic.rb', line 2749

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) ⇒ Boolean

Returns true iff self and other are logically equivalent (identical truth tables).

Parameters:

Returns:

  • (Boolean)

    true iff self and other are logically equivalent (identical truth tables)



3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
# File 'lib/udb/logic.rb', line 3176

def equivalent?(other)
  # 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?
end

#espresso(result_type, exact) ⇒ LogicNode

minimize the function using espresso

Parameters:

Returns:



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
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
# File 'lib/udb/logic.rb', line 3550

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

Parameters:

Returns:

  • (SatisfiedResult)


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
1783
1784
1785
1786
# File 'lib/udb/logic.rb', line 1686

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

Parameters:

  • dimacs (String)

Returns:



3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
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
# File 'lib/udb/logic.rb', line 3461

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_2LogicNode

Returns rewrites the tree so that no node has more than 2 children.

Examples:

(A || B || C) => ((A || B) || C)

Returns:

  • (LogicNode)

    rewrites the tree so that no node has more than 2 children



2370
2371
2372
# File 'lib/udb/logic.rb', line 2370

def group_by_2
  do_group_by_2(self)
end

#grouped_by_2?(node) ⇒ Boolean

does each node have at most two children?

Parameters:

Returns:

  • (Boolean)


2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
# File 'lib/udb/logic.rb', line 2345

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

#hashInteger

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:

  • (Integer)


1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
# File 'lib/udb/logic.rb', line 1881

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

#literalsArray<TermType>

unlike #terms, this list will include leaves that are equivalent

Returns:

  • (Array<TermType>)

    all literals in the tree



1373
1374
1375
1376
1377
1378
1379
1380
# File 'lib/udb/logic.rb', line 1373

def literals
  @memo.literals ||=
  if @type == LogicNodeType::Term
    [@children.fetch(0)]
  else
    node_children.map { |child| child.literals }.flatten
  end
end

#minimal_unsat_subsetsArray<LogicNode>

return minimally unsatisfiable subsets of the unstatisfiable formula

Returns:



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
# File 'lib/udb/logic.rb', line 3507

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

Parameters:

Returns:



1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
# File 'lib/udb/logic.rb', line 1636

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

Returns:

  • (Boolean)


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
2991
2992
2993
2994
# File 'lib/udb/logic.rb', line 2960

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

Parameters:

  • ancestor_or (Boolean)

Returns:

  • (Boolean)


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
2951
2952
2953
2954
# File 'lib/udb/logic.rb', line 2916

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

#nnfLogicNode

Returns self, converted to Negation Normal Form.

Returns:

  • (LogicNode)

    self, converted to Negation Normal Form



2216
2217
2218
# File 'lib/udb/logic.rb', line 2216

def nnf
  do_nnf(self)
end

#nnf?Boolean

Returns true iff self is in Negation Normal Form.

Returns:

  • (Boolean)

    true iff self is in Negation Normal Form



2221
2222
2223
2224
2225
2226
2227
2228
2229
# File 'lib/udb/logic.rb', line 2221

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_childrenArray<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.

Returns:



1298
1299
1300
# File 'lib/udb/logic.rb', line 1298

def node_children
  @node_children
end

#partial_evaluate(cb) ⇒ LogicNode

partially evalute – replace anything known with true/false, and otherwise leave it alone

Parameters:

Returns:



1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
# File 'lib/udb/logic.rb', line 1790

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

#reduceLogicNode

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

Returns:



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
2738
2739
2740
2741
# File 'lib/udb/logic.rb', line 2601

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

Parameters:

Returns:



1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
# File 'lib/udb/logic.rb', line 1668

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?

Parameters:

Returns:

  • (Boolean)


1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
# File 'lib/udb/logic.rb', line 1325

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?Boolean

Returns true iff self is satisfiable (possible to be true for some combination of term values).

Returns:

  • (Boolean)

    true iff self is satisfiable (possible to be true for some combination of term values)



3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
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
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
# File 'lib/udb/logic.rb', line 3091

def satisfiable?
  @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_minisat_sat_solves

        @@cache ||= {}
        cache_key = hash
        if @@cache.key?(cache_key)
          LogicNode.inc_minisat_cache_hits
          return @@cache[cache_key]
        end

        c = self.cnf? ? self : equisat_cnf
        # raise "cnf error" unless c.cnf?

        if c.type == LogicNodeType::True
          return true
        elsif c.type == LogicNodeType::False
          return false
        end

        t = c.terms

        solver = MiniSat::Solver.new

        term_map = T.let({}, T::Hash[TermType, MiniSat::Variable])
        t.each do |term|
          unless term_map.key?(term)
            term_map[term] = solver.new_var
          end
        end
        raise "term mapping failed" unless t.uniq == term_map.keys

        build_solver(solver, flatten_cnf(c), term_map, nil)

        solver.solve
        @@cache[cache_key] = solver.satisfied?
      end
    end
end

#termsArray<TermType>

Returns The unique terms (leafs) of this tree.

Returns:

  • (Array<TermType>)

    The unique terms (leafs) of this tree



1349
1350
1351
1352
1353
1354
1355
1356
# File 'lib/udb/logic.rb', line 1349

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_antecendentsArray<TermType>

Returns The unique terms (leafs) of this tree, exculding antecendents of an IF.

Returns:

  • (Array<TermType>)

    The unique terms (leafs) of this tree, exculding antecendents of an IF



1360
1361
1362
1363
1364
1365
1366
1367
1368
# File 'lib/udb/logic.rb', line 1360

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

Parameters:

  • include_versions (Boolean)

Returns:

  • (String)


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
2012
2013
2014
2015
# File 'lib/udb/logic.rb', line 1968

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(" &#2295; ")})"
  when LogicNodeType::None
    "!++(++#{node_children.map { |c| c.to_asciidoc(include_versions:) }.join(" pass:[||] ")})"
  else
    T.absurd(@type)
  end
end

#to_dimacsString

Returns:

  • (String)


3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
# File 'lib/udb/logic.rb', line 3420

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_eqntottEqntottResult

return equation suitable for ‘eqntott` input

Returns:



3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
# File 'lib/udb/logic.rb', line 3256

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

Parameters:

  • term_determined (Boolean) (defaults to: false)

Returns:

  • (Boolean, Hash{String => T.untyped})


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
2112
2113
2114
2115
# File 'lib/udb/logic.rb', line 2043

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

Parameters:

Returns:

  • (String)


2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
# File 'lib/udb/logic.rb', line 2018

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

Parameters:

Returns:

  • (String)


1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
# File 'lib/udb/logic.rb', line 1906

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_prettyString

return a nice, human-readable form that may gloss over details

Returns:

  • (String)


1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
# File 'lib/udb/logic.rb', line 1856

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

Parameters:

Returns:

  • (String)


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
1962
1963
1964
1965
# File 'lib/udb/logic.rb', line 1931

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

Parameters:

Returns:

  • (Z3::BoolExpr)


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 3045

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)
    else
      raise "unexpected" if t.is_a?(FreeTerm) || 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

#tseytinLogicNode

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:



3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
# File 'lib/udb/logic.rb', line 3401

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_propLogicNode

a free variable representing this formula

Returns:



3389
3390
3391
3392
3393
3394
3395
3396
3397
# File 'lib/udb/logic.rb', line 3389

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?Boolean

Returns true iff self is unsatisfiable (not possible to be true for any combination of term values).

Returns:

  • (Boolean)

    true iff self is unsatisfiable (not possible to be true for any combination of term values)



3163
# File 'lib/udb/logic.rb', line 3163

def unsatisfiable? = !satisfiable?