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.

115 lines
2.7 KiB

4 years ago
4 years ago
  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. ext_f = CNF()
  44. ext_f.extend(extension)
  45. print(iname)
  46. print(len(f.clauses))
  47. print()
  48. fpath, nr = next_file_path(iname)
  49. ext_f.to_file(fpath,
  50. comments=["c extending:{} nr:{}".format(iname, nr),
  51. "c number of cores: {}".format(len(extension))],
  52. compress_with="bzip2")
  53. def gen_extension(instance, expected_num_of_core):
  54. cores = parse_cores(instance)
  55. p = expected_num_of_core / len(cores)
  56. extension = []
  57. print((expected_num_of_core * 10) / len(cores))
  58. print(expected_num_of_core * 10, len(cores))
  59. for core in cores:
  60. if p >= random.random():
  61. extension.append(core)
  62. return extension
  63. def parse_cores(instance):
  64. cores = []
  65. with bz2.open(CORE_DIR / (instance + ".cores.bz2"), "tr") as cores_file:
  66. cores = list(map(lambda l: l.strip(), cores_file.readlines()))
  67. cores = list(map(lambda l: l.split(","), cores))
  68. for i in range(len(cores)):
  69. cores[i] = list(map(int, cores[i]))
  70. cores[i] = list(map(lambda lit: -1 * lit, cores[i]))
  71. return cores
  72. def next_file_path(name):
  73. counter = 0
  74. ext_file_path = EXTENDED_DIR / ("{}_{:04}.cnf.bz2".format(name, counter))
  75. while ext_file_path.exists():
  76. counter += 1
  77. ext_file_path = EXTENDED_DIR / ("{}_{:04}.cnf.bz2".format(name, counter))
  78. return ext_file_path, counter
  79. if __name__ == "__main__":
  80. main()