Class: CoreEnumerationAlgo

Inherits:
Object
  • Object
show all
Defined in:
lib/mbt-gen.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCoreEnumerationAlgo

Returns a new instance of CoreEnumerationAlgo.



1190
1191
1192
1193
1194
1195
# File 'lib/mbt-gen.rb', line 1190

def initialize()
  @num_tries = 0
  @num_docs = 0
  @on_new_doc = nil
  @on_unsat = nil
end

Class Method Details

.parse_assignment(str) ⇒ Object



1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
# File 'lib/mbt-gen.rb', line 1327

def self.parse_assignment(str)
  unless str =~ /assignment\((.*)\)/
    return nil
  end
  split = $1.split(",")
  result = {}
  split.each do |e|
    s2 = e.split(":")
    key = s2[0]
    value = s2[1]
    if value == "nil" then
      result[key] = nil
    elsif value == "true" then
      result[key] = true
    elsif value == "false" then
      result[key] = false
    elsif value =~ /\"(.*)\"/
      result[key] = $1
    end
  end
  result
end

.parse_continuation_point(line) ⇒ Object



1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
# File 'lib/mbt-gen.rb', line 1373

def self.parse_continuation_point(line)
  split = line.split(";")
  doc_number = Integer(split[0])
  num_docs = Integer(split[1])
  state = CoreEnumerationAlgo.parse_state(split[2])
  assignment = CoreEnumerationAlgo.parse_assignment(split[3])
  new_assignment = CoreEnumerationAlgo.parse_assignment(split[4])
  processessing_time = Integer(split[5])
  return [doc_number, num_docs, state, assignment, new_assignment, processessing_time]
end

.parse_new_assignment(str) ⇒ Object



1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
# File 'lib/mbt-gen.rb', line 1350

def self.parse_new_assignment(str)
  unless str =~ /new_assignment\((.*)\)/
    return nil
  end
  split = $1.split(",")
  result = {}
  split.each do |e|
    s2 = e.split(":")
    key = s2[0]
    value = s2[1]
    if value == "nil" then
      result[key] = nil
    elsif value == "true" then
      result[key] = true
    elsif value == "false" then
      result[key] = false
    elsif value =~ /\"(.*)\"/
      result[key] = $1
    end
  end
  result
end

.parse_state(state_str) ⇒ Object



1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
# File 'lib/mbt-gen.rb', line 1303

def self.parse_state(state_str)
  unless state_str =~ /state\((.*)\)/
    return nil
  end
  split = $1.split("#")
  split.map do |e|
    if e == "nil" then
      nil
    elsif e =~ /\[(.*)\]/ then
      $1.split(",").map do |i|
        if i.strip == "nil" then
          nil
        elsif i.strip == "true" then
          true
        elsif i.strip == "false" then
          false
        elsif i.strip =~ /\"(.*)\"/ then
          $1
        end
      end
    end
  end
end

Instance Method Details

#determine_progress(state, vars) ⇒ Object

NOTE: can only be called when all key-fields are finite-state



1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
# File 'lib/mbt-gen.rb', line 1461

def determine_progress(state, vars)
  combinations_per_value = [nil] * vars.size()
  comb = 1
  vars.size().times.to_a.reverse_each do |i|
    combinations_per_value[i] = comb
    comb = values_for_key_field(vars[i][1]).size() * comb
  end

  blocked_combinations = 0
  state.size().times do |i|
    if state[i] then
      blocked_combinations += state[i].size() * combinations_per_value[i]
    end
  end
  blocked_combinations
end

#display_combination_space(assignment, vars, switched, blocked) ⇒ Object

TODO: logging



1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
# File 'lib/mbt-gen.rb', line 1386

def display_combination_space(assignment, vars, switched, blocked)
  # enumerate_fixing_clause(assignment, vars, switched) + enumerate_blocking_clause(vars[switched][0], vars[switched][1], blocked)

  # => all vars left of switched are fixed to their assigned values (when the value is nil, then they are empty)
  # => the switched var is prevented to have any of the blocked values
  res = switched.times.to_a.map do |index|
    var_xpath = vars[index][0]
    "#{var_xpath}=#{assignment[var_xpath].inspect}"
  end + ["#{vars[switched][0]}\\{#{blocked.map{|v| v.inspect}.join(",")}}"]
  "{#{res.join(", ")}}"
end

#enumerate(progress, switched, vars, assignment, message, key, output_dir, config, options, state = [nil] * vars.size(), start_time, prior_processing_time) ⇒ Object

