ferro_para_anim.py

Retour Ă  la liste des codes python.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#!/usr/env python3
# -*- coding: utf-8 -*-
import random as rd
import time
import numpy as np
from numpy import log, tanh, exp, sinh, cosh
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Slider, Button
from matplotlib.gridspec import GridSpec
plt.rcParams['font.family'] = 'monospace'

# Paramètres de la simulation
N = 64

# Paramères physiques
x = 0
mu = 1/2
muBperkB = 0.67  # SI
J = 0  # constante de couplage
ising = [-1, +1]  # Projections possibles des spins
Bswitch = 1

# ############################################################################
# Fonctions utiles
def MaxwellBoltzmann(s, i, j, norm=True):
    """ Retourne la proba que le spin (i,j) se trouve Ă  s """
    e = - mu*s * (x * Bswitch + J*x * mu*s_voisins(i, j))
    if norm:
        Z = np.sum([MaxwellBoltzmann(s2, i, j, norm=False) for s2 in ising])
    else:
        Z = 1
    return exp(-e) / Z

def choisir_s(i, j):
    probas = [MaxwellBoltzmann(s2, i, j) for s2 in ising]
    trigers = [0]
    for p in probas:
        trigers.append(trigers[-1] + p)
    trigers.remove(0)
    r = rd.random()
    for k in range(len(trigers)):
        if r < trigers[k]:
            return ising[k]
    else:
        return ising[-1]

def step():
    """ Avance le réseau d'un pas """
    # Choix du point Ă  mettre Ă  jour
    i, j = rd.randint(0, N-1), rd.randint(0, N-1)
    # Mise Ă  jour
    reseau[i, j] = choisir_s(i, j)


# ############################################################################
# Fonctions physiques
def s_voisins(i, j):
    """ Retourne le spin moyen des voisins de (i,j) """
    voisins = [(j-1,j), (i+1,j), (i,j-1), (i,j+1)]
    return np.sum([reseau[iv%N, jv%N] for iv,jv in voisins])

def valeurs_physiques(x, analytique=True):
    """ Calcule:
        - l'entropie volumique du réseau
        - l'aimantation volumique du réseau
    """
    if analytique:
        M = mu * tanh(x)
        S = - x * tanh(x) + log(2*cosh(x))
        return S, M
    else:
        N_calc = int(N*N/10)
        M = 0
        S = 0
        for k in range(N_calc):
            i, j = rd.randint(0, N-1), rd.randint(0, N-1)
        #for i in range(N):
        #    for j in range(N):
            M += mu * reseau[i, j]
            p = MaxwellBoltzmann(reseau[i, j], i, j)
            S -= p * log(p)
        return S/(N_calc), M/(N_calc)

def temp_Curie():
    """Xc= g^2    (muB/kB)^2    * kB        * J * p / 4 """
    return 2**2 * (muBperkB)**2 * J * 4 / 4

def BaTandTaB():
    BaT = "T = 1.0K, B = {:>3.3f}T".format(x * 1/muBperkB)
    TaB = "B = 1.0T, T = {:>3.3f}K".format(muBperkB*1/x if x != 0 else np.inf)
    return BaT, TaB



# ############################################################################
# Initialisation aléatoire du réseau de spins, sans couplage
reseau = np.ones((N, N), dtype=np.int8)
Jtmp, J = J, 0
for i in range(N):
    for j in range(N):
        reseau[i, j] = choisir_s(i, j)
J = Jtmp

# ############################################################################
Xmin, Xmax = -4, +4
Xspace = np.linspace(Xmin, Xmax, 100)
Jmin, Jmax = 0, 1

# #####
# Initialisation pyplot
fig = plt.figure(constrained_layout=True)
gs = GridSpec(2, 2, figure=fig)

# #####
# Image pour le réseau
ax_reseau = fig.add_subplot(gs[0, 0])
ax_reseau.set_xticks([]) ; ax_reseau.set_yticks([])
im = ax_reseau.imshow(reseau)

