Skip to content

Commit 44c509e

Browse files
Merge pull request #15 from robertsamples/beta-cv-norm
Beta CV and per sample normalization
2 parents 512b0be + c39ab2e commit 44c509e

4 files changed

Lines changed: 337 additions & 41 deletions

File tree

‎code/MSFaST.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,13 @@ def run_MSFaST(params):
221221
adduct_removed = filter.adductgroup(analysis_params, getattr(analysis_params, 'adduct_list', None))
222222
ionfilters['adduct'] = filter.ionfilter('', list(adduct_removed))
223223
filter.applyfilters(analysis_params, ionfilters)
224+
# Beta sample normalization: after filtering, which it would not change
225+
# (the filters compare features within a sample, or replicates of one
226+
# sample), and before the group statistics, which it does change.
227+
if getattr(analysis_params, 'samplenorm', 'none') in ('sum', 'pqn'):
228+
stats.samplenormalize(analysis_params)
229+
if analysis_params.grpave:
230+
stats.groupave(analysis_params)
224231
if analysis_params.prperr:
225232
stats.properr(analysis_params)
226233

@@ -290,6 +297,15 @@ def run_MSFaST(params):
290297
'---Filtering---\n',
291298
'-CV filtering-\n',
292299
'CV threshold: ' + str(analysis_params.cvthresh) + '\n',
300+
('CV sample cutoff (beta): ' + str(getattr(analysis_params, 'cvgate_frac', 0.01))
301+
+ ' x feature maximum\n') if getattr(analysis_params, 'cvgate', False) else '',
302+
('Sample normalization (beta): '
303+
+ {'sum': 'total signal', 'pqn': 'probabilistic quotient'}[analysis_params.samplenorm]
304+
+ '\n'
305+
+ ('Left out of normalization: '
306+
+ ', '.join(map(str, getattr(analysis_params, 'samplenorm_skip', None) or []))
307+
+ '\n' if getattr(analysis_params, 'samplenorm_skip', None) else '')
308+
) if getattr(analysis_params, 'samplenorm', 'none') in ('sum', 'pqn') else '',
293309
'\n',
294310
'-Relative filtering-\n',
295311
'Ringing window: ' + str(analysis_params.ringingwin) + '\n',

‎code/filter.py‎

Lines changed: 35 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import scipy.cluster.hierarchy as spc
1111
from scipy import stats
1212
import mspwriter
13-
from tqdm import tqdm
1413

