Skip to content

Commit

Permalink
Add tests for MonteCarloConfig
Browse files Browse the repository at this point in the history
  • Loading branch information
astralcai committed May 2, 2024
1 parent 8c720e9 commit d477b0f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
7 changes: 6 additions & 1 deletion qexpy/core/derived_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ def error_method(self, method: str):
raise ValueError("The error method can only be 'derivative', 'monte-carlo', or 'auto'")
self._error_method = method

@property
def mc(self):
"""The MonteCarloConfig object for this value"""
return self._mc


class MonteCarloConfig:
"""Stores all data and configurations of a Monte Carlo simulation."""
Expand Down Expand Up @@ -136,6 +141,6 @@ def sample_size(self, size: int):
@property
def samples(self):
"""The array of simulated samples"""
if self._samples is None:
if self._samples is None or len(self._samples) != self.sample_size:
self._samples = q.core.monte_carlo(self._formula, self.sample_size)
return self._samples
43 changes: 43 additions & 0 deletions tests/core/test_monte_carlo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Tests for more fine-grained control of the Monte Carlo error method"""

import pytest

import qexpy as q


class TestMonteCarloConfig:
"""Tests the MonteCarloConfig class"""

@pytest.fixture(autouse=True)
def cleanup(self):
"""Cleans up global configurations"""
yield
q.reset_option()

def test_sample_size(self):
"""Tests the Monte Carlo sample size"""

m1 = q.Measurement(1.23, 0.02)
m2 = q.Measurement(4.56, 0.03)
res = m1 + m2
res.error_method = "monte-carlo"
assert res.mc.sample_size == 100000
assert len(res.mc.samples) == 100000

q.options.error.mc.sample_size = 1000
assert res.mc.sample_size == 1000
assert len(res.mc.samples) == 1000

res.mc.sample_size = 200
assert res.mc.sample_size == 200
assert len(res.mc.samples) == 200

def test_invalid_sample_size(self):
"""Tests that error is raised for invalid sample sizes"""

m1 = q.Measurement(1.23, 0.02)
m2 = q.Measurement(4.56, 0.03)
res = m1 + m2
res.error_method = "monte-carlo"
with pytest.raises(ValueError, match="The sample size must be a positive integer!"):
res.mc.sample_size = -100

0 comments on commit d477b0f

Please sign in to comment.