Skip to content

Commit 70ea7ea

Browse files
committed
refactor: use list accumulation instead of np.append in loop
np.append() copies the entire array on every iteration (O(n^2)). List append + np.array at the end is O(n).
1 parent dbae347 commit 70ea7ea

2 files changed

Lines changed: 40 additions & 4 deletions

File tree

porousmedialab/calibrator.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@ def find_indexes_of_intersections(s, o, eps):
2121
idxs: indexes of simulated values
2222
"""
2323

24-
idxs = np.array([])
24+
idxs = []
2525
for o_i in o:
26-
idx, = np.where(abs(s - o_i) <= eps*1.01)
26+
idx, = np.where(abs(s - o_i) <= eps * 1.01)
2727
if idx.size > 0:
28-
idxs = np.append(idxs, int(idx[0]))
29-
return idxs.astype(int)
28+
idxs.append(int(idx[0]))
29+
return np.array(idxs, dtype=int)
3030

3131

3232
class Calibrator:

tests/test_calibrator.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,42 @@ def test_first_match_used(self):
5757
assert len(idxs) == 1
5858
assert idxs[0] == 1 # First match
5959

60+
def test_large_input(self):
61+
"""Should work correctly with larger arrays."""
62+
simulated = np.linspace(0, 10, 1001)
63+
observed = np.array([1.0, 5.0, 9.0])
64+
eps = 0.01
65+
66+
idxs = find_indexes_of_intersections(simulated, observed, eps)
67+
68+
assert len(idxs) == 3
69+
# Verify values at found indexes are close to observed
70+
for i, o_val in enumerate(observed):
71+
assert abs(simulated[idxs[i]] - o_val) <= eps * 1.01
72+
73+
def test_returns_int_array(self):
74+
"""Return type should be numpy int array."""
75+
simulated = np.array([0.0, 0.1, 0.2])
76+
observed = np.array([0.1])
77+
eps = 0.01
78+
79+
idxs = find_indexes_of_intersections(simulated, observed, eps)
80+
81+
assert isinstance(idxs, np.ndarray)
82+
assert idxs.dtype == int
83+
84+
def test_empty_observed_returns_empty_int_array(self):
85+
"""Empty observed array should return empty int array."""
86+
simulated = np.array([0.0, 0.1, 0.2])
87+
observed = np.array([])
88+
eps = 0.01
89+
90+
idxs = find_indexes_of_intersections(simulated, observed, eps)
91+
92+
assert isinstance(idxs, np.ndarray)
93+
assert idxs.dtype == int
94+
assert len(idxs) == 0
95+
6096

6197
class TestCalibratorInitialization:
6298
"""Tests for Calibrator initialization."""

0 commit comments

Comments
 (0)