Skip to content

Commit c2b8465

Browse files
committed
added pytest to most
1 parent 0996756 commit c2b8465

File tree

7 files changed

+120
-64
lines changed

7 files changed

+120
-64
lines changed

docs/source/chapters/chapter1.rst

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,10 @@ and copy the following lines into it:
280280
assert not issubclass(Utilities, MonteCarlo), "Utilities should not inherit from MonteCarlo"
281281
print("Utilities does not inherit from MonteCarlo, as expected")
282282
283-
test_utilities_does_not_inherit_from_montecarlo()
284-
test_montecarlo_inherits_from_utilities()
283+
# In the script is launched with Python, call Pytest
284+
if __name__ == "__main__":
285+
import pytest
286+
pytest.main(["-s", __file__])
285287
286288
.. label:: end_test_1a_class
287289

@@ -318,8 +320,10 @@ called *test_1b.py*, copy the following lines:
318320
except Exception as e:
319321
print(f"Method call raised an error: {e}")
320322
321-
# Make sure that the method call succeeded
322-
test_init_method()
323+
# In the script is launched with Python, call Pytest
324+
if __name__ == "__main__":
325+
import pytest
326+
pytest.main(["-s", __file__])
323327
324328
.. label:: end_test_1b_class
325329

docs/source/chapters/chapter2.rst

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -382,20 +382,25 @@ type 1, and 3 atoms of type 2:
382382
import numpy as np
383383
from Prepare import Prepare
384384
385-
prep = Prepare(number_atoms=[2, 3],
385+
# Initialize the Prepare object
386+
prep = Prepare(
387+
number_atoms=[2, 3],
386388
epsilon=[0.2, 0.4], # kcal/mol
387389
sigma=[3, 4], # A
388390
atom_mass=[10, 20], # g/mol
389-
)
391+
)
390392
391-
def test_array(result, expected):
392-
"""Test function comparing *result* and *expected*"""
393+
# Test function using pytest
394+
def test_atoms_epsilon():
395+
expected = np.array([1., 1., 2., 2., 2.])
396+
result = prep.atoms_epsilon
393397
assert np.array_equal(result, expected), f"Test failed: {result} != {expected}"
394398
print("Test passed")
395399
396-
# Make sure the *atoms_epsilon* gives the expected values
397-
# of 1 1 2 2 2 (in LJ units)
398-
test_array(prep.atoms_epsilon, np.array([1., 1., 2., 2., 2.]))
400+
# In the script is launched with Python, call Pytest
401+
if __name__ == "__main__":
402+
import pytest
403+
pytest.main(["-s", __file__])
399404
400405
.. label:: end_test_2a_class
401406

docs/source/chapters/chapter3.rst

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -229,19 +229,28 @@ boundaries along all 3 dimensions of space:
229229
import numpy as np
230230
from InitializeSimulation import InitializeSimulation
231231
232-
init = InitializeSimulation(number_atoms=[2, 3],
232+
# Initialize the InitializeSimulation object
233+
init = InitializeSimulation(
234+
number_atoms=[2, 3],
233235
epsilon=[0.2, 0.4], # kcal/mol
234236
sigma=[3, 4], # A
235237
atom_mass=[10, 20], # g/mol
236238
box_dimensions=[20, 20, 20], # A
237-
)
239+
)
238240
239-
def test_placement(box_boundaries, atoms_positions):
240-
"""Ensure that atoms are placed within the box"""
241+
# Test function using pytest
242+
def test_placement():
243+
box_boundaries = init.box_boundaries
244+
atoms_positions = init.atoms_positions
241245
for atom_position in atoms_positions:
242246
for x, boundary in zip(atom_position, box_boundaries):
243-
assert (x >= boundary[0]) & (x <= boundary[1]), f"Test failed: Atoms outside of the box"
247+
assert (x >= boundary[0]) and (x <= boundary[1]), f"Test failed: Atoms outside of the box at position {atom_position}"
244248
print("Test passed")
245-
test_placement(init.box_boundaries, init.atoms_positions)
249+
250+
# If the script is run directly, execute the tests
251+
if __name__ == "__main__":
252+
import pytest
253+
# Run pytest programmatically
254+
pytest.main(["-s", __file__])
246255
247256
.. label:: end_test_3a_class

