Skip to content

utils

detailed_balance

detailed_balance_factor(energy, temperature, energy_unit='meV', temperature_unit='K', divide_by_temperature=True)

Compute the detailed balance factor (DBF): $$ DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E / (k_B*T)})}}, $$ where \(n(E)\) is the Bose-Einstein distribution, \(E\) is the energy transfer, and \(T\) is the temperature. \(k_B\) is the Boltzmann constant. If divide_by_temperature is True, the result is normalized by \(k_B*T\) to have value 1 at \(E=0\).

Parameters:

Name Type Description Default
energy int | float | list | ndarray | Variable

The energy transfer. If number, assumed to be in meV unless energy_unit is set.

required
temperature int | float | Variable | Parameter

The temperature. If number, assumed to be in K unless temperature_unit is set.

required
energy_unit str | sc.Unit, default='meV'

Unit for energy if energy is given as a number or list. Default is 'meV'

'meV'
temperature_unit str | sc.Unit, default='K'

Unit for temperature if temperature is given as a number. Default is 'K'

'K'
divide_by_temperature bool, default=True

If True, divide the result by \(k_B*T\) to make it dimensionless and have value 1 at E=0. Default is True.

True

Returns:

Type Description
ndarray

np.ndarray: Detailed balance factor evaluated at the given energy and temperature.

Raises:

Type Description
TypeError

If energy or temperature is not a number, list, numpy array, or scipp Variable, or if energy_unit or temperature_unit is not a string or scipp Unit, or if divide_by_temperature is not a boolean.

ValueError

If temperature is negative, or if energy is a numpy array with more than 1 dimension, or if temperature is a scipp Variable that does not have a single dimension named 'temperature', or if energy is a scipp Variable that does not have a single dimension named 'energy'.

UnitError

If the provided energy_unit or temperature_unit is invalid, or if the units of energy or temperature cannot be converted to the expected units.

ZeroDivisionError

If divide_by_temperature is True and temperature is zero.

Examples:

detailed_balance_factor(1.0, 300) # 1 meV at 300 K detailed_balance_factor( ... energy=[1.0, 2.0], ... temperature=300, ... energy_unit='microeV', ... temperature_unit='K', ... divide_by_temperature=False, ... )

Source code in src/easydynamics/utils/detailed_balance.py
 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
