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.



1049
1050
1051
1052
1053
1054
# File 'lib/mbt-gen.rb', line 1049

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

Class Method Details

.parse_assignment(str) ⇒ Object



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

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



1242
1243
1244
1245
1246
1247
1248
1249
1250
# File 'lib/mbt-gen.rb', line 1242

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])
  return [doc_number, num_docs, state, assignment, new_assignment]
end

.parse_new_assignment(str) ⇒ Object



1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
# File 'lib/mbt-gen.rb', line 1219

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



1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
# File 'lib/mbt-gen.rb', line 1172

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



1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
# File 'lib/mbt-gen.rb', line 1319

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



1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
# File 'lib/mbt-gen.rb', line 1254

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()) ⇒ Object

core algo



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
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
# File 'lib/mbt-gen.rb', line 1267

def enumerate(progress, switched, vars, assignment, message, key, output_dir, config, options, state = [nil] * vars.size())
  enumerate(progress, switched+1, vars, assignment, message, key, output_dir, config, options, state) 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
    store_continuation_point(generated_doc_number, state, assignment, new_assignment, "#{output_dir}/#{CONTINUATION_FILE}")
    if is_finite_state then
      progress.report_progress(determine_progress(state, vars))
    else
      progress.report_progress(nil)
    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)
      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)) 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



1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
# File 'lib/mbt-gen.rb', line 1093

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



1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
# File 'lib/mbt-gen.rb', line 1058

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



1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
# File 'lib/mbt-gen.rb', line 1130

def generate_doc_return_key_values(progress, message, key, output_filename, config, options)
  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)

  z3path = config[:z3path] || DEFAULT_Z3_PATH
  z3 = Z3Solver.new(progress, z3path)
  begin
    model = z3.query_model(progress, options) do |solver|
      solver.to_solver(progress, "(set-option :produce-unsat-cores true) ; enable generation of unsat cores")
      solver.to_solver(progress, "")
      log.puts "translating structure" if log
      translate_structure_to_SMTLIB(progress, solver, message, :options => options, :config => config)
      solver.to_solver(progress, "")
    end
  ensure
    z3.close()
  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(message, key, output_dir, config, options) ⇒ Object



1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
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
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
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
# File 'lib/mbt-gen.rb', line 1370

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

  number_of_combinations = calc_combinations(message, key)
  if number_of_combinations.is_a?(String) then
    progress = ProgressBar.new(100000000000000)
  else
    progress = ProgressBar.new(number_of_combinations)
  end
  begin
  ensure
  end
  progress.report_progress(0.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

  #progress.print_line "DEBUG: key_fields_list=#{key_fields_list.inspect}"

  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 = 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)
      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 "|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))
    else
      progress.report_progress(nil)
    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
    doc_counter = 0
    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(", ")}}"

        doc_counter += 1
        if options[:max_num_docs] && doc_counter >= 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|
            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"
      }

      # core algo - resume from state
      enumerate(progress, 0, key_fields_list, assignment, message, key, output_dir, config, options, state)
    end
  else
    # init safety mechanism
    @num_tries = 0
    @num_docs = 0
    doc_counter = 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)
      key_values = generate_doc_return_key_values(progress, message, key, output_doc_filename, config, options)
      log.puts "#{output_doc_filename} <- {#{key_values.map{|k,v| "#{k}: #{v.inspect}"}.join(", ")}}"
      doc_counter += 1
      @num_tries += 1
      @on_new_doc = Proc.new { |num_doc, doc_filename, combination|
        # combination logging
        log.puts "#{doc_filename} <- {#{combination.map{|k,v| "#{k}: #{v.inspect}"}.join(", ")}}"

        doc_counter += 1
        if options[:max_num_docs] && doc_counter >= 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|
            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"
      }

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

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



1118
1119
1120
1121
1122
1123
1124
# File 'lib/mbt-gen.rb', line 1118

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



1312
1313
1314
1315
1316
# File 'lib/mbt-gen.rb', line 1312

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



1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
# File 'lib/mbt-gen.rb', line 1354

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



1126
1127
1128
# File 'lib/mbt-gen.rb', line 1126

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

#num_combinations(key_def) ⇒ Object



1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
# File 'lib/mbt-gen.rb', line 1336

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



1166
1167
1168
1169
1170
# File 'lib/mbt-gen.rb', line 1166

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

#summarize_blocking_clause(var_xpath, blocked) ⇒ Object



1114
1115
1116
# File 'lib/mbt-gen.rb', line 1114

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

#summarize_fixing_clause(assignment, vars, switched) ⇒ Object



1076
1077
1078
1079
1080
1081
1082
# File 'lib/mbt-gen.rb', line 1076

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

#value_of_type(value, type) ⇒ Object



1084
1085
1086
1087
1088
1089
1090
# File 'lib/mbt-gen.rb', line 1084

def value_of_type(value, type)
  if type == :string or type == :enum then
    "\"#{value}\""
  elsif type == :int then
    value.to_s
  end
end