Guest User

Untitled

a guest
Jul 8th, 2024
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1.  
  2. import random
  3. from collections import defaultdict
  4. from graphviz import Digraph
  5. from IPython.display import Image, display
  6.  
  7. # Step 1: Generate Random Subset Sum Problem
  8. def generate_random_subset_sum(num_elements, target_sum_range):
  9. elements = [random.randint(1, 100) for _ in range(num_elements)]
  10. target_sum = random.randint(1, target_sum_range)
  11. return elements, target_sum
  12.  
  13. # Step 2: Build Graph Representation
  14. def build_graph(elements, target_sum):
  15. graph = defaultdict(list)
  16. for u in range(target_sum + 1):
  17. for e in elements:
  18. if u + e <= target_sum:
  19. graph[u].append(u + e)
  20. return graph
  21.  
  22. # Step 3: Construct Boolean Circuits
  23. def build_boolean_circuit(graph, target_sum):
  24. dot = Digraph(comment='Boolean Circuit for Subset Sum')
  25.  
  26. # Create nodes for each sum from 0 to target_sum
  27. for i in range(target_sum + 1):
  28. dot.node(f's{i}', f'Sum {i}')
  29.  
  30. # Create edges based on the graph transitions
  31. gate_counter = 1
  32. for u in graph:
  33. for v in graph[u]:
  34. element = v - u
  35. gate_label = f'AND{gate_counter}'
  36. gate_counter += 1
  37. dot.node(gate_label, 'AND', shape='rectangle')
  38. dot.edge(f's{u}', gate_label, label=str(element))
  39. dot.edge(gate_label, f's{v}')
  40.  
  41. # Add the final OR gate to check if target_sum is achievable
  42. dot.node('OR', 'OR', shape='circle')
  43. dot.edge(f's{target_sum}', 'OR')
  44.  
  45. return dot
  46.  
  47. # Step 4: Analyze Circuit Complexity
  48. def analyze_circuit_complexity(graph):
  49. gate_count = 0
  50. for u in graph:
  51. gate_count += len(graph[u])
  52. return gate_count
  53.  
  54. # Main Function
  55. def main():
  56. # Generate random subset sum problem
  57. elements, target_sum = generate_random_subset_sum(5, 50)
  58. print(f"Elements: {elements}")
  59. print(f"Target Sum: {target_sum}")
  60.  
  61. # Build graph representation
  62. graph = build_graph(elements, target_sum)
  63.  
  64. # Construct Boolean circuit
  65. dot = build_boolean_circuit(graph, target_sum)
  66.  
  67. # Save and render the graph
  68. output_path = 'boolean_circuit'
  69. dot.render(output_path, format='png', view=False)
  70. print(f"Circuit saved to {output_path}.png")
  71.  
  72. # Analyze circuit complexity
  73. complexity = analyze_circuit_complexity(graph)
  74. print(f"Number of gates: {complexity}")
  75.  
  76. # Display the image in Jupyter notebook
  77. return Image(filename=f'{output_path}.png')
  78.  
  79. # Run the main function
  80. if __name__ == "__main__":
  81. img = main()
  82. display(img)
Advertisement
Add Comment
Please, Sign In to add comment