1514
class ionmerge:
1615
"""
@@ -234,53 +233,48 @@ def parsionlists(analysis_params):
234233
def cvfilter(analysis_params, ionfilterlist, threshold):
235234
"""
236235
Filters ions based on the coefficient of variation (CV).
236+
237+
Each sample's CV is taken over its technical replicate injections, then
238+
summarised per feature as the average or median over samples.
239+
240+
Beta (analysis_params.cvgate): only samples whose mean is at least
241+
analysis_params.cvgate_frac of the feature's highest sample mean count
242+
towards the summary. In a varied set of samples a compound may be real in
243+
a few and sit near the noise in many others, and those noisy CVs would
244+
otherwise decide the median.
237245
"""
238246
print('Running CV filter')
239-
240-
# Calculate total number of cells in the dataset and set chunk size based on 100,000 cells per chunk
241-
header = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'), nrows=0, header=[0, 1, 2])
242-
total_columns = header.shape[1]
243-
cells_per_chunk = 100_000
244-
chunk_size = max(1, cells_per_chunk // total_columns) # Rows per chunk
245-
246-
# Initialize containers for aggregated results
247-
means = []
248-
stds = []
249-
counts = []
250-
251-
# Import data and calculate sums and counts in chunks with a progress bar
252-
with tqdm(desc='Processing chunks', unit='chunk') as pbar:
253-
for chunk in pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
254-
sep=',', header=[0, 1, 2], index_col=[0, 1, 2], chunksize=chunk_size):
255-
try:
256-
chunk_stacked = chunk.stack([0, 1, 2], future_stack=True)
257-
except TypeError:
258-
chunk_stacked = chunk.stack([0, 1, 2])
259-
260-
# Group data by the specified levels and calculate mean, std, and count per group
261-
groupby_indices = chunk_stacked.groupby(level=[0, 1, 2, 3, 4])
262-
means.append(groupby_indices.mean())
263-
stds.append(groupby_indices.std())
264-
counts.append(groupby_indices.count())
265-
266-
pbar.update(1)
267-
268-
# Concatenate results and calculate overall mean and standard deviation
269-
mean_values = pd.concat(means)
270-
std_values = pd.concat(stds)
271-
count_values = pd.concat(counts)
272-
273-
# Calculate CV
247+
248+
# Works on the wide table (features x injections) and summarises across
249+
# columns, rather than stacking it into one row per value.
250+
msdata = pd.read_csv(analysis_params.outputdir / (analysis_params.filename.stem + '_formatted.csv'),
251+
sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
252+
by_sample = msdata.T.groupby(level=[0, 1], sort=True)
253+
mean_values = by_sample.mean().T # features x (group, sample)
254+
std_values = by_sample.std().T
255+
del by_sample, msdata
256+
257+
# Calculate CV (NaN for a sample with one injection or no signal)
274258
msdata_cv = std_values / mean_values
275-
276-
# Calculate average and median CV across the first level
277-
msdatameancv = msdata_cv.groupby(level=0).mean()
278-
msdatamediancv = msdata_cv.groupby(level=0).median()
259+
msdata_cv.index = msdata_cv.index.get_level_values(0)
260+
mean_values.index = msdata_cv.index
261+
262+
gate = getattr(analysis_params, 'cvgate', False)
263+
if gate:
264+
frac = float(getattr(analysis_params, 'cvgate_frac', 0.01))
265+
print(f' beta: samples below {frac:g} x the feature maximum left out of its CV')
266+
msdata_cv = msdata_cv.where(mean_values.ge(mean_values.max(axis=1) * frac, axis=0))
267+
268+
# Calculate average and median CV across samples
269+
msdatameancv = msdata_cv.mean(axis=1)
270+
msdatamediancv = msdata_cv.median(axis=1)
279271

280272
# Add average and median CV to iondict.csv
281273
iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
282274
iondict['average CV'] = msdatameancv
283275
iondict['median CV'] = msdatamediancv
276+
if gate:
277+
iondict['CV samples used'] = msdata_cv.notna().sum(axis=1)
284278
iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
285279

286280
# Determine ions to keep and reject based on CV threshold
@@ -296,7 +290,7 @@ def cvfilter(analysis_params, ionfilterlist, threshold):
296290
iondict = pd.read_csv(analysis_params.outputdir / 'iondict.csv', sep=',', header=[0], index_col=0)
297291
iondict['pass_cvfil'] = ~iondict.index.isin(ionfilterlist['cv'].ions)
298292
iondict.to_csv(analysis_params.outputdir / 'iondict.csv', header=True, index=True)
299-
293+
300294
return ionfilterlist
301295

302296

‎code/stats.py‎

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
Modifications Copyright 2026, Robert M. Samples
55
"""
66

7+
import shutil
8+
from pathlib import Path
9+
710
import pandas as pd
811
import numpy as np
912
from scipy import stats
@@ -123,6 +126,122 @@ def long(frame):
123126
header=True, index=True
124127
)
125128