def detailed_balance_factor(
    energy: int | float | list | np.ndarray | sc.Variable,
    temperature: int | float | sc.Variable | Parameter,
    energy_unit: str | sc.Unit = 'meV',
    temperature_unit: str | sc.Unit = 'K',
    divide_by_temperature: bool = True,
) -> np.ndarray:
    r"""
    Compute the detailed balance factor (DBF):
    $$
    DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E / (k_B*T)})}},
    $$
    where $n(E)$ is the Bose-Einstein distribution, $E$ is the energy
    transfer, and $T$ is the temperature. $k_B$ is the Boltzmann
    constant.
    If divide_by_temperature is True, the result is normalized by
    $k_B*T$ to have value 1 at $E=0$.

    Args:
        energy (int | float | list | np.ndarray | sc.Variable): The energy
            transfer. If number, assumed to be in meV unless energy_unit
            is set.
        temperature (int | float | sc.Variable | Parameter): The
            temperature. If number, assumed to be in K unless
            temperature_unit is set.
        energy_unit (str | sc.Unit, default='meV'): Unit for energy if energy is
            given as a number or list. Default is 'meV'
        temperature_unit (str | sc.Unit, default='K'): Unit for temperature if
            temperature is given as a number. Default is 'K'
        divide_by_temperature (bool, default=True): If True, divide the result
            by $k_B*T$ to make it dimensionless and have value 1 at E=0.
            Default is True.

    Returns:
        np.ndarray:  Detailed balance factor evaluated at the
            given energy and temperature.

    Raises:
        TypeError: If energy or temperature is not a number, list,
            numpy array, or scipp Variable, or if energy_unit or
            temperature_unit is not a string or scipp Unit,
            or if divide_by_temperature is not a boolean.
        ValueError: If temperature is negative, or if energy is a numpy
            array with more than 1 dimension, or if temperature is a
            scipp Variable that does not have a single dimension named
            'temperature', or if energy is a scipp Variable that does
            not have a single dimension named 'energy'.
        UnitError: If the provided energy_unit or temperature_unit is
            invalid, or if the units of energy or temperature cannot be
            converted to the expected units.
        ZeroDivisionError: If divide_by_temperature is True and temperature is zero.

    Examples:
    >>> detailed_balance_factor(1.0, 300)  # 1 meV at 300 K
    >>> detailed_balance_factor(
    ...     energy=[1.0, 2.0],
    ...     temperature=300,
    ...     energy_unit='microeV',
    ...     temperature_unit='K',
    ...     divide_by_temperature=False,
    ... )
    """

    # Input validation
    if not isinstance(divide_by_temperature, bool):
        raise TypeError('divide_by_temperature must be True or False.')

    if not isinstance(energy_unit, (str, sc.Unit)):
        raise TypeError('energy_unit must be a string or scipp.Unit.')

    if not isinstance(temperature_unit, (str, sc.Unit)):
        raise TypeError('temperature_unit must be a string or scipp.Unit.')

    # Convert temperature and energy to sc variables
    # to make units easy to handle
    temperature = _convert_to_scipp_variable(
        value=temperature, unit=temperature_unit, name='temperature'
    )

    if temperature.value < 0:
        raise ValueError('Temperature must be non-negative.')

    energy = _convert_to_scipp_variable(value=energy, unit=energy_unit, name='energy')

    # What if people give units that don't make sense?
    try:
        sc.to_unit(energy, unit='meV')
    except Exception as e:
        raise UnitError(
            f'The unit of energy is wrong: {energy.unit}: {e} Check that energy has a valid unit.'
        ) from e
    # We give users the option to specify the unit of the energy,
    # but if the input has a unit, they might clash
    if energy.unit != energy_unit:
        warnings.warn(
            f'Input energy has unit {energy.unit}, but energy_unit was set to {energy_unit}. '
            f'Using {energy.unit}.',
            stacklevel=2,
        )

    # Same for temperature
    try:
        sc.to_unit(temperature, unit='K')
    except Exception as e:
        raise UnitError(
            f'The unit of temperature is wrong: {temperature.unit}: {e} '
            f'Check that temperature has a valid unit.'
        ) from e

    if temperature.unit != temperature_unit:
        warnings.warn(
            f'Input temperature has unit {temperature.unit}, '
            f'but temperature_unit was set to {temperature_unit}. Using {temperature.unit}.',
            stacklevel=2,
        )

    # Zero temperature deserves special treatment.
    # Here, DBF is 0 for energy<0 and energy for energy>0
    if temperature.value == 0:
        if divide_by_temperature:
            raise ZeroDivisionError('Cannot divide by T when T = 0.')
        DBF = sc.where(energy < 0.0 * energy.unit, 0.0 * energy.unit, energy)

        return np.array([DBF.value]) if DBF.sizes == {} else DBF.values

    # Now work with finite temperatures.
    # Here, it helps to work with dimensionless x = energy/(kB*T),
    # where we have divided by kB*T
    # We first check if the units are OK.

    x = energy / (kB * temperature)

    x = sc.to_unit(x, unit='1')  # Make sure the unit is 1 and not e.g. 1e3

    # Now compute DBF. First handle small and large x, then general.

    # Small x (small energy and/or high temperature): Taylor expansion.
    # Works and is needed for both positive and negative energies
    small = sc.abs(x) < SMALL_THRESHOLD

    DBF = sc.where(small, 1 + x / 2 + x**2 / 12, sc.zeros_like(x))

    # Large x (large positive energy and/or low temperature):
    # asymptotic form. Only needed for positive energies.
    large = x > LARGE_THRESHOLD
    DBF = sc.where(large, x, DBF)

    # General case: exact formula
    mid = sc.logical_not(small) & sc.logical_not(large)
    DBF = sc.where(mid, x / (1 - sc.exp(-x)), DBF)  # zeros in x are handled by SMALL_THRESHOLD

    #
    if not divide_by_temperature:
        DBF = DBF * (kB * temperature)
        DBF = sc.to_unit(DBF, unit=energy.unit)

    return np.array([DBF.value]) if DBF.sizes == {} else DBF.values