core algo



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
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
# File 'lib/mbt-gen.rb', line 1400

def enumerate(progress, switched, vars, assignment, message, key, output_dir, config, options, state = [nil] * vars.size(), start_time, prior_processing_time)
  enumerate(progress, switched+1, vars, assignment, message, key, output_dir, config, options, state, start_time, prior_processing_time) if switched < vars.size()-1
  is_finite_state = keys_are_finite_state(vars)
  if state[switched] == nil then
    blocked = [assignment[vars[switched][0]]] 
    state[switched] = blocked
  else
    blocked = state[switched] + [assignment[vars[switched][0]]]
    state[switched] = blocked
  end
  found = true
  while found do
    found = false
    # - fix all vars left of switched to their values in assignment
    # - block switched from obtaining the values in blocked
    # progress.print_line "DEBUG: #{summarize_fixing_clause(assignment, vars, switched)}, #{summarize_blocking_clause(vars[switched][0], blocked)}"
    clauses = enumerate_fixing_clause(assignment, vars, switched) + enumerate_blocking_clause(vars[switched][0], vars[switched][1], blocked)
    output_doc_filename = prepare_output_doc_filename(@num_tries, output_dir)
    new_assignment = generate_sparse_doc(progress, message, key, config, options, clauses, output_doc_filename)
    generated_doc_number = @num_tries
    time = prior_processing_time + (Time.now().to_i - options[:timestamp_now])
    store_continuation_point(generated_doc_number, state, assignment, new_assignment, "#{output_dir}/#{CONTINUATION_FILE}", options, time)
    progress.print_line "STORING continuation point"
    progress.print_line "|time=#{time}"
    progress.print_line "|doc_number=#{generated_doc_number}"
    progress.print_line "|num_docs=#{@num_docs}"
    progress.print_line "|state=#{state.inspect}"
    progress.print_line "|assignment=#{assignment.inspect}"
    progress.print_line "|new_assignment=#{new_assignment.inspect}"

    if is_finite_state then
      progress.report_progress(determine_progress(state, vars), start_time, prior_processing_time, @num_docs)
    else
      progress.report_progress(nil, start_time, prior_processing_time, @num_docs)
    end
    @num_tries += 1
    if new_assignment then # sat
      @num_docs += 1
      @on_new_doc.call(generated_doc_number, output_doc_filename, new_assignment) if @on_new_doc
      if switched < vars.size()-1 then
        enumerate(progress, switched+1, vars, new_assignment, message, key, output_dir, config, options, state, start_time, prior_processing_time)
      end
      blocked << new_assignment[vars[switched][0]]
      state[switched] = blocked
      found = true
    else # unsat
      @on_unsat.call(generated_doc_number, log_filename_for_output_filename(output_doc_filename), display_combination_space(assignment, vars, switched, blocked), switched) if @on_unsat
      found = false
    end
  end
  state[switched] = nil
end

#enumerate_blocking_clause(var_xpath, var_def, blocked) ⇒ Object

prevent the var from taking values that already have been enumerated exhaustively



1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
# File 'lib/mbt-gen.rb', line 1226

def enumerate_blocking_clause(var_xpath, var_def, blocked)
  clauses = []
  num = 0
  if var_def[:type] == :field then
    blocked.each do |value|
      if value == nil then
        clauses << "(assert (! (not (= #{filled_var_for_field(var_xpath)} false)) :named blocking_clause_#{num}))"
      else
        clauses << "(assert (! (not (and (= #{filled_var_for_field(var_xpath)} true) (= #{value_var_for_field(var_xpath)} #{value_of_type(value, var_def[:datatype])}))) :named blocking_clause_#{num}))"
      end
      num += 1
    end
  elsif var_def[:type] == :structure then
    blocked.each do |value|
      clauses << "(assert (! (not (= #{exists_var_for_structure(var_xpath)} #{value.inspect})) :named blocking_clause_#{num}))"
      num += 1
    end
  end
  "; blocking clauses:\n#{clauses.join("\n")}" 
end

#enumerate_fixing_clause(assignment, vars, switched) ⇒ Object

fix values of all variables left from switched



1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
# File 'lib/mbt-gen.rb', line 1199