docs/source/chapters/chapter4.rst

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -353,20 +353,31 @@ typically negative.
353353
354354
from MinimizeEnergy import MinimizeEnergy
355355
356-
min = MinimizeEnergy(maximum_steps=100,
356+
# Initialize the MinimizeEnergy object and run the minimization
357+
minimizer = MinimizeEnergy(
358+
maximum_steps=100,
357359
number_atoms=[2, 3],
358360
epsilon=[0.2, 0.4], # kcal/mol
359361
sigma=[3, 4], # A
360362
atom_mass=[10, 20], # g/mol
361363
box_dimensions=[20, 20, 20], # A
362-
)
363-
min.run()
364-
365-
Final_Epot = min.Epot
366-
Final_MaxF = min.MaxF
367-
assert Final_Epot < 0, f"Test failed: Final energy too large"
368-
assert Final_MaxF < 10, f"Test failed: Final max force too large"
369-
print("Test passed")
364+
)
365+
minimizer.run()
366+
367+
# Test function using pytest
368+
def test_energy_and_force():
369+
Final_Epot = minimizer.Epot
370+
Final_MaxF = minimizer.MaxF
371+
assert Final_Epot < 0, f"Test failed: Final energy too large: {Final_Epot}"
372+
assert Final_MaxF < 10, f"Test failed: Final max force too large: {Final_MaxF}"
373+
print("Test passed")
374+
375+
# If the script is run directly, execute the tests
376+
if __name__ == "__main__":
377+
import pytest
378+
# Run pytest programmatically
379+
pytest.main(["-s", __file__])
380+
370381
371382
.. label:: end_test_4a_class
372383

