You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
2.7 KiB

  1. #!python3
  2. from pysat.formula import CNF
  3. from pysat.solvers import Glucose4
  4. import pathlib as pl
  5. import random
  6. import bz2
  7. import sys
  8. CORE_DIR = pl.Path("./cores")
  9. EXTENDED_DIR = pl.Path("./extended")
  10. usage_str = "usage: gen_eq_instance.py [instance dir] [num per instance]"
  11. def main():
  12. instances_dir = None
  13. try:
  14. instances_dir = pl.Path(sys.argv[1])
  15. except:
  16. print(usage_str)
  17. return
  18. else:
  19. if not instances_dir.is_dir():
  20. print(usage_str)
  21. return
  22. num_per_instance = 0
  23. try:
  24. num_per_instance = int(sys.argv[2])
  25. except:
  26. print(usage_str)
  27. return
  28. instances = get_instance_paths(instances_dir)
  29. for instance in instances:
  30. run(instance, num_per_instance)
  31. def get_instance_paths(instances_dir):
  32. instances = []
  33. for p in instances_dir.iterdir():
  34. if str(p).endswith(".cnf.bz2"):
  35. instances.append(p)
  36. return instances
  37. def run(instance, calls_per_instance):
  38. ipath = pl.Path(instance)
  39. iname = ipath.stem[:-4]
  40. f = CNF(str(ipath))
  41. for i in range(calls_per_instance):
  42. extension = gen_extension(iname, len(f.clauses) / 10)
  43. #tmp_f = f.copy()
  44. #tmp_f.extend(extension)
  45. ext_f = CNF()
  46. ext_f.extend(extension)
  47. print(iname)
  48. print(len(f.clauses))
  49. print()
  50. ext_f.to_file(next_file_path(iname),
  51. comments=["c {} core extended".format(iname),
  52. "c number of cores: {}".format(len(extension))],
  53. compress_with="bzip2")
  54. def gen_extension(instance, expected_num_of_core):
  55. cores = parse_cores(instance)
  56. p = expected_num_of_core / len(cores)
  57. extension = []
  58. print((expected_num_of_core * 10) / len(cores))
  59. print(expected_num_of_core * 10, len(cores))
  60. for core in cores:
  61. if p >= random.random():
  62. extension.append(core)
  63. return extension
  64. def parse_cores(instance):
  65. cores = []
  66. with bz2.open(CORE_DIR / (instance + ".cores.bz2"), "tr") as cores_file:
  67. cores = list(map(lambda l: l.strip(), cores_file.readlines()))
  68. cores = list(map(lambda l: l.split(","), cores))
  69. for i in range(len(cores)):
  70. cores[i] = list(map(int, cores[i]))
  71. cores[i] = list(map(lambda lit: -1 * lit, cores[i]))
  72. return cores
  73. def next_file_path(name):
  74. counter = 0
  75. ext_file_path = EXTENDED_DIR / ("{}_{:04}.cnf.bz2".format(name, counter))
  76. while ext_file_path.exists():
  77. counter += 1
  78. ext_file_path = EXTENDED_DIR / ("{}_{:04}.cnf.bz2".format(name, counter))
  79. return ext_file_path
  80. if __name__ == "__main__":
  81. main()