# #####
# Zone pour les données
ax_meta = fig.add_subplot(gs[0, 1])
ax_meta.set_xticks([]) ; ax_meta.set_yticks([]); ax_meta.axis('off')
# Légendes
ax_meta.plot(0, 0, color='r')
ax_meta.plot(0, 0, color='b')
ax_meta.legend(['s/k_B', 'M/M_s'], loc='lower right')
# Valeurs numériques
txt_fps = ax_meta.text(0, 0, '', transform=ax_meta.transAxes)
txt_BaT = ax_meta.text(0, 0.6, BaTandTaB()[0], transform=ax_meta.transAxes)
txt_TaB = ax_meta.text(0, 0.8, BaTandTaB()[1], transform=ax_meta.transAxes)
txt_M = ax_meta.text(0, 0.4, '', transform=ax_meta.transAxes)
txt_Xc = ax_meta.text(0, 0.0, '', transform=ax_meta.transAxes)

# #####
# Courbes f(X)
ax_courbes = fig.add_subplot(gs[1, :])
ax_courbes.set_xlim(Xmin, Xmax)
ax_courbes.set_xlabel('x = {:1.2f}'.format(x))
S, M = valeurs_physiques(Xspace)
line_S, = ax_courbes.plot(Xspace, S, color='r')
line_M, = ax_courbes.plot(Xspace, M, color='b')
XY_S, = ax_courbes.plot(0, 0, color='r', marker='o')
XY_M, = ax_courbes.plot(0, 0, color='b', marker='o')

# #####
# Mise Ă  jour avec sliders
def update_params(_):
    global x; x = slider_X.val
    global J; J = slider_J.val
    ax_courbes.set_xlabel('x = {:1.2f}'.format(x))
    txt_BaT.set_text(BaTandTaB()[0])
    txt_TaB.set_text(BaTandTaB()[1])
    txt_Xc.set_text("Xc = {:f}".format(temp_Curie()))
def switch_B(_):
    global Bswitch; Bswitch = 0 if (Bswitch==1) else 1
    button_B.color = 'r' if Bswitch==0 else 'w'
# Slider X
ax_X = ax_courbes.twinx()
slider_X = Slider(ax_X, '', Xmin, Xmax, x, alpha=0.2, color='k')
slider_X.valtext.set_visible(False)
slider_X.on_changed(update_params)
# Slider J
ax_J = plt.axes([0.1, 0.10, 0.6, 0.03])
slider_J = Slider(ax_J, 'J', Jmin, Jmax, J)
slider_J.on_changed(update_params)
# Boutton B
ax_bB = plt.axes([0.8, 0.10, 0.1, 0.03])
button_B = Button(ax_bB, 'B=0 ?', color='w')
button_B.on_clicked(switch_B)

# ############################################################################
# Simulation
def animate(i):
    # Mise à jour du réseau
    for n in range(int(N*N)):
        step()
    # Mise Ă  jour des textes
    ax_reseau.set_title("Génération {:3.0f}".format(i))
    #txt_fps.set_text("FPS {:>2.4f}".format(1 / (time.time() - t0)))
    # Mise à jour des données
    S, M = valeurs_physiques(x, False)
    txt_M.set_text("M/M_s = {:>+3.2f}".format(M))
    XY_S.set_data(x, S)
    XY_M.set_data(x, M)
    im.set_data(reseau)
    return im

anim = FuncAnimation(fig, animate, interval=1)

# Output
fig.subplots_adjust(bottom=0.2)  # Fait de la place pour les sliders
plt.show()

"""
Jij = 20
print(temp_Curie())
aim = []
for temp in np.linspace(0, 70, 100):
    T = temp
    aim2 = []
    for n in range(50):
        print("Calcul pour temp {}: {}".format(T, n))
        for n in range(int(N*N / 4)):
            step()
        aim2.append(valeurs_physiques(B, T, False)[1])
    aim.append(np.mean(aim2))

plt.plot(np.linspace(0, 70, 100), aim)
plt.show()
print(aim)
"""