docs/source/chapters/chapter5.rst

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -211,21 +211,32 @@ files were indeed created without the *Outputs/* folder:
211211
import os
212212
from MinimizeEnergy import MinimizeEnergy
213213
214-
min = MinimizeEnergy(maximum_steps=100,
214+
# Initialize the MinimizeEnergy object and run the minimization
215+
minimizer = MinimizeEnergy(
216+
maximum_steps=100,
215217
thermo_period=25,
216218
dumping_period=25,
217-
thermo_outputs = "Epot-MaxF",
219+
thermo_outputs="Epot-MaxF",
218220
number_atoms=[2, 3],
219221
epsilon=[0.1, 1.0], # kcal/mol
220222
sigma=[3, 4], # A
221223
atom_mass=[10, 20], # g/mol
222224
box_dimensions=[20, 20, 20], # A
223225
data_folder="Outputs/",
224-
)
225-
min.run()
226-
227-
assert os.path.exists("Outputs/dump.min.lammpstrj"), f"Test failed: dump file was not created"
228-
assert os.path.exists("Outputs/simulation.log"), f"Test failed: log file was not created"
226+
)
227+
minimizer.run()
228+
229+
# Test function using pytest
230+
def test_output_files():
231+
assert os.path.exists("Outputs/dump.min.lammpstrj"), "Test failed: dump file was not created"
232+
assert os.path.exists("Outputs/simulation.log"), "Test failed: log file was not created"
233+
print("Test passed")
234+
235+
# If the script is run directly, execute the tests
236+
if __name__ == "__main__":
237+
import pytest
238+
# Run pytest programmatically
239+
pytest.main(["-s", __file__])
229240
230241
.. label:: end_test_5a_class
231242

docs/source/chapters/chapter7.rst

Lines changed: 46 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -96,53 +96,69 @@ chosen to make the calculation faster.
9696
9797
import numpy as np
9898
from MonteCarlo import MonteCarlo
99-
10099
from scipy import constants as cst
101100
from pint import UnitRegistry
101+
from reader import import_data
102+
103+
# Initialize the unit registry
102104
ureg = UnitRegistry()
103105
104106
# Constants
105-
kB = cst.Boltzmann*ureg.J/ureg.kelvin # boltzman constant
106-
Na = cst.Avogadro/ureg.mole # avogadro
107-
R = kB*Na # gas constant
107+
kB = cst.Boltzmann * ureg.J / ureg.kelvin # Boltzmann constant
108+
Na = cst.Avogadro / ureg.mole # Avogadro's number
109+
R = kB * Na # Gas constant
108110
109111
# Parameters taken from Wood1957
110-
tau = 2 # ratio between volume / reduced volume
111-
epsilon = (119.76*ureg.kelvin*kB*Na).to(ureg.kcal/ureg.mol) # kcal/mol
112-
r_star = 3.822*ureg.angstrom # angstrom
113-
sigma = r_star / 2**(1/6) # angstrom
114-
N_atom = 50 # no units
115-
m_argon = 39.948*ureg.gram/ureg.mol # g/mol
116-
T = 328.15 * ureg.degK # 328 K or 55°C
112+
tau = 2 # Ratio between volume / reduced volume
113+
epsilon = (119.76 * ureg.kelvin * kB * Na).to(ureg.kcal / ureg.mol) # kcal/mol
114+
r_star = 3.822 * ureg.angstrom # Angstrom
115+
sigma = r_star / 2**(1/6) # Angstrom
116+
N_atom = 50 # Number of atoms
117+
m_argon = 39.948 * ureg.gram / ureg.mol # g/mol
118+
T = 328.15 * ureg.degK # 328 K or 55°C
117119
volume_star = r_star**3 * Na * 2**(-0.5)
118-
cut_off = sigma*2.5 # angstrom
119-
displace_mc = sigma/5 # angstrom
120-
volume = N_atom*volume_star*tau/Na # angstrom**3
121-
box_size = volume**(1/3) # angstrom
122-
123-
mc = MonteCarlo(maximum_steps=15000,
120+
cut_off = sigma * 2.5 # Angstrom
121+
displace_mc = sigma / 5 # Angstrom
122+
volume = N_atom * volume_star * tau / Na # Angstrom^3
123+
box_size = volume**(1/3) # Angstrom
124+
125+
# Initialize and run the Monte Carlo simulation
126+
mc = MonteCarlo(
127+
maximum_steps=15000,
124128
dumping_period=1000,
125129
thermo_period=1000,
126-
thermo_outputs = "Epot-press",
130+
thermo_outputs="Epot-press",
127131
neighbor=50,
128132
number_atoms=[N_atom],
129133
epsilon=[epsilon.magnitude],
130134
sigma=[sigma.magnitude],
131135
atom_mass=[m_argon.magnitude],
132136
box_dimensions=[box_size.magnitude, box_size.magnitude, box_size.magnitude],
133-
displace_mc = displace_mc.magnitude,
134-
desired_temperature = T.magnitude,
135-
cut_off = cut_off.magnitude,
136-
data_folder = "Outputs/",
137-
)
137+
displace_mc=displace_mc.magnitude,
138+
desired_temperature=T.magnitude,
139+
cut_off=cut_off.magnitude,
140+
data_folder="Outputs/",
141+
)
138142
mc.run()
139143
140-
# Import the data and calculate p V / R T
141-
# output = np.mean(np.loadtxt("Outputs/pressure.dat")[:,1][10:])
142-
# pressure = (output*ureg.atm).to(ureg.pascal)
143-
# volume = (volume_star * tau / Na).to(ureg.meter**3)
144-
# pV_over_RT = np.round((pressure * volume / (R * T) * Na).magnitude,2)
145-
# print("p v / R T =", pV_over_RT, " --- (The expected value from Wood1957 is 1.5)")
144+
# Test function using pytest
145+
def test_pV_over_RT():
146+
# Import the data and calculate pV / RT
147+
pressure_data = np.array(import_data("Outputs/simulation.log")[1:])[0][:,2][10:] # Skip initial values
148+
pressure_atm = np.mean(pressure_data) # atm
149+
pressure_Pa = (pressure_atm * ureg.atm).to(ureg.pascal) # Pa
150+
volume = (volume_star * tau / Na).to(ureg.meter**3) # m3
151+
pV_over_RT = (pressure_Pa * volume / (R * T) * Na).magnitude
152+
153+
# Assert that pV_over_RT is close to 1.5
154+
assert np.isclose(pV_over_RT, 1.5, atol=1.0), f"Test failed: pV/Rt = {pV_over_RT}, expected close to 1.5"
155+
print(f"pV/RT = {pV_over_RT:.2f} --- (The expected value from Wood1957 is 1.5)")
156+
157+
# If the script is run directly, execute the tests
158+
if __name__ == "__main__":
159+
import pytest
160+
# Run pytest programmatically
161+
pytest.main(["-s", __file__])
146162
147163
.. label:: end_test_7a_class
148164

@@ -154,4 +170,4 @@ of 1.5 by Wood and Parker for :math:`\tau = V/V^* = 2` (see Fig. 4 in Ref. :cite
154170
(...)
155171
p v / R T = 1.56 --- (The expected value from Wood1957 is 1.5)
156172
157-
The exact value will varie from one simulation to the other due to noise.
173+
The exact value will vary from one simulation to the other due to noise.

tests/build-documentation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
os.mkdir("generated-codes/")
1919

2020
# loop on the different chapter
21-
for chapter_id in [1]:
21+
for chapter_id in [1, 2, 3, 4, 5, 6, 7]:
2222
# for each chapter, create the corresponding code
2323
RST_EXISTS, created_tests, folder = sphinx_to_python(path_to_docs, chapter_id)
2424
if RST_EXISTS:

0 commit comments

Comments
 (0)