detailed_balance_factor(energy, temperature, energy_unit='meV', temperature_unit='K', divide_by_temperature=True)

Compute the detailed balance factor (DBF): $$ DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E / (k_B*T)})}}, $$ where \(n(E)\) is the Bose-Einstein distribution, \(E\) is the energy transfer, and \(T\) is the temperature. \(k_B\) is the Boltzmann constant. If divide_by_temperature is True, the result is normalized by \(k_B*T\) to have value 1 at \(E=0\).

Parameters:

Name Type Description Default
energy int | float | list | ndarray | Variable

The energy transfer. If number, assumed to be in meV unless energy_unit is set.

required
temperature int | float | Variable | Parameter

The temperature. If number, assumed to be in K unless temperature_unit is set.

required
energy_unit str | sc.Unit, default='meV'

Unit for energy if energy is given as a number or list. Default is 'meV'

'meV'
temperature_unit str | sc.Unit, default='K'

Unit for temperature if temperature is given as a number. Default is 'K'

'K'
divide_by_temperature bool, default=True

If True, divide the result by \(k_B*T\) to make it dimensionless and have value 1 at E=0. Default is True.

True

Returns:

Type Description
ndarray

np.ndarray: Detailed balance factor evaluated at the given energy and temperature.

Raises:

Type Description
TypeError

If energy or temperature is not a number, list, numpy array, or scipp Variable, or if energy_unit or temperature_unit is not a string or scipp Unit, or if divide_by_temperature is not a boolean.

ValueError

If temperature is negative, or if energy is a numpy array with more than 1 dimension, or if temperature is a scipp Variable that does not have a single dimension named 'temperature', or if energy is a scipp Variable that does not have a single dimension named 'energy'.

UnitError

If the provided energy_unit or temperature_unit is invalid, or if the units of energy or temperature cannot be converted to the expected units.

ZeroDivisionError

If divide_by_temperature is True and temperature is zero.

Examples:

detailed_balance_factor(1.0, 300) # 1 meV at 300 K detailed_balance_factor( ... energy=[1.0, 2.0], ... temperature=300, ... energy_unit='microeV', ... temperature_unit='K', ... divide_by_temperature=False, ... )

Source code in src/easydynamics/utils/detailed_balance.py
 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
