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.

91 lines
2.7 KiB

6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
  1. #!/usr/bin/env python3
  2. import numpy as np
  3. import random
  4. from . import kSAT
  5. import math
  6. def generateRandomKSAT(numberOfClauses,
  7. numberOfVariables,
  8. numberOfVariablesPerClause):
  9. instance = kSAT.kSAT()
  10. clauses = [[] for i in range(numberOfClauses)]
  11. #make sure every variable is bound to at least one clause
  12. for varIndex in range(numberOfVariables):
  13. clauseIndex = random.choice(range(numberOfClauses))
  14. while (len(clauses[clauseIndex]) >= numberOfVariablesPerClause or
  15. varIndex + 1 in clauses[clauseIndex]):
  16. clauseIndex = random.choice(range(numberOfClauses))
  17. clauses[clauseIndex].append(varIndex + 1)
  18. #fill in the missing bindings
  19. for clauseIndex, clause in enumerate(clauses):
  20. tmpClause = []
  21. clauseIsUnique = False
  22. while not clauseIsUnique:
  23. tmpClause = clause.copy()
  24. numRemainingBindings = numberOfVariablesPerClause - len(tmpClause)
  25. variablesNotYetInClause = __getVariablesNotYetInClause(tmpClause,
  26. numberOfVariables)
  27. remainingBindings = random.sample(variablesNotYetInClause,
  28. numRemainingBindings)
  29. tmpClause += remainingBindings
  30. for i in range(len(tmpClause)):
  31. tmpClause[i] *= random.choice([-1, 1])
  32. tmpClause = list(np.sort(tmpClause))
  33. if tmpClause not in clauses:
  34. clauseIsUnique = True
  35. clauses[clauseIndex] = tmpClause
  36. instance.addClause(tmpClause)
  37. return instance
  38. def __getVariablesNotYetInClause(clause, numberOfTotalVars):
  39. missingVariables = []
  40. prevVar = 1;
  41. for currVar in clause:
  42. missingVariables += list(range(prevVar, currVar))
  43. prevVar = currVar + 1
  44. missingVariables += list(range(prevVar, numberOfTotalVars + 1))
  45. return missingVariables
  46. def number_of_possible_clauses(number_of_variables, variables_per_clause):
  47. return int(__binom(number_of_variables, variables_per_clause)
  48. * __number_of_sign_placements(variables_per_clause))
  49. def __binom(n, k):
  50. if n == k:
  51. return 1
  52. elif k == 1:
  53. return n
  54. else:
  55. return math.factorial(n) / (math.factorial(k) * math.factorial(n - k))
  56. def __number_of_sign_placements(variables_per_clause):
  57. result = 0;
  58. for i in range(variables_per_clause + 1):
  59. result += __binom(variables_per_clause, i)
  60. return result