bitk20a / SEM

0 stars 0 forks source link

Transition Matrix #4

Open bitk20a opened 3 weeks ago

bitk20a commented 3 weeks ago

import numpy as np import matplotlib.pyplot as plt

N = 8 time_steps = 100

Given J matrix

J = np.array([ [0, 0.1707, 0.1993, 0.5335, -0.3873, 0.1229, 0.0436, 0.3265], [0.1707, 0, -0.1502, -0.6043, -0.1221, 0.0507, 0.0764, 0.0530], [0.1993, -0.1502, 0, 0.2392, -0.8534, -0.7487, -0.4066, 0.4094], [0.5335, -0.6043, 0.2392, 0, 0.0, 0.0, 0.0, 0.0], [-0.3873, -0.1221, -0.8534, 0.0, 0, 0.0, 0.0, 0.0], [0.1229, 0.0507, -0.7487, 0.0, 0.0, 0, 0.0, 0.0], [0.0436, 0.0764, -0.4066, 0.0, 0.0, 0.0, 0, 0.0], [0.3265, 0.0530, 0.4094, 0.0, 0.0, 0.0, 0.0, 0] ])

h = np.array([0, 0, 0, 0,0,0,0,0])

def energy_function(state): return -0.5 * np.dot(state, np.dot(J, state)) - np.dot(h, state)

def sigmoid(x): return 1 / (1 + np.exp(-x))

def transition_probability(current_state, new_state, temperature): delta_energy = energy_function(new_state) - energy_function(current_state)

# Calculate the acceptance probability using the sigmoid function
acceptance_probability = sigmoid(-delta_energy / temperature)

return acceptance_probability

def build_transition_matrix(temperature): num_states = 2**N transition_matrix = np.zeros((num_states, num_states))

states = [np.array([1 if bit == '1' else -1 for bit in np.binary_repr(i, width=N)]) for i in range(num_states)]

for i, current_state in enumerate(states):
    for j, new_state in enumerate(states):
        transition_matrix[i, j] = transition_probability(current_state, new_state, temperature)

    # Normalize the row to ensure probabilities sum to 1
    row_sum = np.sum(transition_matrix[i, :])
    if row_sum > 0:
        transition_matrix[i, :] /= row_sum

return transition_matrix.T

initial_prob = np.ones(2N) / 2N prob_over_time = [initial_prob.copy()]

for t in range(1, time_steps + 1): temperature = 1 / (np.log(t + 1) + 1e-9) temperature = 1 / (np.sqrt(t)) transition_mat = build_transition_matrix(temperature)

print(f"transition matrix in step {t}:", transition_mat)

initial_prob = np.dot(transition_mat, initial_prob)
prob_over_time.append(initial_prob.copy())

prob_over_time = np.array(prob_over_time)

plt.figure(figsize=(10, 6)) for state_idx in range(2**N): plt.plot(range(time_steps + 1), prob_over_time[:, state_idx], label=f"State {state_idx}")

plt.plot(range(time_steps + 1), prob_over_time[:, 3], label=f"State 3")

plt.xlabel("Time Step") plt.ylabel("Probability") plt.title("Probability Distribution Over Time for Each State with Decreasing Temperature") plt.legend() plt.show()

bitk20a commented 3 weeks ago

Ising Machine## Energy Check

import numpy as np import matplotlib.pyplot as plt import pandas as pd

N=8

Given J matrix

Define the interaction matrix J

J = np.array([ [0, 0.1707, 0.1993, 0.5335, -0.3873, 0.1229, 0.0436, 0.3265], [0.1707, 0, -0.1502, -0.6043, -0.1221, 0.0507, 0.0764, 0.0530], [0.1993, -0.1502, 0, 0.2392, -0.8534, -0.7487, -0.4066, 0.4094], [0.5335, -0.6043, 0.2392, 0, -0.1631, -0.3620, 0.6246, -0.1146], [-0.3873, -0.1221, -0.8534, -0.1631, 0, 0.5450, -0.3560, 0.3380], [0.1229, 0.0507, -0.7487, -0.3620, 0.5450, 0, -0.1799, -0.1700], [0.0436, 0.0764, -0.4066, 0.6246, -0.3560, -0.1799, 0, -0.3250], [0.3265, 0.0530, 0.4094, -0.1146, 0.3380, -0.1700, -0.3250, 0] ])

h = np.array([0, 0, 0, 0,0,0,0,0])

def energy(state): return -0.5 * np.dot(state, np.dot(J, state)) - np.dot(h, state)

Generate all possible spin configurations for 8 qubits (each spin can be -1 or 1)

spin_configs= [np.array([1 if bit == '1' else -1 for bit in np.binary_repr(i, width=N)]) for i in range(2**N)]

Compute the energy for each configuration

energies = np.array([energy(spins) for spins in spin_configs])

Convert each spin configuration to a string for labeling

state_labels = [''.join(map(str, s)) for s in spin_configs]

Plotting the energy of each state in a bar graph

plt.figure(figsize=(12, 6)) plt.bar(state_labels, energies, color='skyblue') plt.title("Energy of Different Spin Configurations (Ising Machine)") plt.xlabel("Spin Configuration") plt.ylabel("Energy") plt.xticks(rotation=90, fontsize=8) plt.grid(axis='y', linestyle='--', alpha=0.7)