def detailed_balance_factor(
    energy: int | float | list | np.ndarray | sc.Variable,
    temperature: int | float | sc.Variable | Parameter,
    energy_unit: str | sc.Unit = 'meV',
    temperature_unit: str | sc.Unit = 'K',
    divide_by_temperature: bool = True,
) -> np.ndarray:
    r"""
    Compute the detailed balance factor (DBF):
    $$
    DBF(E, T) = E(n(E)+1)=\frac{E}{(1 - e^{-E / (k_B*T)})}},
    $$
    where $n(E)$ is the Bose-Einstein distribution, $E$ is the energy
    transfer, and $T$ is the temperature. $k_B$ is the Boltzmann
    constant.
    If divide_by_temperature is True, the result is normalized by
    $k_B*T$ to have value 1 at $E=0$.

    Args:
        energy (int | float | list | np.ndarray | sc.Variable): The energy
            transfer. If number, assumed to be in meV unless energy_unit
            is set.
        temperature (int | float | sc.Variable | Parameter): The
            temperature. If number, assumed to be in K unless
            temperature_unit is set.
        energy_unit (str | sc.Unit, default='meV'): Unit for energy if energy is
            given as a number or list. Default is 'meV'
        temperature_unit (str | sc.Unit, default='K'): Unit for temperature if
            temperature is given as a number. Default is 'K'
        divide_by_temperature (bool, default=True): If True, divide the result
            by $k_B*T$ to make it dimensionless and have value 1 at E=0.
            Default is True.

    Returns:
        np.ndarray:  Detailed balance factor evaluated at the
            given energy and temperature.

    Raises:
        TypeError: If energy or temperature is not a number, list,
            numpy array, or scipp Variable, or if energy_unit or
            temperature_unit is not a string or scipp Unit,
            or if divide_by_temperature is not a boolean.
        ValueError: If temperature is negative, or if energy is a numpy
            array with more than 1 dimension, or if temperature is a
            scipp Variable that does not have a single dimension named
            'temperature', or if energy is a scipp Variable that does
            not have a single dimension named 'energy'.
        UnitError: If the provided energy_unit or temperature_unit is
            invalid, or if the units of energy or temperature cannot be
            converted to the expected units.
        ZeroDivisionError: If divide_by_temperature is True and temperature is zero.

    Examples:
    >>> detailed_balance_factor(1.0, 300)  # 1 meV at 300 K
    >>> detailed_balance_factor(
    ...     energy=[1.0, 2.0],
    ...     temperature=300,
    ...     energy_unit='microeV',
    ...     temperature_unit='K',
    ...     divide_by_temperature=False,
    ... )
    """

    # Input validation
    if not isinstance(divide_by_temperature, bool):
        raise TypeError('divide_by_temperature must be True or False.')

    if not isinstance(energy_unit, (str, sc.Unit)):
        raise TypeError('energy_unit must be a string or scipp.Unit.')

    if not isinstance(temperature_unit, (str, sc.Unit)):
        raise TypeError('temperature_unit must be a string or scipp.Unit.')

    # Convert temperature and energy to sc variables
    # to make units easy to handle
    temperature = _convert_to_scipp_variable(
        value=temperature, unit=temperature_unit, name='temperature'
    )

    if temperature.value < 0:
        raise ValueError('Temperature must be non-negative.')

    energy = _convert_to_scipp_variable(value=energy, unit=energy_unit, name='energy')

    # What if people give units that don't make sense?
    try:
        sc.to_unit(energy, unit='meV')
    except Exception as e:
        raise UnitError(
            f'The unit of energy is wrong: {energy.unit}: {e} Check that energy has a valid unit.'
        ) from e
    # We give users the option to specify the unit of the energy,
    # but if the input has a unit, they might clash
    if energy.unit != energy_unit:
        warnings.warn(
            f'Input energy has unit {energy.unit}, but energy_unit was set to {energy_unit}. '
            f'Using {energy.unit}.',
            stacklevel=2,
        )

    # Same for temperature
    try:
        sc.to_unit(temperature, unit='K')
    except Exception as e:
        raise UnitError(
            f'The unit of temperature is wrong: {temperature.unit}: {e} '
            f'Check that temperature has a valid unit.'
        ) from e

    if temperature.unit != temperature_unit:
        warnings.warn(
            f'Input temperature has unit {temperature.unit}, '
            f'but temperature_unit was set to {temperature_unit}. Using {temperature.unit}.',
            stacklevel=2,
        )

    # Zero temperature deserves special treatment.
    # Here, DBF is 0 for energy<0 and energy for energy>0
    if temperature.value == 0:
        if divide_by_temperature:
            raise ZeroDivisionError('Cannot divide by T when T = 0.')
        DBF = sc.where(energy < 0.0 * energy.unit, 0.0 * energy.unit, energy)

        return np.array([DBF.value]) if DBF.sizes == {} else DBF.values

    # Now work with finite temperatures.
    # Here, it helps to work with dimensionless x = energy/(kB*T),
    # where we have divided by kB*T
    # We first check if the units are OK.

    x = energy / (kB * temperature)

    x = sc.to_unit(x, unit='1')  # Make sure the unit is 1 and not e.g. 1e3

    # Now compute DBF. First handle small and large x, then general.

    # Small x (small energy and/or high temperature): Taylor expansion.
    # Works and is needed for both positive and negative energies
    small = sc.abs(x) < SMALL_THRESHOLD

    DBF = sc.where(small, 1 + x / 2 + x**2 / 12, sc.zeros_like(x))

    # Large x (large positive energy and/or low temperature):
    # asymptotic form. Only needed for positive energies.
    large = x > LARGE_THRESHOLD
    DBF = sc.where(large, x, DBF)

    # General case: exact formula
    mid = sc.logical_not(small) & sc.logical_not(large)
    DBF = sc.where(mid, x / (1 - sc.exp(-x)), DBF)  # zeros in x are handled by SMALL_THRESHOLD

    #
    if not divide_by_temperature:
        DBF = DBF * (kB * temperature)
        DBF = sc.to_unit(DBF, unit=energy.unit)

    return np.array([DBF.value]) if DBF.sizes == {} else DBF.values

utils