129+
# samplenormalize warns about a sample whose signal is more than this many
130+
# times above or below the median sample.
131+
EXTREME_FACTOR = 5.0
132+
133+
134+
def normalization_factors(msdata, method, skip_groups=()):
135+
"""
136+
Per-sample normalization factors for a wide peak table.
137+
138+
Args:
139+
msdata (DataFrame): features x injections, columns (group, sample, injection).
140+
method (str): 'sum' (total signal) or 'pqn' (probabilistic quotient,
141+
Dieterle et al. 2006, Anal. Chem. 78, 4281).
142+
skip_groups: groups left as they are (factor 1), such as blanks.
143+
144+
Returns:
145+
DataFrame indexed (group, sample) with the number of injections, the
146+
sample's signal relative to the median sample, and the factor that
147+
divides it out (1 / relative signal).
148+
"""
149+
# One profile per sample: the mean of its technical replicate injections,
150+
# so every injection of a sample gets the same factor and technical CVs
151+
# are unchanged.
152+
profiles = msdata.T.groupby(level=[0, 1], sort=True).mean().T
153+
injections = msdata.T.groupby(level=[0, 1], sort=True).size()
154+
used = ~profiles.columns.get_level_values(0).isin(list(skip_groups))
155+
relative = pd.Series(np.nan, index=profiles.columns)
156+
if used.any():
157+
sample_profiles = profiles.loc[:, used]
158+
if method == 'sum':
159+
totals = sample_profiles.sum(axis=0)
160+
relative[used] = totals / totals[totals > 0].median()
161+
elif method == 'pqn':
162+
reference = sample_profiles.median(axis=1)
163+
ratios = sample_profiles.div(reference, axis=0)
164+
ratios = ratios.where((sample_profiles > 0) & (reference > 0).values[:, None])
165+
quotients = ratios.median(axis=0)
166+
relative[used] = quotients / quotients[quotients > 0].median()
167+
else:
168+
raise ValueError('unknown normalization method: ' + str(method))
169+
# A sample with no usable signal is left as it is.
170+
relative = relative.where(relative > 0)
171+
factors = pd.DataFrame({'injections': injections,
172+
'relative signal': relative,
173+
'factor': (1 / relative).fillna(1.0)})
174+
factors.index.names = ['Group', 'Sample']
175+
return factors
176+
177+
178+
def _scale_table(path, factors):
179+
"""Multiply a peak table on disk (three header rows, then Compound, m/z,
180+
RT and one column per injection) by its sample's factor, in place."""
181+
table = pd.read_csv(path, sep=',', header=None, index_col=None, low_memory=False)
182+
header, body = table.iloc[:3], table.iloc[3:]
183+
lookup = factors['factor'].to_dict()
184+
column_factors = [lookup.get((str(header.iat[0, i]), str(header.iat[1, i])), 1.0)
185+
for i in range(3, table.shape[1])]
186+
values = body.iloc[:, 3:].astype(float) * np.array(column_factors)
187+
body = pd.concat([body.iloc[:, :3], values], axis=1)
188+
pd.concat([header, body], ignore_index=True).to_csv(path, index=False, header=False)
189+
190+
191+
def samplenormalize(analysis_params):
192+
"""
193+
Beta: normalize each biological sample to the same overall signal.
194+
195+
The factor is worked out from the features that passed every filter, so
196+
noise, solvent and blank peaks do not set it, and it is applied to every
197+
injection of the sample alike, so technical CVs are unchanged. The
198+
formatted and filtered tables are rescaled in place; the unscaled filtered
199+
table is kept as <name>_filtered_raw.csv and the factors are written to
200+
<name>_normfactors.csv. The blank group, and any group named in
201+
samplenorm_skip (a media blank, say), is left unscaled and is not used to
202+
work out the factors of the others.
203+
204+
Args:
205+
analysis_params (object): needs samplenorm ('sum' or 'pqn'), outputdir,
206+
filename and blnkgrp; samplenorm_skip is optional.
207+
208+
Returns:
209+
DataFrame: the factors (see normalization_factors).
210+
"""
211+
method = getattr(analysis_params, 'samplenorm', 'none')
212+
print(f'Normalizing samples (beta: {method})')
213+
stem = analysis_params.outputdir / analysis_params.filename.stem
214+
filtered_path = Path(str(stem) + '_filtered.csv')
215+
formatted_path = Path(str(stem) + '_formatted.csv')
216+
217+
filtered = pd.read_csv(filtered_path, sep=',', header=[0, 1, 2], index_col=[0, 1, 2])
218+
blank = getattr(analysis_params, 'blnkgrp', '') or ''
219+
skip = [str(g) for g in getattr(analysis_params, 'samplenorm_skip', None) or []]
220+
if blank and blank not in skip:
221+
skip.insert(0, blank)
222+
if skip:
223+
print(' left unscaled: ' + ', '.join(skip))
224+
factors = normalization_factors(filtered, method, skip_groups=skip)
225+
factors.to_csv(Path(str(stem) + '_normfactors.csv'), header=True, index=True)
226+
names = factors.index.get_level_values(1)
227+
unused = factors['relative signal'].isna() & ~factors.index.get_level_values(0).isin(skip)
228+
if unused.any():
229+
print(' warning: no usable signal in ' + ', '.join(names[unused]) + '; left unscaled')
230+
# A factor this far from 1 is more likely a group with different contents
231+
# (a media blank, a strain that makes more) than a dilution.
232+
relative = factors['relative signal']
233+
extreme = (relative < 1 / EXTREME_FACTOR) | (relative > EXTREME_FACTOR)
234+
if extreme.any():
235+
listed = ', '.join(f'{n} ({r:.3g}x)' for n, r in zip(names[extreme], relative[extreme]))
236+
print(f' warning: signal more than {EXTREME_FACTOR:g}x from the median sample in '
237+
f'{listed}; check these are dilutions, or leave their groups out')
238+
239+
shutil.copyfile(filtered_path, Path(str(stem) + '_filtered_raw.csv'))
240+
for path in (formatted_path, filtered_path):
241+
_scale_table(path, factors)
242+
return factors
243+
244+
126245
def properr(analysis_params):
127246
"""
128247
Propagates error and calculates the combined relative standard deviation,

0 commit comments

Comments
 (0)