|
4 | 4 | Modifications Copyright 2026, Robert M. Samples |
5 | 5 | """ |
6 | 6 |
|
| 7 | +import shutil |
| 8 | +from pathlib import Path |
| 9 | + |
7 | 10 | import pandas as pd |
8 | 11 | import numpy as np |
9 | 12 | from scipy import stats |
@@ -123,6 +126,122 @@ def long(frame): |
123 | 126 | header=True, index=True |
124 | 127 | ) |
125 | 128 |
|
| 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 | + |
126 | 245 | def properr(analysis_params): |
127 | 246 | """ |
128 | 247 | Propagates error and calculates the combined relative standard deviation, |
|
0 commit comments