• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

zincware / MDSuite / 3999396905

pending completion
3999396905

push

github-actions

GitHub
[merge before other PRs] ruff updates (#580)

960 of 1311 branches covered (73.23%)

Branch coverage included in aggregate %.

15 of 15 new or added lines in 11 files covered. (100.0%)

4034 of 4930 relevant lines covered (81.83%)

3.19 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

36.36
/mdsuite/calculators/einstein_helfand_thermal_kinaci.py
1
"""
2
MDSuite: A Zincwarecode package.
3

4
License
5
-------
6
This program and the accompanying materials are made available under the terms
7
of the Eclipse Public License v2.0 which accompanies this distribution, and is
8
available at https://www.eclipse.org/legal/epl-v20.html
9

10
SPDX-License-Identifier: EPL-2.0
11

12
Copyright Contributors to the Zincwarecode Project.
13

14
Contact Information
15
-------------------
16
email: zincwarecode@gmail.com
17
github: https://github.com/zincware
18
web: https://zincwarecode.com/
19

20
Citation
21
--------
22
If you use this module please cite us with:
23

24
Summary
25
-------
26
MDSuite module for the computation of the thermal conductivity in solids using the
27
Einstein method as applied to the Kinaci integrated thermal flux.
28
"""
29
from abc import ABC
4✔
30
from dataclasses import dataclass
4✔
31

32
import numpy as np
4✔
33
import tensorflow as tf
4✔
34
from tqdm import tqdm
4✔
35

36
from mdsuite.calculators.calculator import call
4✔
37
from mdsuite.calculators.trajectory_calculator import TrajectoryCalculator
4✔
38
from mdsuite.database.mdsuite_properties import mdsuite_properties
4✔
39
from mdsuite.utils.calculator_helper_methods import fit_einstein_curve
4✔
40

41

42
@dataclass
4✔
43
class Args:
3✔
44
    """Data class for the saved properties."""
45

46
    data_range: int
4✔
47
    correlation_time: int
4✔
48
    tau_values: np.s_
4✔
49
    atom_selection: np.s_
4✔
50
    fit_range: int
4✔
51

52

53
class EinsteinHelfandThermalKinaci(TrajectoryCalculator, ABC):
4✔
54
    """
55
    Class for the Einstein-Helfand Ionic Conductivity.
56

57
    Attributes
58
    ----------
59
    experiment :  object
60
            Experiment class to call from
61
    x_label : str
62
            X label of the tensor_values when plotted
63
    y_label : str
64
            Y label of the tensor_values when plotted
65
    analysis_name : str
66
            Name of the analysis
67
    loaded_property : str
68
            Property loaded from the database_path for the analysis
69

70
    See Also
71
    --------
72
    mdsuite.calculators.calculator.Calculator
73

74
    Examples
75
    --------
76
    experiment.run_computation.EinsteinHelfandThermalKinaci(data_range=500,
77
                                                            plot=True,
78
                                                            correlation_time=10)
79

80
    """
81

82
    def __init__(self, **kwargs):
4✔
83
        """
84
        Python constructor.
85

86
        Parameters
87
        ----------
88
        experiment :  object
89
            Experiment class to call from
90
        """
91
        # parse to the experiment class
92
        super().__init__(**kwargs)
×
93
        self.scale_function = {"linear": {"scale_factor": 5}}
×
94

95
        self.loaded_property = mdsuite_properties.kinaci_heat_current
×
96
        self.dependency = mdsuite_properties.unwrapped_positions
×
97
        self.system_property = True
×
98

99
        self.x_label = r"$$\text{Time} / s)$$"
×
100
        self.y_label = r"$$\text{MSD} / m^2/s$$"
×
101
        self.analysis_name = "Einstein Helfand Thermal Conductivity Kinaci"
×
102

103
        self._dtype = tf.float64
×
104

105
        self.prefactor = None
×
106

107
    @call
4✔
108
    def __call__(
4✔
109
        self,
110
        plot=True,
111
        data_range=500,
112
        correlation_time=1,
113
        tau_values: np.s_ = np.s_[:],
114
        fit_range: int = -1,
115
    ):
116
        """
117
        Python constructor.
118

119
        Parameters
120
        ----------
121
        plot : bool
122
                if true, plot the output.
123
        data_range : int
124
                Data range to use in the analysis.
125

126
        correlation_time : int
127
                Correlation time to use in the window sampling.
128
        """
129
        if fit_range == -1:
×
130
            fit_range = int(data_range - 1)
×
131

132
        # set args that will affect the computation result
133
        self.args = Args(
×
134
            data_range=data_range,
135
            correlation_time=correlation_time,
136
            tau_values=tau_values,
137
            atom_selection=np.s_[:],
138
            fit_range=fit_range,
139
        )
140

141
        self.plot = plot
×
142
        self.time = self._handle_tau_values()
×
143
        self.msd_array = np.zeros(self.data_resolution)
×
144

145
    def check_input(self):
4✔
146
        """
147
        Check the user input to ensure no conflicts are present.
148

149
        Returns
150
        -------
151

152
        """
153
        self._run_dependency_check()
×
154

155
    def _calculate_prefactor(self):
4✔
156
        """
157
        Compute the ionic conductivity prefactor.
158

159
        Returns
160
        -------
161

162
        """
163
        # Calculate the prefactor
164
        numerator = 1
×
165
        denominator = (
×
166
            self.experiment.volume
167
            * self.experiment.temperature
168
            * self.experiment.units.boltzmann
169
        )
170
        units_change = (
×
171
            self.experiment.units.energy
172
            / self.experiment.units.length
173
            / self.experiment.units.time
174
            / self.experiment.units.temperature
175
        )
176
        self.prefactor = numerator / denominator * units_change
×
177

178
    def _apply_averaging_factor(self):
4✔
179
        """
180
        Apply the averaging factor to the msd array.
181

182
        Returns
183
        -------
184
        -------.
185

186
        """
187
        self.msd_array /= int(self.n_batches) * self.ensemble_loop
×
188

189
    def ensemble_operation(self, ensemble):
4✔
190
        """
191
        Calculate and return the msd.
192

193
        Parameters
194
        ----------
195
        ensemble
196

197
        Returns
198
        -------
199
        MSD of the tensor_values.
200
        """
201
        msd = tf.math.squared_difference(ensemble, ensemble[None, 0])
×
202

203
        msd = self.prefactor * tf.reduce_sum(msd, axis=1)
×
204
        self.msd_array += np.array(msd)  # Update the averaged function
×
205

206
    def _post_operation_processes(self):
4✔
207
        """
208
        call the post-op processes
209
        Returns
210
        -------.
211

212
        """
213
        fit_values, covariance, gradients, gradient_errors = fit_einstein_curve(
×
214
            x_data=self.time, y_data=self.msd_array, fit_max_index=self.args.fit_range
215
        )
216
        error = np.sqrt(np.diag(covariance))[0]
×
217

218
        data = {
×
219
            "thermal_conductivity": 1 / 6 * fit_values[0],
220
            "uncertainty": 1 / 6 * error,
221
            "time": self.time.tolist(),
222
            "msd": self.msd_array.tolist(),
223
        }
224

225
        self.queue_data(data=data, subjects=["System"])
×
226

227
        # Update the plot if required
228
        if self.plot:
×
229
            self.run_visualization(
×
230
                x_data=np.array(self.time) * self.experiment.units.time,
231
                y_data=self.msd_array * self.experiment.units.time,
232
                title=f"{fit_values[0]} +- {error}",
233
            )
234

235
    def run_calculator(self):
4✔
236
        """
237
        Run analysis.
238

239
        Returns
240
        -------
241

242
        """
243
        self.check_input()
×
244
        # Compute the pre-factor early.
245
        self._calculate_prefactor()
×
246

247
        dict_ref = str.encode(
×
248
            "/".join([self.loaded_property.name, self.loaded_property.name])
249
        )
250

251
        batch_ds = self.get_batch_dataset([self.loaded_property.name])
×
252

253
        for batch in tqdm(
×
254
            batch_ds,
255
            ncols=70,
256
            total=self.n_batches,
257
            disable=self.memory_manager.minibatch,
258
        ):
259
            ensemble_ds = self.get_ensemble_dataset(batch, self.loaded_property.name)
×
260

261
            for ensemble in ensemble_ds:
×
262
                self.ensemble_operation(ensemble[dict_ref])
×
263

264
        # Scale, save, and plot the data.
265
        self._apply_averaging_factor()
×
266
        self._post_operation_processes()
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc