|
| 1 | +"""Pythonic wrapper for :class:`pyopenms.ExperimentalDesign`.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from pathlib import Path |
| 5 | +from typing import Union, Optional, Set |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | +import pyopenms as oms |
| 9 | + |
| 10 | +from ._io_utils import ensure_allowed_suffix |
| 11 | + |
| 12 | +# Supported file extensions for experimental design |
| 13 | +EXPERIMENTAL_DESIGN_EXTENSIONS = {".tsv"} |
| 14 | + |
| 15 | + |
| 16 | +class Py_ExperimentalDesign: |
| 17 | + """A Pythonic wrapper around :class:`pyopenms.ExperimentalDesign`. |
| 18 | + |
| 19 | + This class provides convenient methods for loading, storing, and working with |
| 20 | + experimental design files in OpenMS format. |
| 21 | + |
| 22 | + Example: |
| 23 | + >>> from openms_python import Py_ExperimentalDesign |
| 24 | + >>> design = Py_ExperimentalDesign.from_file("design.tsv") |
| 25 | + >>> print(f"Samples: {design.n_samples}, MS files: {design.n_ms_files}") |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, native_design: Optional[oms.ExperimentalDesign] = None): |
| 29 | + """Initialize with an optional native ExperimentalDesign object. |
| 30 | + |
| 31 | + Parameters |
| 32 | + ---------- |
| 33 | + native_design: |
| 34 | + Optional :class:`pyopenms.ExperimentalDesign` to wrap. |
| 35 | + """ |
| 36 | + self._design = native_design if native_design is not None else oms.ExperimentalDesign() |
| 37 | + |
| 38 | + @classmethod |
| 39 | + def from_file(cls, filepath: Union[str, Path]) -> 'Py_ExperimentalDesign': |
| 40 | + """Load an experimental design from a TSV file. |
| 41 | + |
| 42 | + Parameters |
| 43 | + ---------- |
| 44 | + filepath: |
| 45 | + Path to the experimental design TSV file. |
| 46 | + |
| 47 | + Returns |
| 48 | + ------- |
| 49 | + Py_ExperimentalDesign |
| 50 | + A new instance with the loaded design. |
| 51 | + |
| 52 | + Example: |
| 53 | + >>> design = Py_ExperimentalDesign.from_file("design.tsv") |
| 54 | + """ |
| 55 | + instance = cls() |
| 56 | + instance.load(filepath) |
| 57 | + return instance |
| 58 | + |
| 59 | + def load(self, filepath: Union[str, Path]) -> 'Py_ExperimentalDesign': |
| 60 | + """Load an experimental design from disk. |
| 61 | + |
| 62 | + Parameters |
| 63 | + ---------- |
| 64 | + filepath: |
| 65 | + Path to the experimental design TSV file. |
| 66 | + |
| 67 | + Returns |
| 68 | + ------- |
| 69 | + Py_ExperimentalDesign |
| 70 | + Self for method chaining. |
| 71 | + """ |
| 72 | + ensure_allowed_suffix(filepath, EXPERIMENTAL_DESIGN_EXTENSIONS, "ExperimentalDesign") |
| 73 | + edf = oms.ExperimentalDesignFile() |
| 74 | + self._design = edf.load(str(filepath), False) |
| 75 | + return self |
| 76 | + |
| 77 | + def store(self, filepath: Union[str, Path]) -> 'Py_ExperimentalDesign': |
| 78 | + """Store the experimental design to disk. |
| 79 | + |
| 80 | + Note: Storage functionality is not available in the current pyOpenMS API. |
| 81 | + This method is provided for API consistency but will raise NotImplementedError. |
| 82 | + |
| 83 | + Parameters |
| 84 | + ---------- |
| 85 | + filepath: |
| 86 | + Path where the experimental design should be saved. |
| 87 | + |
| 88 | + Returns |
| 89 | + ------- |
| 90 | + Py_ExperimentalDesign |
| 91 | + Self for method chaining. |
| 92 | + |
| 93 | + Raises |
| 94 | + ------ |
| 95 | + NotImplementedError |
| 96 | + Storage is not yet implemented in pyOpenMS. |
| 97 | + """ |
| 98 | + ensure_allowed_suffix(filepath, EXPERIMENTAL_DESIGN_EXTENSIONS, "ExperimentalDesign") |
| 99 | + raise NotImplementedError( |
| 100 | + "ExperimentalDesign storage is not yet available in pyOpenMS. " |
| 101 | + "Please use the native pyOpenMS API if this functionality is needed." |
| 102 | + ) |
| 103 | + |
| 104 | + @property |
| 105 | + def native(self) -> oms.ExperimentalDesign: |
| 106 | + """Return the underlying :class:`pyopenms.ExperimentalDesign`.""" |
| 107 | + return self._design |
| 108 | + |
| 109 | + # ==================== Properties ==================== |
| 110 | + |
| 111 | + @property |
| 112 | + def n_samples(self) -> int: |
| 113 | + """Number of samples in the experimental design.""" |
| 114 | + return self._design.getNumberOfSamples() |
| 115 | + |
| 116 | + @property |
| 117 | + def n_ms_files(self) -> int: |
| 118 | + """Number of MS files in the experimental design.""" |
| 119 | + return self._design.getNumberOfMSFiles() |
| 120 | + |
| 121 | + @property |
| 122 | + def n_fractions(self) -> int: |
| 123 | + """Number of fractions in the experimental design.""" |
| 124 | + return self._design.getNumberOfFractions() |
| 125 | + |
| 126 | + @property |
| 127 | + def n_fraction_groups(self) -> int: |
| 128 | + """Number of fraction groups in the experimental design.""" |
| 129 | + return self._design.getNumberOfFractionGroups() |
| 130 | + |
| 131 | + @property |
| 132 | + def n_labels(self) -> int: |
| 133 | + """Number of labels in the experimental design.""" |
| 134 | + return self._design.getNumberOfLabels() |
| 135 | + |
| 136 | + @property |
| 137 | + def is_fractionated(self) -> bool: |
| 138 | + """Whether the experimental design includes fractionation.""" |
| 139 | + return self._design.isFractionated() |
| 140 | + |
| 141 | + @property |
| 142 | + def same_n_ms_files_per_fraction(self) -> bool: |
| 143 | + """Whether all fractions have the same number of MS files.""" |
| 144 | + return self._design.sameNrOfMSFilesPerFraction() |
| 145 | + |
| 146 | + @property |
| 147 | + def samples(self) -> Set[str]: |
| 148 | + """Set of sample identifiers in the design. |
| 149 | + |
| 150 | + Returns |
| 151 | + ------- |
| 152 | + Set[str] |
| 153 | + Set of sample identifiers. |
| 154 | + """ |
| 155 | + sample_section = self._design.getSampleSection() |
| 156 | + samples = sample_section.getSamples() |
| 157 | + # Convert bytes to str if needed |
| 158 | + return {s.decode() if isinstance(s, bytes) else str(s) for s in samples} |
| 159 | + |
| 160 | + # ==================== Summary methods ==================== |
| 161 | + |
| 162 | + def summary(self) -> dict: |
| 163 | + """Get a summary of the experimental design. |
| 164 | + |
| 165 | + Returns |
| 166 | + ------- |
| 167 | + dict |
| 168 | + Dictionary with summary statistics. |
| 169 | + """ |
| 170 | + return { |
| 171 | + 'n_samples': self.n_samples, |
| 172 | + 'n_ms_files': self.n_ms_files, |
| 173 | + 'n_fractions': self.n_fractions, |
| 174 | + 'n_fraction_groups': self.n_fraction_groups, |
| 175 | + 'n_labels': self.n_labels, |
| 176 | + 'is_fractionated': self.is_fractionated, |
| 177 | + 'samples': sorted(self.samples), |
| 178 | + } |
| 179 | + |
| 180 | + def print_summary(self) -> None: |
| 181 | + """Print a formatted summary of the experimental design.""" |
| 182 | + summary = self.summary() |
| 183 | + print("Experimental Design Summary") |
| 184 | + print("=" * 40) |
| 185 | + print(f"Samples: {summary['n_samples']}") |
| 186 | + print(f"MS Files: {summary['n_ms_files']}") |
| 187 | + print(f"Fractions: {summary['n_fractions']}") |
| 188 | + print(f"Fraction Groups: {summary['n_fraction_groups']}") |
| 189 | + print(f"Labels: {summary['n_labels']}") |
| 190 | + print(f"Fractionated: {summary['is_fractionated']}") |
| 191 | + if summary['samples']: |
| 192 | + print(f"Sample IDs: {', '.join(summary['samples'])}") |
| 193 | + |
| 194 | + # ==================== Factory methods ==================== |
| 195 | + |
| 196 | + @classmethod |
| 197 | + def from_consensus_map(cls, consensus_map: Union['Py_ConsensusMap', oms.ConsensusMap]) -> 'Py_ExperimentalDesign': |
| 198 | + """Create an ExperimentalDesign from a ConsensusMap. |
| 199 | + |
| 200 | + Parameters |
| 201 | + ---------- |
| 202 | + consensus_map: |
| 203 | + A :class:`Py_ConsensusMap` or :class:`pyopenms.ConsensusMap`. |
| 204 | + |
| 205 | + Returns |
| 206 | + ------- |
| 207 | + Py_ExperimentalDesign |
| 208 | + A new instance derived from the consensus map. |
| 209 | + """ |
| 210 | + # Handle both Py_ConsensusMap and native ConsensusMap |
| 211 | + native_map = consensus_map.native if hasattr(consensus_map, 'native') else consensus_map |
| 212 | + design = oms.ExperimentalDesign.fromConsensusMap(native_map) |
| 213 | + return cls(design) |
| 214 | + |
| 215 | + @classmethod |
| 216 | + def from_feature_map(cls, feature_map: Union['Py_FeatureMap', oms.FeatureMap]) -> 'Py_ExperimentalDesign': |
| 217 | + """Create an ExperimentalDesign from a FeatureMap. |
| 218 | + |
| 219 | + Parameters |
| 220 | + ---------- |
| 221 | + feature_map: |
| 222 | + A :class:`Py_FeatureMap` or :class:`pyopenms.FeatureMap`. |
| 223 | + |
| 224 | + Returns |
| 225 | + ------- |
| 226 | + Py_ExperimentalDesign |
| 227 | + A new instance derived from the feature map. |
| 228 | + """ |
| 229 | + # Handle both Py_FeatureMap and native FeatureMap |
| 230 | + native_map = feature_map.native if hasattr(feature_map, 'native') else feature_map |
| 231 | + design = oms.ExperimentalDesign.fromFeatureMap(native_map) |
| 232 | + return cls(design) |
| 233 | + |
| 234 | + @classmethod |
| 235 | + def from_identifications( |
| 236 | + cls, |
| 237 | + protein_ids: list |
| 238 | + ) -> 'Py_ExperimentalDesign': |
| 239 | + """Create an ExperimentalDesign from protein identification data. |
| 240 | + |
| 241 | + Parameters |
| 242 | + ---------- |
| 243 | + protein_ids: |
| 244 | + List of :class:`pyopenms.ProteinIdentification` objects. |
| 245 | + |
| 246 | + Returns |
| 247 | + ------- |
| 248 | + Py_ExperimentalDesign |
| 249 | + A new instance derived from the identifications. |
| 250 | + """ |
| 251 | + design = oms.ExperimentalDesign.fromIdentifications(protein_ids) |
| 252 | + return cls(design) |
| 253 | + |
| 254 | + # ==================== Delegation ==================== |
| 255 | + |
| 256 | + def __getattr__(self, name: str): |
| 257 | + """Delegate attribute access to the underlying ExperimentalDesign.""" |
| 258 | + return getattr(self._design, name) |
| 259 | + |
| 260 | + def __repr__(self) -> str: |
| 261 | + """String representation of the ExperimentalDesign.""" |
| 262 | + return ( |
| 263 | + f"Py_ExperimentalDesign(samples={self.n_samples}, " |
| 264 | + f"ms_files={self.n_ms_files}, fractionated={self.is_fractionated})" |
| 265 | + ) |
0 commit comments