plt.tight_layout() plt.show() T = 1 beta = 1 / T # Inverse temperature

Compute the partition function Z

Z = np.sum(np.exp(-beta * energies))

Compute the Boltzmann probability for each configuration

boltzmann_probs = np.exp(-beta * energies) / Z

Convert each spin configuration to a string for labeling

state_labels = [''.join(map(str, s)) for s in spin_configs]

Convert bipolar to binary and then to decimal

binary_configs = [(s + 1) // 2 for s in spin_configs] # Convert -1 to 0, +1 to 1 binary_labels = [''.join(map(str, b)) for b in binary_configs] decimal_values = [int(b, 2) for b in binary_labels] # Convert binary string to decimal

Create a DataFrame with energies, configurations, decimal values, and Boltzmann probabilities

df = pd.DataFrame({ 'Spin Configuration (Bipolar)': state_labels, 'Spin Configuration (Binary)': binary_labels, 'Decimal Value': decimal_values, 'Energy': energies, 'Boltzmann Probability': boltzmann_probs })

Sort the DataFrame by energy in ascending order

df_sorted = df.sort_values(by='Energy').reset_index(drop=True)

Display the sorted DataFrame

df_sorted

Plotting Boltzmann Probability vs. Decimal Value

plt.figure(figsize=(10, 6)) plt.bar(df['Decimal Value'], df['Boltzmann Probability'], color='skyblue')

plt.bar(df['Decimal Value'], df['Energy'], color='skyblue')

plt.title("Boltzmann Probability vs. Decimal Value of Spin Configurations") plt.xlabel("Decimal Value") plt.ylabel("Boltzmann Probability") plt.grid(True, linestyle='--', alpha=0.7)

plt.tight_layout() plt.show()

bitk20a commented 3 weeks ago

Change sigmoid function each time ### Transition Matrix

import numpy as np import matplotlib.pyplot as plt

N = 8 time_steps = 100

Given J matrix

Define the interaction matrix J

J = np.array([ [0, 0.1707, 0.1993, 0.5335, -0.3873, 0.1229, 0.0436, 0.3265], [0.1707, 0, -0.1502, -0.6043, -0.1221, 0.0507, 0.0764, 0.0530], [0.1993, -0.1502, 0, 0.2392, -0.8534, -0.7487, -0.4066, 0.4094], [0.5335, -0.6043, 0.2392, 0, -0.1631, -0.3620, 0.6246, -0.1146], [-0.3873, -0.1221, -0.8534, -0.1631, 0, 0.5450, -0.3560, 0.3380], [0.1229, 0.0507, -0.7487, -0.3620, 0.5450, 0, -0.1799, -0.1700], [0.0436, 0.0764, -0.4066, 0.6246, -0.3560, -0.1799, 0, -0.3250], [0.3265, 0.0530, 0.4094, -0.1146, 0.3380, -0.1700, -0.3250, 0] ])

h = np.array([0, 0, 0, 0,0,0,0,0])

def energy_function(state): return -0.5 * np.dot(state, np.dot(J, state)) - np.dot(h, state)

def sigmoid(x,t): return 1 / (1 + np.exp(-t*x/10))

def transition_probability(current_state, new_state, temperature,t): delta_energy = energy_function(new_state) - energy_function(current_state)

## Calculate the acceptance probability using the sigmoid function
acceptance_probability = sigmoid(-delta_energy / temperature,t)

return acceptance_probability

def build_transition_matrix(temperature,t): num_states = 2**N transition_matrix = np.zeros((num_states, num_states))

states = [np.array([1 if bit == '1' else -1 for bit in np.binary_repr(i, width=N)]) for i in range(num_states)]

for i, current_state in enumerate(states):
    for j, new_state in enumerate(states):
        transition_matrix[i, j] = transition_probability(current_state, new_state, temperature,t)

    ## Normalize the row to ensure probabilities sum to 1
    row_sum = np.sum(transition_matrix[i, :])
    if row_sum > 0:
        transition_matrix[i, :] /= row_sum

return transition_matrix.T

initial_prob = np.ones(2N) / 2N prob_over_time = [initial_prob.copy()]

for t in range(1, time_steps + 1):

temperature = 1 / (np.log(t + 1) + 1e-9)

temperature = 3 / (np.sqrt(t))
transition_mat = build_transition_matrix(temperature,t)
##print(f"transition matrix in step {t}:", transition_mat)
initial_prob = np.dot(transition_mat, initial_prob)
prob_over_time.append(initial_prob.copy())

prob_over_time = np.array(prob_over_time)

plt.figure(figsize=(10, 6)) for state_idx in range(2**N): plt.plot(range(time_steps + 1), prob_over_time[:, state_idx], label=f"State {state_idx}")

plt.plot(range(time_steps + 1), prob_over_time[:, 3], label=f"State 3")

plt.xlabel("Time Step") plt.ylabel("Probability") plt.title("Probability Distribution Over Time for Each State with Decreasing Temperature") plt.legend() plt.show()

bitk20a commented 3 weeks ago

Transition Matrix_change sigmoid function.txt Ising Machine_Energy Check.txt Sigmoid function check.txt Transition Matrix.txt Change to txt.txt

bitk20a commented 3 weeks ago

Transition Matrix_CompareSigmoid changed_unchanged.txt