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.

94 lines
2.8 KiB

6 years ago
6 years ago
5 years ago
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
  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. for i in range(len(clauses)):
  19. clauses[i].sort()
  20. #fill in the missing bindings
  21. for clauseIndex, clause in enumerate(clauses):
  22. tmpClause = []
  23. clauseIsUnique = False
  24. while not clauseIsUnique:
  25. tmpClause = clause.copy()
  26. numRemainingBindings = numberOfVariablesPerClause - len(tmpClause)
  27. variablesNotYetInClause = __getVariablesNotYetInClause(tmpClause,
  28. numberOfVariables)
  29. remainingBindings = random.sample(variablesNotYetInClause,
  30. numRemainingBindings)
  31. tmpClause += remainingBindings
  32. for i in range(len(tmpClause)):
  33. tmpClause[i] *= random.choice([-1, 1])
  34. tmpClause.sort()
  35. if tmpClause not in clauses:
  36. clauseIsUnique = True
  37. clauses[clauseIndex] = tmpClause
  38. instance.addClause(tmpClause)
  39. return instance
  40. def __getVariablesNotYetInClause(clause, numberOfTotalVars):
  41. missingVariables = []
  42. prevVar = 1;
  43. for currVar in clause:
  44. missingVariables += list(range(prevVar, currVar))
  45. prevVar = currVar + 1
  46. missingVariables += list(range(prevVar, numberOfTotalVars + 1))
  47. return missingVariables
  48. def number_of_possible_clauses(number_of_variables, variables_per_clause):
  49. return int(__binom(number_of_variables, variables_per_clause)
  50. * __number_of_sign_placements(variables_per_clause))
  51. def __binom(n, k):
  52. if n == k:
  53. return 1
  54. elif k == 1:
  55. return n
  56. else:
  57. return math.factorial(n) / (math.factorial(k) * math.factorial(n - k))
  58. def __number_of_sign_placements(variables_per_clause):
  59. result = 0;
  60. for i in range(variables_per_clause + 1):
  61. result += __binom(variables_per_clause, i)
  62. return result