def enumerate_fixing_clause(assignment, vars, switched)
  clauses = []
  switched.times do |index|
    var_xpath = vars[index][0]
    var_def = vars[index][1]
    if var_def[:type] == :field then
      if assignment[var_xpath] == nil then
        clauses << "(assert (! (= #{filled_var_for_field(var_xpath)} false) :named fixing_clause_#{index}))"
      else
        clauses << "(assert (! (and (= #{filled_var_for_field(var_xpath)} true) (= #{value_var_for_field(var_xpath)} #{value_of_type(assignment[var_xpath], var_def[:datatype])})) :named fixing_clause_#{index}))"
      end
    elsif var_def[:type] == :structure then
      clauses << "(assert (! (= #{exists_var_for_structure(var_xpath)} #{assignment[var_xpath].inspect}) :named fixing_clause_#{index}))"
    end
  end
  "; fixing clauses:\n#{clauses.join("\n")}" 
end

#generate_doc_return_key_values(progress, message, key, output_filename, config, options) ⇒ Object

Raises:

  • (RuntimeError)


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
# File 'lib/mbt-gen.rb', line 1263

def generate_doc_return_key_values(progress, message, key, output_filename, config, options)
  raise RuntimeError.new("option :solverFactory is required.") unless options[:solverFactory]
  log = options[:log] || nil
  log.puts "generating doc #{output_filename}" if log
  options[:solverLog] = log_filename_for_output_filename(output_filename)

  key_fields = collect_key_fields(key, message)

  solverFactory = options[:solverFactory]    
  model = solverFactory.query_model(options) do |solver|
    set_standard_options(progress, solver)
    log.puts "translating structure" if log
    translate_structure_to_SMTLIB(progress, solver, message, :options => options, :config => config)
    solver.to_solver(progress, "")
  end

  if model then
    result_doc = build_document_from_model(progress, message, model)
    dir = File.dirname(output_filename)
    FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
    File.open(output_filename, "w") do |f|
      f.puts result_doc.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML)
    end
    progress.print_line "DONE. Generated XML was written to #{output_filename}, SMTLIB log was written to #{options[:solverLog]}"
    return extract_key_field_values_from_model(key_fields, model)
  else
    progress.print_line "FAILED. No XML document was generated. For more details, please see the SMTLIB log in #{options[:solverLog]}"
    return nil
  end
end

#generate_docs_for_key(progress, message, key, output_dir, config, options) ⇒ Object



1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
# File 'lib/mbt-gen.rb', line 1512

