Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
287 views
ubuntu2404
�

�8�h`*����dZddlZddlmZddlmZejjd�Gd�d�Z
Gd�d�Zd	�Zdd
�Z
d�Zd�Zd
�Zedk(r�e
dd��\ZZZeD�cgc]}|d��	c}ZeD�cgc]}|d��	c}ZeD�cgc]}|d��	c}Zed�ededd���ededd���eeee�e�e�yycc}wcc}wcc}w)a
Statistical Mechanics Monte Carlo Simulations
==============================================

This module implements Monte Carlo simulations for statistical mechanics systems:
- 2D Ising model with Metropolis algorithm
- Exact 1D Ising model solutions
- Thermodynamic property calculations
- Phase transition analysis

Keywords: ising model monte carlo, statistical mechanics python, metropolis algorithm,
phase transition simulation, partition function calculation, magnetic susceptibility

Author: CoCalc Scientific Templates
License: MIT
�N)�jit�*c��eZdZdZd
d�Zeed��d���Zeed��d���Zeed��d���Z	dd�Z
y	)�IsingModel2Du�
    2D Ising model Monte Carlo simulation using Metropolis algorithm.

    Hamiltonian: H = -J Σ_{<i,j>} S_i S_j - h Σ_i S_i
    where S_i = ±1 are spin variables.
    c��||_||_||_tjjddg||f��|_y)u�
        Parameters:
        -----------
        N : int
            Linear lattice size (N×N total spins)
        J : float
            Nearest-neighbor coupling constant
        h : float
            External magnetic field
        ������)�sizeN)�N�J�h�np�random�choice�spins)�selfrrr
s    �code/statistical_mechanics.py�__init__zIsingModel2D.__init__"s<������������Y�Y�%�%�r�1�g�Q��F�%�;��
�T)�nopythonc���|jd}d}t|�D]?}t|�D]/}|||dz|zf}||dz|z|f}|||||fz||zzz}�1�A||tj|�zz}|S)z,Calculate total energy of the configuration.r�r	)�shape�ranger�sum)	rrr
r�energy�i�j�right�downs	         r�total_energyzIsingModel2D.total_energy2s���
�K�K��N�����q��A��1�X���a�!�A�#���l�+���a��c�Q�Y��\�*���!�e�A�q�D�k�/�U�T�\�:�:����	�!�b�f�f�U�m�#�#���
rc���|jd}t||z�D]�}tjj	d|d�\}}|||dz|zf|||dz
|zfz||dz|z|fz||dz
|z|fz}d|z|||fz|zd|z|||fzz}	|	dks9tjj�tj
||	z�ks��|||fxxdzcc<��y)z)Perform one Metropolis Monte Carlo sweep.r�r	rN)rrrr�randint�exp)
r�betarr
r�_rr�	neighbors�delta_Es
          r�metropolis_stepzIsingModel2D.metropolis_stepDs��
�K�K��N���q�1�u��A��9�9�$�$�Q��1�-�D�A�q��q�1�Q�3�!�)�|�,�u�Q��1���	�\�/B�B��q��s�a�i��l�+�,�.3�Q�q�S�A�I�q�L�.A�B�I��!�e�e�A�q�D�k�)�I�5��A���a��d��8K�K�G���{�b�i�i�.�.�0�2�6�6�4�%�'�/�3J�J��a��d��r�!��rc�,�tj|�S)z!Calculate magnetization per site.)r�mean)rs r�
magnetizationzIsingModel2D.magnetizationXs���w�w�u�~�rc�z�d|z}t|�D]4}|j|j||j|j��6g}g}t|�D]�}|j|j||j|j�||zdk(s�>t|j
|j��}	|j|j|j|j�|jdzz}
|j|	�|j|
���tj|�}tj|�}tj|�}
tj|�}|||z|jdzz|
|dz|z|jdzz|jj�d�}|S)a�
        Run Monte Carlo simulation at given temperature.

        Parameters:
        -----------
        temperature : float
            Temperature T
        n_steps : int
            Number of Monte Carlo steps after equilibration
        n_equilibration : int
            Number of equilibration steps
        sample_interval : int
            Sampling interval for measurements

        Returns:
        --------
        observables : dict
            Dictionary containing measured observables
        ��?rr#)r-�susceptibilityr�
heat_capacity�final_configuration)rr*rrr
�absr-r!r�appendrr,�var�copy)r�temperature�n_steps�n_equilibration�sample_intervalr&�step�magnetizations�energies�magr�mag_mean�mag_var�energy_mean�
energy_var�observabless                r�simulatezIsingModel2D.simulate^ss��(�[� ���/�*�D�� � ����T�4�6�6�4�6�6�B�+������'�N�D�� � ����T�4�6�6�4�6�6�B��o�%��*��$�,�,�T�Z�Z�8�9���*�*�4�:�:�t�v�v�t�v�v�F�$�&�&�RS�)�T���%�%�c�*�����'�#��7�7�>�*���&�&��(���g�g�h�'���V�V�H�%�
�&�"�W�n�t�v�v�q�y�8�!�!�1�W�z�1�D�F�F�A�I�=�#'�:�:�?�?�#4�
���rN�r/r)����
)�__name__�
__module__�__qualname__�__doc__r�staticmethodrr!r*r-rD�rrrrst���<� ��$������ ��$��"���"�$��$������6rrc�&�eZdZdZdd�Zd�Zdd�Zy)�IsingModel1Dz�
    1D Ising model exact solution using transfer matrix method.

    The transfer matrix approach provides exact thermodynamic properties
    for comparison with Monte Carlo results and validation.
    c� �||_||_y)z�
        Parameters:
        -----------
        J : float
            Nearest-neighbor coupling constant
        h : float
            External magnetic field
        N�rr
)rrr
s   rrzIsingModel1D.__init__�s�������rc��d|z}tj||j|jzz�}tj||jz�}tj||jz�}tj||j|jz
z�}tj||g||gg�S)u�
        Construct transfer matrix for given temperature.

        Returns:
        --------
        T_matrix : ndarray
            2×2 transfer matrix
        r/)rr%rr
�array)rr7r&�T11�T12�T21�T22s       r�transfer_matrixzIsingModel1D.transfer_matrix�s����[� ���f�f�T�T�V�V�d�f�f�_�-�.���f�f�T�d�f�f�W�%�&���f�f�T�d�f�f�W�%�&���f�f�T�T�V�V�d�f�f�_�-�.���x�x�#�s��c�3�Z�0�1�1rNc�|�|j|�}tjj|�}tj|�}|tj
|�z}||d�}|�Vtjtjj||��}|tj
|�z}	||d<|	|d<|S)aQ
        Calculate exact thermodynamic properties.

        Parameters:
        -----------
        temperature : float
            Temperature T
        N : int, optional
            System size for finite-size calculations

        Returns:
        --------
        properties : dict
            Exact thermodynamic properties
        )�free_energy_per_site�eigenvalues�partition_function�free_energy_total)rYr�linalg�eigvals�max�log�trace�matrix_power)
rr7r�T_matrix�	eigenvals�
lambda_max�
f_per_site�
properties�Z�F_totals
          r�exact_propertieszIsingModel1D.exact_properties�s��� �'�'��4���I�I�%�%�h�/�	��V�V�I�&�
�"�\�B�F�F�:�$6�6�
�%/�$�
�
�
�=�������/�/��!�<�=�A�"�l�R�V�V�A�Y�.�G�/0�J�+�,�.5�J�*�+��rrE)N)rIrJrKrLrrYrlrNrrrPrP�s���
�2�&#rrPc�^�dtjdtjd�z�zS)ul
    Return the exact critical temperature for 2D Ising model.

    T_c = 2J / ln(1 + √2) ≈ 2.269 J
    g@r	r#)rrb�sqrtrNrr�critical_temperature_2dro�s$�������B�G�G�A�J��'�'�'rc
�P�td|�d|�d��tj|||�}t�}td|d���t	|dd��}g}t|�D]B\}}	td	|d
z�d|�d|	d
���|j
|	dd��}
|j|
��D|||fS)a�
    Study the magnetic phase transition in 2D Ising model.

    Parameters:
    -----------
    lattice_size : int
        Linear size of the lattice
    T_min, T_max : float
        Temperature range
    n_temps : int
        Number of temperature points

    Returns:
    --------
    temperatures : array
        Temperature points
    results : list
        List of simulation results at each temperature
    zPhase transition study: �×z latticez(Theoretical critical temperature: T_c = �.3fr/r)rrr
z  Temperature r	�/z: T = z.2frFrG)r8r9)�printr�linspaceror�	enumeraterDr4)�lattice_size�T_min�T_max�n_temps�temperatures�T_c�ising�resultsr�TrCs           r�phase_transition_studyr��s���(
�$�\�N�"�\�N�(�
K�L��;�;�u�e�W�5�L�
!�
#�C�	�4�S��I�
>�?��<�3�#�6�E��G��,�'���1�
��q��s�e�1�W�I�V�A�c�7�;�<��n�n�Q��d�n�K�����{�#�(�
��#�%�%rc���td�d}d}tjddd�}t||��}g}|D]&}|j	|d�	�}|j|��(td
t
|��d��||fS)zL
    Compare 1D Ising model exact solution with Monte Carlo simulation.
    z,=== 1D Ising Model: Exact vs Monte Carlo ===r/皙�����?��?�@�rR�d�rz Exact 1D calculation completed: z
 temperatures)rtrrurPrlr4�len)rr
r{�exact_model�
exact_resultsr�propss       r�exact_vs_monte_carlo_comparisonr�s���
�
8�9�	�A��A��;�;�s�C��,�L���a�(�K��M�
���,�,�Q�#�,�6�����U�#��
�,�S��->�,?�}�
M�N���&�&rc���td�tjddd�}tdd��}g}g}|D]=}|j	|d�	�}|j|d
�|j|d��?|||fS)z>
    Demonstrate calculation of thermodynamic properties.
    z&=== Thermodynamic Integration Demo ===r�r�r�r/r�rR�2r�r[r])rtrrurPrlr4)r{�model_1d�
free_energies�partition_functionsrr�s      r�thermodynamic_integration_demor�$s���
�
2�3��;�;�s�C��-�L��c�S�)�H��M���
���)�)�!�r�)�2�����U�#9�:�;��"�"�5�)=�#>�?��
��(;�;�;rc��tj||z
�dk}||}tj|�|}||k}tj|�dkDrv|||z
|z}tj||dz�}tj|dz�}	tj
|	|d�}
|
d}t
d|d���t
d�|St
d	�y
)u�
    Extract critical exponents from Monte Carlo data.

    Near T_c: m ∝ |T - T_c|^β where β ≈ 1/8 for 2D Ising model
    r��g�����|�=r	ru!Estimated critical exponent β = rruTheoretical value β = 0.125zCInsufficient data points below T_c for critical exponent extractionN)rr3rTrrb�polyfitrt)r{r<r|�mask�T_fit�m_fit�below_Tc�reduced_temp�log_m�log_t�coeffs�
beta_criticals            r�extract_critical_exponentsr�8s����6�6�,��$�%��+�D����E��H�H�^�$�T�*�E��s�{�H�	�v�v�h��!���e�H�o�-��4�����u�X���.�/�����|�e�+�,�����E�5�!�,���q�	�
�
�1�-��1D�E�F�
�,�.���
�S�T�r�__main__� rH)rwrzr-rr0z
Final results:zLowest T magnetization: z.4fzHighest T magnetization: r)�@r/g@r�)rL�numpyr�matplotlib.pyplot�pyplot�plt�numbarr�seedrrPror�r�r�r�rIr{r~r|r<r=�susceptibilitiesrt)�rs0r�<module>r�s,���"����	�	���r��z�z�xJ�J�X(�"&�H'�,<�(�<�z��!7�R�QS�!T��L�'�3�3:�:�'�Q�a��(�'�:�N�%,�-�W���(��W�-�H�5<�=�W���*�+�W�=��	���	�$�^�A�%6�s�$;�
<�=�	�%�n�R�&8��%=�
>�?��|�^�S�A�$�%�"�$�%��
;��-��=s�)C�<C#�C(