Skip to content

Commit a07bb0d

Browse files
committed
Added tests for scripts. Closes #117
1 parent 57b88dd commit a07bb0d

5 files changed

Lines changed: 64 additions & 53 deletions

File tree

CONTRIBUTING.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Isort is configured in [pyproject.toml](./pyproject.toml) under the section `too
7676
## Documentation
7777

7878
Every method and every class should have a [docstring](https://www.python.org/dev/peps/pep-0257/) that describes in plain terms what it does, and what the expected input and output is.
79+
The only exception are unit test methods starting with `test_` - unit test classes and other methods in unit tests should all have docstrings.
7980

8081
Each docstring should start with a one-line explanation.
8182
If more explanation is needed, this one-liner is followed by a blank line and more information in the following paragraphs.

pcpostprocess/scripts/run_herg_qc.py

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,6 @@
2828
from pcpostprocess.leak_correct import fit_linear_leak, get_leak_corrected
2929
from pcpostprocess.subtraction_plots import do_subtraction_plot
3030

31-
# TODO: Remove this
32-
color_cycle = ["#5790fc", "#f89c20", "#e42536", "#964a8b", "#9c9ca1", "#7a21dd"]
33-
plt.rcParams['axes.prop_cycle'] = cycler.cycler('color', color_cycle)
34-
35-
# TODO: Not sure we need to explicitly set this!
36-
matplotlib.use('Agg')
37-
3831

3932
def run_from_command_line():
4033
"""
@@ -110,11 +103,7 @@ def run(data_path, output_path, qc_map, wells=None,
110103
write_traces=False, write_failed_traces=False, write_map={},
111104
reversal_potential=-90, reversal_spread_threshold=10,
112105
max_processes=1, figure_size=None,
113-
debug=False,
114-
115-
save_id=None,
116-
117-
):
106+
debug=False, save_id=None):
118107
"""
119108
Imports traces and runs QC.
120109
@@ -149,6 +138,9 @@ def run(data_path, output_path, qc_map, wells=None,
149138
# TODO Remove protocol selection here: this is done via the export file!
150139
# Only protocols listed there are accepted
151140

141+
# TODO: Find some way around setting this?
142+
matplotlib.use('Agg')
143+
152144
# Select wells to use
153145
all_wells = [row + str(i).zfill(2) for row in string.ascii_uppercase[:16]
154146
for i in range(1, 25)]
@@ -504,8 +496,6 @@ def agg_func(x):
504496
qc_df['protocol'] = ['staircaseramp1_2' if p == 'staircaseramp2' else p
505497
for p in qc_df.protocol]
506498

507-
print(qc_df.protocol.unique())
508-
509499
fails_dict = {}
510500
no_wells = 384
511501

@@ -1256,7 +1246,7 @@ def fit_func(x, args=None):
12561246
]
12571247

12581248
# TESTING ONLY
1259-
np.random.seed(1)
1249+
# np.random.seed(1)
12601250

12611251
#  Repeat optimisation with different starting guesses
12621252
x0s = [[np.random.uniform(lower_b, upper_b) for lower_b, upper_b in bounds] for i in range(100)]

pcpostprocess/scripts/summarise_herg_export.py

Lines changed: 10 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,6 @@
1717
from pcpostprocess.directory_builder import setup_output_directory
1818
from pcpostprocess.scripts.run_herg_qc import create_qc_table
1919

20-
matplotlib.use('Agg')
21-
22-
pool_kws = {'maxtasksperchild': 1}
23-
24-
color_cycle = ["#5790fc", "#f89c20", "#e42536", "#964a8b", "#9c9ca1", "#7a21dd"]
25-
plt.rcParams['axes.prop_cycle'] = cycler.cycler('color', color_cycle)
26-
sns.set_palette(sns.color_palette(color_cycle))
27-
2820

2921
def get_wells_list(input_dir, experiment_name):
3022
regex = re.compile(f"{experiment_name}-([a-z|A-Z|0-9]*)-([A-Z][0-9][0-9])-after")
@@ -54,7 +46,6 @@ def run_from_command_line():
5446

5547
description = '' # TODO Describe what this does
5648
parser = argparse.ArgumentParser(description)
57-
5849
parser.add_argument(
5950
'data_directory', help='path to the run_herg_qc results')
6051
parser.add_argument(
@@ -67,32 +58,27 @@ def run_from_command_line():
6758
parser.add_argument(
6859
'--figsize', type=int, nargs=2, default=(5, 3),
6960
help='A figure size, to pass to matplotlib')
70-
parser.add_argument('--log_level', default='INFO')
7161
args = parser.parse_args()
7262

73-
# Setup logging
74-
logging.basicConfig(level=args.log_level)
75-
logger = logging.getLogger(__name__)
76-
logger.setLevel(args.log_level)
77-
7863
run(args.data_directory, args.output_dir, args.experiment_name,
79-
logger, args.Erev, args.figsize)
64+
args.Erev, args.figsize)
8065

8166

82-
def run(data_path, output_path, experiment_name, logger,
83-
reversal_potential=None, figsize=None):
67+
def run(data_path, output_path, experiment_name, reversal_potential=None,
68+
figsize=None):
8469
"""
8570
Does whatever this does.
8671
8772
@param data_path The path to read data from
8873
@param output_path A root path, will be appended with "summarise_herg_export"
8974
@param experiment_name
90-
@param logger
9175
@param reversal_potential The calculated reversal potential, or ``None``
9276
@param figsize The matplotlib figure size, or ``None``.
93-
9477
"""
95-
output_path = setup_output_directory(output_path, 'summarise_herg_export')
78+
# TODO: Find some way around setting this
79+
matplotlib.use('Agg')
80+
81+
output_path = setup_output_directory(output_path)
9682

9783
leak_parameters_df = pd.read_csv(os.path.join(data_path, 'subtraction_qc.csv'))
9884

@@ -113,8 +99,6 @@ def run(data_path, output_path, experiment_name, logger,
11399
leak_parameters_df.protocol = ['staircaseramp1_2' if protocol == 'staircaseramp_2' else protocol
114100
for protocol in leak_parameters_df.protocol]
115101

116-
print(leak_parameters_df.protocol.unique())
117-
118102
with open(os.path.join(data_path, 'passed_wells.txt')) as fin:
119103
passed_wells = fin.read().splitlines()
120104

@@ -138,8 +122,6 @@ def run(data_path, output_path, experiment_name, logger,
138122

139123
leak_parameters_df.sort_values(['protocol', 'sweep'], inplace=True)
140124
except FileNotFoundError as exc:
141-
logging.warning(str(exc))
142-
logger.warning('no chronological information provided. Sorting alphabetically')
143125
leak_parameters_df.sort_values(['protocol', 'sweep'])
144126

145127
scatterplot_timescale_E_obs(output_path, leak_parameters_df, passed_wells, figsize)
@@ -171,13 +153,6 @@ def run(data_path, output_path, experiment_name, logger,
171153
# do_scatter_matrices(leak_parameters_df, qc_vals_df, output_path, reversal_potential)
172154
plot_histograms(leak_parameters_df, output_path, reversal_potential, figsize)
173155

174-
# Don't work
175-
# wells = leak_parameters_df.well.unique()
176-
# overlay_reversal_plots(data_path, output_path, experiment_name,
177-
# leak_parameters_df, wells, reversal_potential, figsize)
178-
# do_combined_plots(data_path, output_path, experiment_name,
179-
# leak_parameters_df, passed_wells, logger, figsize)
180-
181156

182157
def compute_leak_magnitude(df, lims=[-120, 60]):
183158
def compute_magnitude(g, E, lims=lims):
@@ -371,7 +346,7 @@ def label_func(p, s):
371346

372347

373348
def do_combined_plots(data_path, output_path, experiment_name,
374-
leak_parameters_df, passed_wells, logger, figsize=None):
349+
leak_parameters_df, passed_wells, figsize=None):
375350
"""
376351
???
377352
@@ -380,7 +355,6 @@ def do_combined_plots(data_path, output_path, experiment_name,
380355
@param experiment_name
381356
@param leak_parameters_df
382357
@param passed_wells
383-
@param logger
384358
@param figsize
385359
386360
"""
@@ -389,8 +363,6 @@ def do_combined_plots(data_path, output_path, experiment_name,
389363

390364
wells = [well for well in leak_parameters_df.well.unique() if well in passed_wells]
391365

392-
logger.info(f"passed wells are {passed_wells}")
393-
394366
protocol_overlaid_dir = os.path.join(output_path, 'overlaid_by_protocol')
395367
if not os.path.exists(protocol_overlaid_dir):
396368
os.makedirs(protocol_overlaid_dir)
@@ -456,8 +428,6 @@ def do_combined_plots(data_path, output_path, experiment_name,
456428
if not os.path.exists(wells_overlaid_dir):
457429
os.makedirs(wells_overlaid_dir)
458430

459-
logger.info('overlaying traces by well')
460-
461431
for well in passed_wells:
462432
i = 0
463433
for sweep in leak_parameters_df.sweep.unique():
@@ -728,6 +698,7 @@ def func(protocol, sweep):
728698
ax = fig.subplots()
729699
# add black color for NaNs
730700

701+
color_cycle = ["#5790fc", "#f89c20"]
731702
cmap = matplotlib.colors.ListedColormap([color_cycle[0], color_cycle[1]], 'indexed')
732703
ax.pcolormesh(zs, edgecolors='white', cmap=cmap,
733704
linewidths=1, antialiased=True)
@@ -776,6 +747,7 @@ def plot_spatial_passed(df, output_path, passed_wells):
776747

777748
zs = np.array(zs).reshape(16, 24)
778749

750+
color_cycle = ["#5790fc", "#f89c20"]
779751
cmap = matplotlib.colors.ListedColormap([color_cycle[0], color_cycle[1]], 'indexed')
780752
_ = ax.pcolormesh(zs, edgecolors='white',
781753
linewidths=1, antialiased=True, cmap=cmap

tests/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#
2+
#
3+
# Unit tests for pcpostproces
4+
#
5+
#

tests/test_scripts.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import tempfile
4+
import unittest
5+
6+
from pcpostprocess.scripts.run_herg_qc import run as run_herg_qc
7+
from pcpostprocess.scripts.summarise_herg_export import run as run_summarise
8+
9+
store_output = False
10+
11+
12+
class TestScripts(unittest.TestCase):
13+
"""
14+
Tests the scripts bundled with pcpostprocess.
15+
"""
16+
17+
def test_run_herg_qc_and_summarise_herg_export(self):
18+
# Test run_herg_qc_, then summarise_herg_export
19+
20+
data = os.path.join('tests', 'test_data', '13112023_MW2_FF')
21+
with tempfile.TemporaryDirectory() as d:
22+
if store_output:
23+
d = 'test_output'
24+
d1 = os.path.join(d, 'run_herg_qc')
25+
d2 = os.path.join(d, 'summarise_herg_export')
26+
27+
# Test run herg qc
28+
erev = -90.71
29+
qc_map = {'staircaseramp (2)_2kHz': 'staircaseramp'}
30+
write_map = {'staircaseramp2': 'staircaseramp2'}
31+
run_herg_qc(
32+
data, d1, qc_map, ('A03', 'A20', 'D16'),
33+
write_traces=True, write_map=write_map,
34+
save_id='13112023_MW2', reversal_potential=erev)
35+
36+
# Test summarise herg export
37+
run_summarise(d1, d2, '13112023_MW2', reversal_potential=erev)
38+
39+
40+
if __name__ == '__main__':
41+
store_output=True
42+
unittest.main()
43+

0 commit comments

Comments
 (0)