def generate_docs_for_key(progress, message, key, output_dir, config, options)

  prior_processing_time = 0
  start_time = options[:timestamp_now]
  number_of_combinations = calc_combinations(message, key)
  if number_of_combinations.is_a?(String) then
    progress.set_max(100000000000000)
  else
    progress.set_max(number_of_combinations)
  end
  progress.report_progress(0.0, start_time, prior_processing_time, 0)
  progress.print_line "generating sparse documents efficiently..."
  progress.print_line "there is a theoretical maximum of #{number_of_combinations} combinations."
  progress.print_line "Note, however, that we are generating only those documents that are valid, which are usually much less."

  progress.print_line "preparing output dir #{output_dir}..."
  if options[:continue] then
    unless Dir.exist?(output_dir) then
      raise FatalError.new("FATAL: directory #{output_dir} not found. There seems to be nothing to continue from...")
    end
    log_mode = "a"
  else
    unless Dir.exist?(output_dir) then
      FileUtils.mkdir_p(output_dir)
    end
    log_mode = "w"
  end
  log_filename = "#{output_dir}/#{COMBINATION_LOG}"

  key_fields = collect_key_fields(key, message)
  key_fields_list = key_fields.each_pair.to_a
  key_fields_list.sort! {|a,b| num_combinations(b[1]) <=> num_combinations(a[1]) }

  if options[:continue] then
    stored_key_fields_str = File.read("#{output_dir}/#{VARS_LOG}")
    unless key_fields_list.to_yaml == stored_key_fields_str then
      raise FatalError.new("vars are differing! please specify the same key in order to use -continue!")
    end
    progress.print_line "continuing enumerating documents for key #{key}!"
  else
    # store vars
    File.open("#{output_dir}/#{VARS_LOG}", "w") do |f|
      f.puts(key_fields_list.to_yaml)
    end
  end

  cont_filename = "#{output_dir}/#{CONTINUATION_FILE}"
  if options[:continue] then
    unless File.exist?(cont_filename) then
      raise FatalError.new("FATAL: file #{cont_filename} not found. There seems to be no continuation point to continue from...")
    end
    doc_number, num_docs, state, assignment, new_assignment, prior_processing_time = CoreEnumerationAlgo.parse_continuation_point(File.read(cont_filename).chomp)
    if is_final_state(state, new_assignment, key_fields_list) then
      progress.report_progress(number_of_combinations, start_time, prior_processing_time, num_docs)
      raise FatalError.new("FATAL: The enumeration is finished. There is nothing left to do. Resuming the enumeration hence does not make sense.")
    end
    progress.print_line "RESUMING enumeration from the following continuation point:"
    progress.print_line "|time=#{prior_processing_time}"
    progress.print_line "|doc_number=#{doc_number}"
    progress.print_line "|num_docs=#{num_docs}"
    progress.print_line "|state=#{state.inspect}"
    progress.print_line "|assignment=#{assignment.inspect}"
    progress.print_line "|new_assignment=#{new_assignment.inspect}"
    if keys_are_finite_state(key_fields_list) then
      progress.report_progress(determine_progress(state, key_fields_list), start_time, prior_processing_time, num_docs)
    else
      progress.report_progress(nil, start_time, prior_processing_time, num_docs)
    end

    if new_assignment && !new_assignment.empty? then
      assignment = new_assignment
    end

    # restore state at continuation point
    @num_tries = doc_number+1 # we do not want to overwrite the last document written before the STOP
    number_of_combinations += 1 # account for this in the safety mechanism
    @num_docs = num_docs
    File.open(log_filename, log_mode) do |log|

      @on_new_doc = Proc.new { |num_doc, doc_filename, combination|
        # combination logging
        log.puts "#{doc_filename} <- {#{combination.map{|k,v| "#{k}=#{v.inspect}"}.join(", ")}}"

        if options[:max_num_docs] && @num_docs >= options[:max_num_docs] then
          raise NormalProgramTermination.new("-max-num-docs exceeded. Stopping!")
        end

        # safety mechanism
        if @num_docs > number_of_combinations then
          raise RuntimeError.new("This should never happen! Number of combinations exceeded. #{@num_docs} documents generated, but there are only #{number_of_combinations} possible combinations of the key vars.")
        end
      }
      @on_unsat = Proc.new { |num_doc, log_filename, combination_str, switched|
            log.puts "CONTRADICTION (see: #{log_filename}) <- #{combination_str}"
            progress.print_line "doc#{num_doc} NOT generated"
            progress.print_line "No more valid combinations of the free vars could be found. -> Switching (var #{switched})"
      }

      # core algo - resume from state
      enumerate(progress, 0, key_fields_list, assignment, message, key, output_dir, config, options, state, start_time, prior_processing_time)
    end
  else
    # init safety mechanism
    @num_tries = 0
    @num_docs = 0
    # first try - a freely generated document
    File.open(log_filename, log_mode) do |log|
      output_doc_filename = prepare_output_doc_filename(@num_tries, output_dir)
      @on_new_doc = Proc.new { |num_doc, doc_filename, combination|
        # combination logging
        log.puts "#{doc_filename} <- {#{combination.map{|k,v| "#{k}=#{v.inspect}"}.join(", ")}}"

        if options[:max_num_docs] && @num_docs >= options[:max_num_docs] then
          raise NormalProgramTermination.new("-max-num-docs exceeded. Stopping!")
        end

        # safety mechanism
        unless number_of_combinations.is_a?(String) then
          if @num_docs > number_of_combinations then
            raise RuntimeError.new("This should never happen! Number of combinations exceeded. #{@num_docs} documents generated, but there are only #{number_of_combinations} possible combinations of the key vars.")
          end
        end
      }
      @on_unsat = Proc.new { |num_doc, log_filename, combination_str, switched|
            log.puts "CONTRADICTION (see: #{log_filename}) <- #{combination_str}"
            progress.print_line "doc#{num_doc} NOT generated"
            progress.print_line "No more valid combinations of the free vars could be found. -> Switching (var #{switched})"
      }
      key_values = generate_doc_return_key_values(progress, message, key, output_doc_filename, config, options)
      @num_tries += 1
      if key_values then
        @num_docs += 1
        @on_new_doc.call(@num_tries, output_doc_filename, key_values)
      else
        # NOTE: this only occurs when the model is inconsistent and has no valid documents
        progress.print_line("ERROR: Model inconsistent - no valid documents could be found.")
        @on_unsat.call(@num_tries, log_filename_for_output_filename(output_doc_filename), "{}", 0)
      end

      # core algo - start enumeration
      enumerate(progress, 0, key_fields_list, key_values, message, key, output_dir, config, options, start_time, prior_processing_time)
    end
  end
  progress.print_line "No more valid documents could be found. -> Exiting"
  progress.report_progress(number_of_combinations, start_time, prior_processing_time, @num_docs)
end

#generate_sparse_doc(progress, message, key, config, options, code, output_doc_filename) ⇒ Object



1251
1252
1253
1254
1255
1256
1257
# File 'lib/mbt-gen.rb', line 1251

def generate_sparse_doc(progress, message, key, config, options, code, output_doc_filename)
  additional_options = {}
  if code then
      additional_options = { :add_SMTLIB => code }
  end
  return generate_doc_return_key_values(progress, message, key, output_doc_filename, config, options.merge(additional_options))
end

#is_final_state(state, new_assignment, key_fields_list) ⇒ Object

NOTE: can only be called when all key-fields are finite-state



1454
1455
1456
1457
1458
# File 'lib/mbt-gen.rb', line 1454

def is_final_state(state, new_assignment, key_fields_list)
  return state[1,state.size()] == [nil] * (state.size()-1) &&
     state[0].to_set == values_for_key_field(key_fields_list[0][1]).to_set &&
     new_assignment.empty?
end

#keys_are_finite_state(list) ⇒ Object



1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
# File 'lib/mbt-gen.rb', line 1496

def keys_are_finite_state(list)
  list.each do |field|
    name = field[0]
    if field[1][:type] == :field then
      if field[1][:datatype] == :enum then
        # enums are finite-state
      elsif field[1][:datatype] == :int and field[1].has_key?(:min) and field[1].has_key?(:max) and field[1][:min] <= field[1][:max] then
        # ints are finite-state when both bounds are given and :min <= :max
      else
        return false
      end
    end
  end
  return true
end

#log_filename_for_output_filename(output_filename) ⇒ Object



1259
1260
1261
# File 'lib/mbt-gen.rb', line 1259

def log_filename_for_output_filename(output_filename)
  "#{output_filename}.smt2"
end

#num_combinations(key_def) ⇒ Object



1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
# File 'lib/mbt-gen.rb', line 1478

def num_combinations(key_def)
  if key_def[:type] == :field then
    if key_def[:datatype] == :enum then
      key_def[:values].size() + (key_def[:optional] ? 1 : 0)
    elsif key_def[:datatype] == :int then
      if key_def.has_key?(:min) and key_def.has_key?(:max) and key_def[:min] <= key_def[:max] then
        1 + key_def[:max] - key_def[:min] + (key_def[:optional] ? 1 : 0)
      else
        nil
      end
    else
      nil
    end
  elsif key_def[:type] == :structure then
    2
  end
end

#store_continuation_point(doc_number, state, assignment, new_assignment, filename, options, time) ⇒ Object



1294
1295
1296
1297
1298
1299
1300
1301
# File 'lib/mbt-gen.rb', line 1294

def store_continuation_point(doc_number, state, assignment, new_assignment, filename, options, time)
  File.open(filename, "w") do |f|
    state_str = "state(#{state.map{|s| if s then "[#{s.map{|v| v.inspect}.join(",")}]" else "nil" end}.join("#")})"
    assignment_str = "assignment(#{assignment.to_a.map{|k,v| "#{k}:#{v.inspect}"}.join(",")})"
    new_assignment_str = "new_assignment(#{new_assignment.to_a.map{|k,v| "#{k}:#{v.inspect}"}.join(",")})"
    f.puts("#{doc_number};#{@num_docs};#{state_str};#{assignment_str};#{new_assignment_str};#{time}")
  end
end

#summarize_blocking_clause(var_xpath, blocked) ⇒ Object



1247
1248
1249
# File 'lib/mbt-gen.rb', line 1247

def summarize_blocking_clause(var_xpath, blocked)
  "blocked(#{var_xpath})=[#{blocked.map{|v| v.inspect}.join(", ")}]"
end

#summarize_fixing_clause(assignment, vars, switched) ⇒ Object



1217
1218
1219
1220
1221
1222
1223
# File 'lib/mbt-gen.rb', line 1217

def summarize_fixing_clause(assignment, vars, switched)
  fixed = switched.times.to_a.map do |index|
    var_xpath = vars[index][0]
    "#{var_xpath}=#{assignment[var_xpath].inspect}"
  end
  "fixed(#{fixed.join(", ")})"
end