This is a complex bioinformatics/marine biology pipeline design question. Let me think through the key components needed:
-
Thermal tolerance screening - This would involve:
- Gene expression profiling under heat stress
- Biomarker identification (heat shock proteins, antioxidant genes)
- Genomic variants associated with thermal tolerance
- Epigenetic markers
-
Symbiont compatibility - This involves:
- Symbiodiniaceae diversity analysis
- Host-symbiont genetic compatibility
- Metabolomic profiling
- 16S/18S rRNA sequencing for symbiont identification
-
Disease resistance - This involves:
- Immune gene profiling
- Pathogen detection/diagnostics
- Microbiome analysis
- Resistance marker identification
I'll design a comprehensive pipeline that integrates:
- Sample collection and preparation
- Multi-omics approaches (genomics, transcriptomics, metabolomics, microbiomics)
- Computational analysis components
- Machine learning for prediction
- Data integration and scoring
Let me structure this as a detailed pipeline with code examples for key components.
High-Throughput Screening Pipeline for Climate-Resilient Coral Genotypes
Pipeline Overview
flowchart TD
subgraph Sample_Collection["1. Sample Collection & Preparation"]
A[Coral Fragment Collection] --> B[Tissue Biopsy]
B --> C[Symbiont Isolation]
B --> D[DNA/RNA Extraction]
C --> E[Symbiont Culture]
end
subgraph Thermal_Screening["2. Thermal Tolerance Assay"]
F[Heat Stress Treatment<br/>26°C → 34°C ramp] --> G[Physiological Metrics<br/>Fv/Fm, Bleaching Score]
F --> H[RNA-seq Time Series]
G --> I[Thermal Tolerance Index]
H --> I
end
subgraph Symbiont_Assay["3. Symbiont Compatibility Assay"]
E --> J[Cross-inoculation Matrix]
J --> K[Metabarcoding 18S/ITS2]
J --> L[Host Gene Expression]
K --> M[Compatibility Score]
L --> M
end
subgraph Disease_Assay["4. Disease Resistance Assay"]
N[Pathogen Challenge<br/>Vibrio spp.] --> O[Survival Kinetics]
N --> P[Immune Gene Profiling]
O --> Q[Disease Resistance Index]
P --> Q
end
subgraph Multiomics["5. Multi-omics Integration"]
I --> R[Machine Learning<br/>Ensemble Model]
M --> R
Q --> R
S[Whole Genome Sequencing] --> R
T[Microbiome 16S] --> R
R --> U[Climate Resilience Score]
end
subgraph Selection["6. Candidate Selection"]
U --> V[Top Performer Identification]
V --> W[Assisted Gene Flow<br/>Outplanting]
end
1. Pipeline Configuration and Setup
# coral_screening_pipeline/config.py
from dataclasses import dataclass, field
from typing import List, Dict, Optional
from enum import Enum
import yaml
class AssayType(Enum):
THERMAL_TOLERANCE = "thermal"
SYMBIONT_COMPATIBILITY = "symbiont"
DISEASE_RESISTANCE = "disease"
GENOMIC = "genomic"
MICROBIOME = "microbiome"
@dataclass
class ThermalAssayConfig:
"""Configuration for thermal tolerance screening"""
control_temp: float = 26.0 # °C
stress_temps: List[float] = field(default_factory=lambda: [28, 30, 32, 34])
ramp_rate: float = 0.5 # °C per hour
exposure_duration: int = 72 # hours
recovery_duration: int = 48 # hours
sampling_timepoints: List[int] = field(default_factory=lambda: [0, 6, 12, 24, 48, 72])
# Photophysiology parameters
fv_fm_threshold: float = 0.5 # Minimum healthy Fv/Fm
bleaching_score_max: int = 5 # Maximum bleaching score
@dataclass
class SymbiontAssayConfig:
"""Configuration for symbiont compatibility"""
target_genera: List[str] = field(default_factory=lambda: [
"Cladocopium", "Durusdinium", "Symbiodinium", "Breviolum"
])
inoculation_density: int = 10**5 # cells/mL
colonization_period: int = 21 # days
marker_genes: List[str] = field(default_factory=lambda: ["ITS2", "23S", "psbA"])
@dataclass
class DiseaseAssayConfig:
"""Configuration for disease resistance"""
pathogens: List[str] = field(default_factory=lambda: [
"Vibrio_coralliilyticus",
"Vibrio_owensii",
"Thalassomonas_loyana"
])
challenge_doses: List[float] = field(default_factory=lambda: [10**4, 10**5, 10**6]) # CFU/mL
observation_period: int = 14 # days
@dataclass
class SequencingConfig:
"""Sequencing parameters"""
genome_coverage: int = 30
transcriptome_depth: int = 50 # million reads
amplicon_depth: int = 100 # thousand reads
platforms: Dict[str, str] = field(default_factory=lambda: {
"wgs": "illumina_novaseq",
"rna_seq": "illumina_novaseq",
"amplicon": "illumina_miseq"
})
@dataclass
class PipelineConfig:
"""Master pipeline configuration"""
thermal: ThermalAssayConfig = field(default_factory=ThermalAssayConfig)
symbiont: SymbiontAssayConfig = field(default_factory=SymbiontAssayConfig)
disease: DiseaseAssayConfig = field(default_factory=DiseaseAssayConfig)
sequencing: SequencingConfig = field(default_factory=SequencingConfig)
# Execution parameters
n_samples_per_batch: int = 96
n_replicates: int = 3
output_dir: str = "results/"
reference_genome: str = "references/stylophora_pistillata_v2.fasta"
@classmethod
def from_yaml(cls, path: str) -> 'PipelineConfig':
with open(path) as f:
config_dict = yaml.safe_load(f)
return cls(**config_dict)
2. Sample Management and Metadata
# coral_screening_pipeline/sample_management.py
from dataclasses import dataclass
from typing import Optional, List
from datetime import datetime
import uuid
import pandas as pd
from pathlib import Path
@dataclass
class CoralSample:
"""Coral sample metadata"""
sample_id: str
species: str
collection_site: str
latitude: float
longitude: float
collection_date: datetime
depth_meters: float
fragment_id: str
genotype_cluster: Optional[str] = None
# Assay assignments
thermal_assay_id: Optional[str] = None
symbiont_assay_id: Optional[str] = None
disease_assay_id: Optional[str] = None
# Derived metrics
thermal_tolerance_index: Optional[float] = None
symbiont_compatibility_score: Optional[float] = None
disease_resistance_index: Optional[float] = None
climate_resilience_score: Optional[float] = None
@classmethod
def generate_id(cls) -> str:
return f"COR_{datetime.now().strftime('%Y%m%d')}_{uuid.uuid4().hex[:8]}"
def to_dict(self) -> dict:
return {
'sample_id': self.sample_id,
'species': self.species,
'collection_site': self.collection_site,
'latitude': self.latitude,
'longitude': self.longitude,
'collection_date': self.collection_date.isoformat(),
'depth_meters': self.depth_meters,
'fragment_id': self.fragment_id,
'genotype_cluster': self.genotype_cluster,
'thermal_tolerance_index': self.thermal_tolerance_index,
'symbiont_compatibility_score': self.symbiont_compatibility_score,
'disease_resistance_index': self.disease_resistance_index,
'climate_resilience_score': self.climate_resilience_score
}
class SampleRegistry:
"""Central registry for sample tracking"""
def __init__(self, registry_path: Path):
self.registry_path = registry_path
self.samples: Dict[str, CoralSample] = {}
self._load_registry()
def _load_registry(self):
if self.registry_path.exists():
df = pd.read_csv(self.registry_path)
for _, row in df.iterrows():
sample = CoralSample(**row.to_dict())
self.samples[sample.sample_id] = sample
def register_sample(self, sample: CoralSample):
self.samples[sample.sample_id] = sample
self._save_registry()
def _save_registry(self):
df = pd.DataFrame([s.to_dict() for s in self.samples.values()])
df.to_csv(self.registry_path, index=False)
def get_samples_by_criteria(
self,
species: Optional[str] = None,
site: Optional[str] = None,
min_thermal_index: Optional[float] = None
) -> List[CoralSample]:
"""Filter samples by criteria"""
results = list(self.samples.values())
if species:
results = [s for s in results if s.species == species]
if site:
results = [s for s in results if s.collection_site == site]
if min_thermal_index is not None:
results = [
s for s in results
if s.thermal_tolerance_index and s.thermal_tolerance_index >= min_thermal_index
]
return results
def assign_to_batch(
self,
samples: List[CoralSample],
assay_type: str,
batch_size: int = 96
) -> Dict[str, List[str]]:
"""Assign samples to experimental batches"""
batches = {}
for i in range(0, len(samples), batch_size):
batch_id = f"{assay_type}_batch_{i//batch_size + 1}"
batch_samples = samples[i:i+batch_size]
batches[batch_id] = [s.sample_id for s in batch_samples]
return batches
3. Thermal Tolerance Screening Module
# coral_screening_pipeline/thermal_assay.py
import numpy as np
import pandas as pd
from dataclasses import dataclass
from typing import List, Dict, Tuple, Optional
from scipy import stats
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
@dataclass
class ThermalMetrics:
"""Physiological metrics from thermal assay"""
sample_id: str
timepoint_hours: float
temperature_c: float
fv_fm: float # Maximum quantum yield of PSII
bleaching_score: int # 1-5 scale
respiration_rate: Optional[float] = None # mg O2/cm2/h
protein_content: Optional[float] = None # mg/cm2
@dataclass
class ThermalToleranceResult:
"""Computed thermal tolerance metrics"""
sample_id: str
ed50_temp: float # Temperature at 50% physiological decline
critical_thermal_max: float # CTmax
bleaching_threshold: float
recovery_potential: float # 0-1 scale
thermal_tolerance_index: float # Composite score 0-100
heat_shock_response_magnitude: float
acclimation_capacity: float
class ThermalToleranceAssay:
"""High-throughput thermal tolerance screening"""
# Key thermal tolerance genes
THERMAL_BIOMARKERS = {
'heat_shock_proteins': ['HSP70', 'HSP90', 'HSP16', 'HSP40'],
'antioxidant': ['SOD', 'CAT', 'GPX', 'PRX'],
'apoptosis': ['BCL2', 'BAX', 'CASP3'],
'metabolism': ['ATP5A', 'ND1', 'COX1'],
'calcification': ['CA', 'GALAXIN', 'SLC4A']
}
def __init__(self, config: 'ThermalAssayConfig'):
self.config = config
self.metrics_data: Dict[str, List[ThermalMetrics]] = {}
self.gene_expression: Dict[str, pd.DataFrame] = {}
def add_metrics(self, metrics: ThermalMetrics):
if metrics.sample_id not in self.metrics_data:
self.metrics_data[metrics.sample_id] = []
self.metrics_data[metrics.sample_id].append(metrics)
def load_expression_data(self, sample_id: str, count_matrix: pd.DataFrame):
"""Load normalized gene expression from RNA-seq"""
self.gene_expression[sample_id] = count_matrix
def calculate_ed50(self, temps: np.ndarray, responses: np.ndarray) -> float:
"""Calculate ED50 (effective dose for 50% response) using logistic model"""
def logistic(x, bottom, top, ec50, slope):
return bottom + (top - bottom) / (1 + (x / ec50)**slope)
try:
popt, _ = curve_fit(
logistic, temps, responses,
p0=[0, 100, 30, -1],
bounds=([0, 50, 25, -10], [50, 100, 40, -0.1])
)
return popt[2] # EC50
except RuntimeError:
return np.nan
def calculate_bleaching_threshold(self, metrics: List[ThermalMetrics]) -> float:
"""Determine temperature threshold for bleaching onset"""
temps = np.array([m.temperature_c for m in metrics])
bleaching = np.array([m.bleaching_score for m in metrics])
fv_fm = np.array([m.fv_fm for m in metrics])
# Find first temperature where bleaching score > 2 or Fv/Fm drops > 20%
control_fvfm = fv_fm[temps == self.config.control_temp].mean()
for temp in sorted(set(temps)):
temp_mask = temps == temp
if bleaching[temp_mask].mean() > 2:
return temp
if fv_fm[temp_mask].mean() < control_fvfm * 0.8:
return temp
return max(temps)
def calculate_recovery_potential(self, metrics: List[ThermalMetrics]) -> float:
"""Calculate recovery potential after stress removal"""
control_fvfm = [m.fv_fm for m in metrics
if m.temperature_c == self.config.control_temp]
recovery_fvfm = [m.fv_fm for m in metrics
if m.timepoint_hours > self.config.exposure_duration]
if not control_fvfm or not recovery_fvfm:
return np.nan
recovery_ratio = np.mean(recovery_fvfm) / np.mean(control_fvfm)
return min(max(recovery_ratio, 0), 1)
def calculate_hsr_magnitude(self, sample_id: str) -> float:
"""Calculate heat shock response magnitude from expression data"""
if sample_id not in self.gene_expression:
return np.nan
expr = self.gene_expression[sample_id]
# Calculate fold change for HSP genes
hsp_genes = self.THERMAL_BIOMARKERS['heat_shock_proteins']
control_cols = [c for c in expr.columns if 'control' in c.lower()]
stress_cols = [c for c in expr.columns if 'stress' in c.lower()]
if not control_cols or not stress_cols:
return np.nan
hsr_values = []
for gene in hsp_genes:
if gene in expr.index:
control_expr = expr.loc[gene, control_cols].mean()
stress_expr = expr.loc[gene, stress_cols].mean()
if control_expr > 0:
hsr_values.append(np.log2(stress_expr / control_expr))
return np.mean(hsr_values) if hsr_values else np.nan
def analyze_sample(self, sample_id: str) -> ThermalToleranceResult:
"""Perform complete thermal tolerance analysis for a sample"""
metrics = self.metrics_data.get(sample_id, [])
if not metrics:
raise ValueError(f"No metrics data for sample {sample_id}")
# Sort by temperature
metrics = sorted(metrics, key=lambda m: m.temperature_c)
temps = np.array([m.temperature_c for m in metrics])
fv_fm = np.array([m.fv_fm for m in metrics])
# Calculate ED50
ed50 = self.calculate_ed50(temps, fv_fm * 100)
# Calculate bleaching threshold
bleaching_threshold = self.calculate_bleaching_threshold(metrics)
# Calculate CTmax (critical thermal maximum)
# Defined as temp where Fv/Fm drops below 0.3
ctmax_mask = fv_fm < 0.3
if any(ctmax_mask):
ctmax = temps[ctmax_mask][0]
else:
ctmax = max(temps)
# Calculate recovery potential
recovery = self.calculate_recovery_potential(metrics)
# Calculate HSR magnitude
hsr_magnitude = self.calculate_hsr_magnitude(sample_id)
# Calculate composite thermal tolerance index (0-100)
# Weighted combination of metrics
tti = self._calculate_composite_index(
ed50, ctmax, bleaching_threshold, recovery, hsr_magnitude
)
return ThermalToleranceResult(
sample_id=sample_id,
ed50_temp=ed50,
critical_thermal_max=ctmax,
bleaching_threshold=bleaching_threshold,
recovery_potential=recovery if recovery else 0.0,
thermal_tolerance_index=tti,
heat_shock_response_magnitude=hsr_magnitude if hsr_magnitude else 0.0,
acclimation_capacity=recovery * 100 if recovery else 0.0
)
def _calculate_composite_index(
self,
ed50: float,
ctmax: float,
bleaching_threshold: float,
recovery: float,
hsr: float
) -> float:
"""Calculate weighted composite thermal tolerance index"""
# Normalize each metric to 0-100 scale
ed50_score = min(max((ed50 - 26) / (34 - 26) * 100, 0), 100)
ctmax_score = min(max((ctmax - 28) / (36 - 28) * 100, 0), 100)
bleaching_score = min(max((bleaching_threshold - 26) / (34 - 26) * 100, 0), 100)
recovery_score = recovery * 100
hsr_score = min(max(hsr * 20, 0), 100) # Assuming log2 fold change
# Weighted average
weights = {
'ed50': 0.25,
'ctmax': 0.20,
'bleaching': 0.25,
'recovery': 0.15,
'hsr': 0.15
}
tti = (
weights['ed50'] * ed50_score +
weights['ctmax'] * ctmax_score +
weights['bleaching'] * bleaching_score +
weights['recovery'] * recovery_score +
weights['hsr'] * hsr_score
)
return round(tti, 2)
def generate_thermal_profile_plot(self, sample_id: str, output_path: str):
"""Generate visualization of thermal response"""
metrics = self.metrics_data.get(sample_id, [])
if not metrics:
return
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
temps = [m.temperature_c for m in metrics]
fv_fm = [m.fv_fm for m in metrics]
bleaching = [m.bleaching_score for m in metrics]
# Fv/Fm vs Temperature
axes[0, 0].scatter(temps, fv_fm, c='blue', alpha=0.6)
axes[0, 0].set_xlabel('Temperature (°C)')
axes[0, 0].set_ylabel('Fv/Fm')
axes[0, 0].set_title('Photosynthetic Efficiency')
axes[0, 0].axhline(y=0.5, color='r', linestyle='--', label='Healthy threshold')
# Bleaching score vs Temperature
axes[0, 1].scatter(temps, bleaching, c='red', alpha=0.6)
axes[0, 1].set_xlabel('Temperature (°C)')
axes[0, 1].set_ylabel('Bleaching Score')
axes[0, 1].set_title('Bleaching Response')
# Time series at max temp
max_temp = max(temps)
max_temp_metrics = [m for m in metrics if m.temperature_c == max_temp]
times = [m.timepoint_hours for m in max_temp_metrics]
fv_fm_time = [m.fv_fm for m in max_temp_metrics]
axes[1, 0].plot(times, fv_fm_time, 'b-o')
axes[1, 0].set_xlabel('Time (hours)')
axes[1, 0].set_ylabel('Fv/Fm')
axes[1, 0].set_title(f'Time Course at {max_temp}°C')
# Thermal tolerance summary
result = self.analyze_sample(sample_id)
summary_text = f"""
Thermal Tolerance Index: {result.thermal_tolerance_index:.1f}
ED50: {result.ed50_temp:.1f}°C
Critical Thermal Max: {result.critical_thermal_max:.1f}°C
Bleaching Threshold: {result.bleaching_threshold:.1f}°C
Recovery Potential: {result.recovery_potential:.2f}
HSR Magnitude: {result.heat_shock_response_magnitude:.2f}
"""
axes[1, 1].text(0.1, 0.5, summary_text, fontsize=12,
verticalalignment='center', fontfamily='monospace')
axes[1, 1].axis('off')
plt.tight_layout()
plt.savefig(output_path, dpi=300)
plt.close()
4. Symbiont Compatibility Module
# coral_screening_pipeline/symbiont_assay.py
import numpy as np
import pandas as pd
from dataclasses import dataclass
from typing import List, Dict, Tuple, Optional
from collections import Counter
import re
@dataclass
class SymbiontProfile:
"""Symbiont community profile"""
sample_id: str
clade: str # A, B, C, D, etc.
genus: str # Symbiodinium, Breviolum, Cladocopium, Durusdinium
species: Optional[str] = None
relative_abundance: float = 0.0
its2_types: List[str] = None
def __post_init__(self):
if self.its2_types is None:
self.its2_types = []
@dataclass
class CompatibilityResult:
"""Results from symbiont compatibility assay"""
sample_id: str
symbiont_genotype: str
host_genotype: str
colonization_success: float # 0-1
growth_rate_benefit: float # relative to control
stress_protection: float # survival under stress
photosynthate_transfer: float # carbon flux
compatibility_score: float # composite 0-100
optimal_symbiont: str # best matching symbiont genus
dominant_its2_type: str
class SymbiontCompatibilityAssay:
"""Screening for optimal host-symbiont combinations"""
# Known symbiont characteristics
SYMBIONT_TRAITS = {
'Durusdinium': {
'thermal_tolerance': 0.95,
'growth_rate': 0.6,
'carbon_sharing': 0.5,
'stress_tolerance': 0.9
},
'Cladocopium': {
'thermal_tolerance': 0.7,
'growth_rate': 0.85,
'carbon_sharing': 0.9,
'stress_tolerance': 0.6
},
'Symbiodinium': {
'thermal_tolerance': 0.65,
'growth_rate': 0.8,
'carbon_sharing': 0.85,
'stress_tolerance': 0.55
},
'Breviolum': {
'thermal_tolerance': 0.6,
'growth_rate': 0.9,
'carbon_sharing': 0.95,
'stress_tolerance': 0.5
}
}
# Host-symbiont compatibility genes
COMPATIBILITY_GENES = {
'host': ['SYMREC', 'NFR5', 'LYK6', 'SRK', 'LEC'],
'symbiont': ['Sym32', 'Sym34', 'NHR1', 'MAMP1']
}
def __init__(self, config: 'SymbiontAssayConfig'):
self.config = config
self.symbiont_profiles: Dict[str, List[SymbiontProfile]] = {}
self.expression_data: Dict[str, pd.DataFrame] = {}
self.inoculation_matrix: Dict[Tuple[str, str], Dict] = {} # (host, symbiont) -> results
def parse_its2_sequence(self, sequence: str) -> SymbiontProfile:
"""Parse ITS2 sequence to classify symbiont"""
# Simplified classification based on sequence motifs
# In practice, would use proper alignment and phylogenetic placement
clade_markers = {
'A': 'Symbiodinium',
'B': 'Breviolum',
'C': 'Cladocopium',
'D': 'Durusdinium',
'E': 'Effrenium',
'F': 'Fugacium',
'G': 'Gerakladium'
}
# Extract clade from sequence (simplified)
for clade, genus in clade_markers.items():
if f"clade_{clade}" in sequence.lower() or f"type_{clade}" in sequence.lower():
return SymbiontProfile(
sample_id="",
clade=clade,
genus=genus
)
# Default to unknown
return SymbiontProfile(sample_id="", clade="Unknown", genus="Unknown")
def analyze_its2_community(self, sample_id: str, sequences: List[str]) -> List[SymbiontProfile]:
"""Analyze ITS2 amplicon sequencing to profile symbiont community"""
profiles = []
clade_counts = Counter()
for seq in sequences:
profile = self.parse_its2_sequence(seq)
clade_key = f"{profile.clade}_{profile.genus}"
clade_counts[clade_key] += 1
total = len(sequences)
for clade_key, count in clade_counts.items():
clade, genus = clade_key.split('_', 1)
profiles.append(SymbiontProfile(
sample_id=sample_id,
clade=clade,
genus=genus,
relative_abundance=count / total
))
self.symbiont_profiles[sample_id] = profiles
return profiles
def calculate_colonization_success(
self,
host_id: str,
symbiont_genus: str,
cell_counts: Dict[int, float] # timepoint -> cells/cm2
) -> float:
"""Calculate symbiont colonization success over time"""
if not cell_counts:
return 0.0
initial = cell_counts.get(0, cell_counts[min(cell_counts.keys())])
final = cell_counts[max(cell_counts.keys())]
if initial == 0:
return 0.0
# Normalized to expected colonization density
expected_final = self.config.inoculation_density * 0.001 # Expected density per cm2
success = min(final / expected_final, 1.0)
return success
def calculate_growth_benefit(
self,
host_id: str,
symbiont_genus: str,
host_growth_rates: Dict[str, float] # condition -> rate
) -> float:
"""Calculate host growth benefit from symbiosis"""
if 'symbiotic' not in host_growth_rates or 'aposymbiotic' not in host_growth_rates:
return 0.0
symbiotic = host_growth_rates['symbiotic']
aposymbiotic = host_growth_rates['aposymbiotic']
if aposymbiotic == 0:
return 0.0
benefit = (symbiotic - aposymbiotic) / aposymbiotic
return max(benefit, 0.0)
def analyze_compatibility_genes(
self,
host_expr: pd.DataFrame,
symbiont_expr: pd.DataFrame
) -> float:
"""Analyze expression of compatibility-related genes"""
host_genes = self.COMPATIBILITY_GENES['host']
symbiont_genes = self.COMPATIBILITY_GENES['symbiont']
# Check for upregulation of recognition genes
host_scores = []
for gene in host_genes:
if gene in host_expr.index:
# Compare symbiotic vs control
symb_cols = [c for c in host_expr.columns if 'symbiotic' in c.lower()]
ctrl_cols = [c for c in host_expr.columns if 'control' in c.lower()]
if symb_cols and ctrl_cols:
fc = host_expr.loc[gene, symb_cols].mean() / host_expr.loc[gene, ctrl_cols].mean()
host_scores.append(min(fc, 2.0) / 2.0) # Normalize to 0-1
symbiont_scores = []
for gene in symbiont_genes:
if gene in symbiont_expr.index:
symbiont_scores.append(1.0) # Presence indicates compatibility
host_avg = np.mean(host_scores) if host_scores else 0.5
symb_avg = np.mean(symbiont_scores) if symbiont_scores else 0.5
return (host_avg + symb_avg) / 2
def calculate_compatibility_score(
self,
colonization: float,
growth_benefit: float,
stress_protection: float,
carbon_transfer: float
) -> float:
"""Calculate composite compatibility score"""
weights = {
'colonization': 0.25,
'growth': 0.25,
'stress': 0.25,
'carbon': 0.25
}
score = (
weights['colonization'] * colonization * 100 +
weights['growth'] * min(growth_benefit, 1.0) * 100 +
weights['stress'] * stress_protection * 100 +
weights['carbon'] * carbon_transfer * 100
)
return round(score, 2)
def identify_optimal_symbiont(
self,
host_genotype: str,
environmental_conditions: Dict[str, float]
) -> Tuple[str, float]:
"""Identify optimal symbiont for given host and environment"""
# Calculate suitability score for each symbiont type
scores = {}
for genus, traits in self.SYMBIONT_TRAITS.items():
# Weight traits based on environmental conditions
temp_weight = environmental_conditions.get('temperature_stress', 0.5)
growth_weight = environmental_conditions.get('growth_priority', 0.3)
carbon_weight = environmental_conditions.get('carbon_priority', 0.2)
score = (
temp_weight * traits['thermal_tolerance'] +
growth_weight * traits['growth_rate'] +
carbon_weight * traits['carbon_sharing']
)
scores[genus] = score
best_symbiont = max(scores, key=scores.get)
return best_symbiont, scores[best_symbiont]
def run_cross_inoculation_screen(
self,
host_ids: List[str],
symbiont_cultures: List[str],
n_replicates: int = 3
) -> Dict[Tuple[str, str], CompatibilityResult]:
"""Run full cross-inoculation matrix"""
results = {}
for host_id in host_ids:
for symbiont in symbiont_cultures:
# This would normally run the actual experiment
# Here we simulate based on known traits
genus = symbiont.split('_')[0]
traits = self.SYMBIONT_TRAITS.get(genus, {})
# Simulate results with some noise
colonization = traits.get('growth_rate', 0.5) + np.random.normal(0, 0.1)
growth_benefit = traits.get('carbon_sharing', 0.5) + np.random.normal(0, 0.1)
stress_protection = traits.get('stress_tolerance', 0.5) + np.random.normal(0, 0.1)
carbon_transfer = traits.get('carbon_sharing', 0.5) + np.random.normal(0, 0.1)
# Clamp values
colonization = max(min(colonization, 1.0), 0.0)
growth_benefit = max(min(growth_benefit, 1.0), 0.0)
stress_protection = max(min(stress_protection, 1.0), 0.0)
carbon_transfer = max(min(carbon_transfer, 1.0), 0.0)
compatibility = self.calculate_compatibility_score(
colonization, growth_benefit, stress_protection, carbon_transfer
)
results[(host_id, symbiont)] = CompatibilityResult(
sample_id=host_id,
symbiont_genotype=symbiont,
host_genotype=host_id,
colonization_success=round(colonization, 3),
growth_rate_benefit=round(growth_benefit, 3),
stress_protection=round(stress_protection, 3),
photosynthate_transfer=round(carbon_transfer, 3),
compatibility_score=compatibility,
optimal_symbiont=genus,
dominant_its2_type=f"{genus}_type1"
)
return results
5. Disease Resistance Module
# coral_screening_pipeline/disease_assay.py
import numpy as np
import pandas as pd
from dataclasses import dataclass
from typing import List, Dict, Optional, Tuple
from scipy import stats
from lifelines import KaplanMeierFitter
import matplotlib.pyplot as plt
@dataclass
class DiseaseMetrics:
"""Metrics from disease challenge assay"""
sample_id: str
pathogen: str
dose_cfu_ml: float
timepoint_hours: float
lesion_area_cm2: float = 0.0
survival_status: bool = True # True = alive
disease_severity: int = 0 # 0-5 scale
immune_gene_expression: Optional[Dict[str, float]] = None
@dataclass
class DiseaseResistanceResult:
"""Computed disease resistance metrics"""
sample_id: str
pathogen: str
ld50_dose: float # Lethal dose 50%
survival_rate: float # at challenge dose
disease_progression_rate: float # lesion growth rate
immune_response_magnitude: float
resistance_index: float # composite 0-100
key_immune_genes: List[str]
protection_duration_days: float
class DiseaseResistanceAssay:
"""High-throughput disease resistance screening"""
# Coral immune genes
IMMUNE_GENES = {
'pattern_recognition': ['TLR', 'NOD', 'RIG', 'MD5', 'LYS'],
'signaling': ['NFkB', 'MAPK', 'JNK', 'STAT', 'MYD88'],
'effectors': ['DEF', 'C3', 'BPI', 'LYZ', 'MPO'],
'antioxidant': ['SOD', 'CAT', 'GPX', 'PRX', 'TRX'],
'apoptosis': ['CASP', 'BCL', 'FAS', 'TRADD', 'FADD'],
'innate': ['NLR', 'TOLL', 'IMD', 'STING', 'CGAS']
}
# Known pathogen virulence factors
PATHOGEN_FACTORS = {
'Vibrio_coralliilyticus': {
'virulence': 0.85,
'thermal_sensitivity': 1.2, # More virulent at high temp
'target_tissue': 'tissue_mucus_interface'
},
'Vibrio_owensii': {
'virulence': 0.75,
'thermal_sensitivity': 1.1,
'target_tissue': 'gastrovascular_cavity'
},
'Thalassomonas_loyana': {
'virulence': 0.70,
'thermal_sensitivity': 1.0,
'target_tissue': 'coral_surface'
}
}
def __init__(self, config: 'DiseaseAssayConfig'):
self.config = config
self.metrics_data: Dict[str, List[DiseaseMetrics]] = {}
self.expression_data: Dict[str, pd.DataFrame] = {}
def add_metrics(self, metrics: DiseaseMetrics):
key = f"{metrics.sample_id}_{metrics.pathogen}"
if key not in self.metrics_data:
self.metrics_data[key] = []
self.metrics_data[key].append(metrics)
def calculate_ld50(
self,
sample_id: str,
pathogen: str
) -> float:
"""Calculate LD50 using probit analysis"""
key = f"{sample_id}_{pathogen}"
metrics = self.metrics_data.get(key, [])
if not metrics:
return np.nan
# Group by dose
dose_survival = {}
for m in metrics:
if m.dose_cfu_ml not in dose_survival:
dose_survival[m.dose_cfu_ml] = {'alive': 0, 'total': 0}
dose_survival[m.dose_cfu_ml]['total'] += 1
if m.survival_status:
dose_survival[m.dose_cfu_ml]['alive'] += 1
doses = sorted(dose_survival.keys())
mortality_rates = [
1 - (dose_survival[d]['alive'] / dose_survival[d]['total'])
for d in doses
]
# Find dose with ~50% mortality
for i, rate in enumerate(mortality_rates):
if rate >= 0.5:
if i == 0:
return doses[0]
# Linear interpolation
prev_rate = mortality_rates[i-1]
prev_dose = doses[i-1]
curr_dose = doses[i]
ld50 = prev_dose + (0.5 - prev_rate) / (rate - prev_rate) * (curr_dose - prev_dose)
return ld50
return max(doses) # If never reaches 50% mortality
def calculate_survival_curve(
self,
sample_id: str,
pathogen: str,
dose: float
) -> Tuple[np.ndarray, np.ndarray]:
"""Generate Kaplan-Meier survival curve data"""
key = f"{sample_id}_{pathogen}"
metrics = self.metrics_data.get(key, [])
# Filter by dose
dose_metrics = [m for m in metrics if m.dose_cfu_ml == dose]
if not dose_metrics:
return np.array([]), np.array([])
# Prepare data for survival analysis
times = np.array([m.timepoint_hours for m in dose_metrics])
events = np.array([not m.survival_status for m in dose_metrics]) # 1 = death event
# Fit Kaplan-Meier
kmf = KaplanMeierFitter()
kmf.fit(times, events)
return kmf.survival_function_.index.values, kmf.survival_function_['KM_estimate'].values
def calculate_disease_progression(
self,
sample_id: str,
pathogen: str
) -> float:
"""Calculate rate of disease progression (lesion growth)"""
key = f"{sample_id}_{pathogen}"
metrics = self.metrics_data.get(key, [])
if len(metrics) < 2:
return 0.0
times = np.array([m.timepoint_hours for m in metrics])
lesions = np.array([m.lesion_area_cm2 for m in metrics])
# Linear regression for growth rate
slope, _, _, _, _ = stats.linregress(times, lesions)
return max(slope, 0.0) # cm2/hour
def calculate_immune_response(
self,
sample_id: str,
pathogen: str
) -> Tuple[float, List[str]]:
"""Calculate magnitude of immune response"""
key = f"{sample_id}_{pathogen}"
metrics = self.metrics_data.get(key, [])
# Collect immune gene expression
all_immune_expr = {}
for m in metrics:
if m.immune_gene_expression:
for gene, expr in m.immune_gene_expression.items():
if gene not in all_immune_expr:
all_immune_expr[gene] = []
all_immune_expr[gene].append(expr)
if not all_immune_expr:
return 0.0, []
# Calculate fold change for each immune gene category
category_responses = {}
for category, genes in self.IMMUNE_GENES.items():
category_values = []
for gene in genes:
if gene in all_immune_expr:
values = all_immune_expr[gene]
# Calculate fold change from baseline
if len(values) > 1:
baseline = values[0]
max_response = max(values)
if baseline > 0:
fc = max_response / baseline
category_values.append(np.log2(fc))
if category_values:
category_responses[category] = np.mean(category_values)
# Overall immune response magnitude
overall_magnitude = np.mean(list(category_responses.values())) if category_responses else 0.0
# Identify key responding genes
key_genes = []
for gene, values in all_immune_expr.items():
if len(values) > 1:
fc = max(values) / values[0] if values[0] > 0 else 1
if fc > 2.0: # 2-fold induction threshold
key_genes.append(gene)
return overall_magnitude, key_genes
def calculate_resistance_index(
self,
ld50: float,
survival_rate: float,
progression_rate: float,
immune_magnitude: float
) -> float:
"""Calculate composite disease resistance index"""
# Normalize metrics to 0-100 scale
ld50_score = min(ld50 / 10**6 * 100, 100) # Higher LD50 = more resistant
survival_score = survival_rate * 100
# Lower progression = more resistant (invert)
max_progression = 1.0 # cm2/hour threshold
progression_score = max(100 - (progression_rate / max_progression * 100), 0)
immune_score = min(max(immune_magnitude * 25, 0), 100) # Normalize log2 FC
# Weighted combination
weights = {
'ld50': 0.25,
'survival': 0.35,
'progression': 0.20,
'immune': 0.20
}
index = (
weights['ld50'] * ld50_score +
weights['survival'] * survival_score +
weights['progression'] * progression_score +
weights['immune'] * immune_score
)
return round(index, 2)
def analyze_sample(
self,
sample_id: str,
pathogen: str
) -> DiseaseResistanceResult:
"""Perform complete disease resistance analysis"""
ld50 = self.calculate_ld50(sample_id, pathogen)
# Get survival rate at standard challenge dose
challenge_dose = self.config.challenge_doses[1] # Middle dose
key = f"{sample_id}_{pathogen}"
metrics = self.metrics_data.get(key, [])
dose_metrics = [m for m in metrics if m.dose_cfu_ml == challenge_dose]
if dose_metrics:
final_status = [m for m in dose_metrics if m.timepoint_hours >= self.config.observation_period * 24]
survival_rate = sum(1 for m in final_status if m.survival_status) / len(final_status) if final_status else 0
else:
survival_rate = 0.0
progression = self.calculate_disease_progression(sample_id, pathogen)
immune_mag, key_genes = self.calculate_immune_response(sample_id, pathogen)
resistance_index = self.calculate_resistance_index(
ld50 if not np.isnan(ld50) else 10**6,
survival_rate,
progression,
immune_mag
)
return DiseaseResistanceResult(
sample_id=sample_id,
pathogen=pathogen,
ld50_dose=ld50 if not np.isnan(ld50) else 0.0,
survival_rate=survival_rate,
disease_progression_rate=progression,
immune_response_magnitude=immune_mag,
resistance_index=resistance_index,
key_immune_genes=key_genes[:10], # Top 10
protection_duration_days=self._calculate_protection_duration(metrics)
)
def _calculate_protection_duration(self, metrics: List[DiseaseMetrics]) -> float:
"""Calculate duration before disease onset"""
if not metrics:
return 0.0
# Find first timepoint with disease severity > 1
sorted_metrics = sorted(metrics, key=lambda m: m.timepoint_hours)
for m in sorted_metrics:
if m.disease_severity > 1:
return m.timepoint_hours / 24 # Convert to days
return max(m.timepoint_hours for m in metrics) / 24
def generate_survival_plot(
self,
sample_ids: List[str],
pathogen: str,
output_path: str
):
"""Generate comparative survival curves"""
plt.figure(figsize=(10, 8))
for sample_id in sample_ids:
times, survival = self.calculate_survival_curve(
sample_id,
pathogen,
self.config.challenge_doses[1]
)
if len(times) > 0:
plt.step(times / 24, survival * 100, where='post', label=sample_id)
plt.xlabel('Days post-challenge')
plt.ylabel('Survival (%)')
plt.title(f'Survival Curves - {pathogen}')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.ylim(0, 105)
plt.xlim(0, self.config.observation_period)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig(output_path, dpi=300)
plt.close()
6. Genomic Analysis Module
# coral_screening_pipeline/genomic_analysis.py
import numpy as np
import pandas as pd
from dataclasses import dataclass
from typing import List, Dict, Optional, Tuple
from collections import defaultdict
@dataclass
class GeneticVariant:
"""Genetic variant annotation"""
chrom: str
pos: int
ref: str
alt: str
gene: Optional[str] = None
impact: str = "MODIFIER" # HIGH, MODERATE, LOW, MODIFIER
effect: str = "intergenic"
allele_freq: float = 0.0
phenotype_association: Optional[str] = None
@dataclass
class GenomicProfile:
"""Genomic profile for climate resilience"""
sample_id: str
thermal_tolerance_alleles: Dict[str, int] # gene -> allele count
disease_resistance_alleles: Dict[str, int]
symbiont_compatibility_alleles: Dict[str, int]
heterozygosity: float
inbreeding_coefficient: float
population_assignment: str
adaptive_variants: List[GeneticVariant]
class GenomicAnalyzer:
"""Analyze coral genomes for climate-resilience markers"""
# Climate-resilience associated genes
RESILIENCE_GENES = {
'thermal': {
'HSP70': {'chrom': 'chr1', 'pos_range': (100000, 105000), 'effect': 'positive'},
'HSP90': {'chrom': 'chr2', 'pos_range': (200000, 205000), 'effect': 'positive'},
'SOD1': {'chrom': 'chr3', 'pos_range': (300000, 302000), 'effect': 'positive'},
'CAT': {'chrom': 'chr4', 'pos_range': (400000, 403000), 'effect': 'positive'},
'GPX': {'chrom': 'chr5', 'pos_range': (500000, 502000), 'effect': 'positive'},
'BCL2': {'chrom': 'chr6', 'pos_range': (600000, 603000), 'effect': 'positive'},
'TNF': {'chrom': 'chr7', 'pos_range': (700000, 702000), 'effect': 'positive'},
'TRP': {'chrom': 'chr8', 'pos_range': (800000, 802000), 'effect': 'positive'}
},
'disease': {
'TLR4': {'chrom': 'chr1', 'pos_range': (150000, 155000), 'effect': 'positive'},
'NOD2': {'chrom': 'chr2', 'pos_range': (250000, 255000), 'effect': 'positive'},
'DEF1': {'chrom': 'chr3', 'pos_range': (350000, 352000), 'effect': 'positive'},
'C3': {'chrom': 'chr4', 'pos_range': (450000, 455000), 'effect': 'positive'},
'LYZ': {'chrom': 'chr5', 'pos_range': (550000, 552000), 'effect': 'positive'},
'MPO': {'chrom': 'chr6', 'pos_range': (650000, 653000), 'effect': 'positive'}
},
'symbiont': {
'SYMREC1': {'chrom': 'chr1', 'pos_range': (180000, 185000), 'effect': 'positive'},
'NFR5': {'chrom': 'chr2', 'pos_range': (280000, 285000), 'effect': 'positive'},
'LYK6': {'chrom': 'chr3', 'pos_range': (380000, 385000), 'effect': 'positive'},
'SRK': {'chrom': 'chr4', 'pos_range': (480000, 485000), 'effect': 'positive'}
}
}
# Known adaptive SNPs from previous studies
ADAPTIVE_SNPS = {
'rs_thermal_001': {'gene': 'HSP70', 'pos': 102500, 'ref': 'A', 'alt': 'G', 'effect_size': 0.15},
'rs_thermal_002': {'gene': 'HSP90', 'pos': 201800, 'ref': 'C', 'alt': 'T', 'effect_size': 0.12},
'rs_thermal_003': {'gene': 'SOD1', 'pos': 301000, 'ref': 'G', 'alt': 'A', 'effect_size': 0.10},
'rs_disease_001': {'gene': 'TLR4', 'pos': 152300, 'ref': 'T', 'alt': 'C', 'effect_size': 0.18},
'rs_disease_002': {'gene': 'DEF1', 'pos': 351500, 'ref': 'A', 'alt': 'G', 'effect_size': 0.14},
'rs_symbiont_001': {'gene': 'SYMREC1', 'pos': 182000, 'ref': 'C', 'alt': 'G', 'effect_size': 0.16}
}
def __init__(self, reference_genome: str):
self.reference = reference_genome
self.variant_data: Dict[str, List[GeneticVariant]] = {}
self.genotype_matrix: Optional[pd.DataFrame] = None
def load_vcf(self, sample_id: str, vcf_path: str):
"""Load and parse VCF file"""
variants = []
with open(vcf_path) as f:
for line in f:
if line.startswith('#'):
continue
fields = line.strip().split('\t')
chrom, pos, vid, ref, alt = fields[:5]
# Parse INFO field for annotations
info = {}
if len(fields) > 7:
for item in fields[7].split(';'):
if '=' in item:
key, val = item.split('=', 1)
info[key] = val
variant = GeneticVariant(
chrom=chrom,
pos=int(pos),
ref=ref,
alt=alt.split(',')[0], # First alt allele
gene=info.get('GENE'),
impact=info.get('IMPACT', 'MODIFIER'),
effect=info.get('EFFECT', 'intergenic'),
allele_freq=float(info.get('AF', 0.0))
)
variants.append(variant)
self.variant_data[sample_id] = variants
def build_genotype_matrix(self, sample_ids: List[str]) -> pd.DataFrame:
"""Build genotype matrix across all samples"""
# Collect all variant positions
all_positions = set()
for sample_id in sample_ids:
for var in self.variant_data.get(sample_id, []):
all_positions.add((var.chrom, var.pos, var.ref, var.alt))
# Build matrix
data = {}
for sample_id in sample_ids:
sample_variants = {(v.chrom, v.pos, v.ref, v.alt): v for v in self.variant_data.get(sample_id, [])}
genotypes = []
for pos in sorted(all_positions):
if pos in sample_variants:
# Encode as allele count (0, 1, 2)
genotypes.append(1) # Heterozygous assumption for simplified case
else:
genotypes.append(0)
data[sample_id] = genotypes
index = [f"{p[0]}_{p[1]}_{p[2]}_{p[3]}" for p in sorted(all_positions)]
self.genotype_matrix = pd.DataFrame(data, index=index)
return self.genotype_matrix
def calculate_heterozygosity(self, sample_id: str) -> float:
"""Calculate genome-wide heterozygosity"""
variants = self.variant_data.get(sample_id, [])
if not variants:
return 0.0
# Count heterozygous sites
het_count = sum(1 for v in variants if 0 < v.allele_freq < 1)
return het_count / len(variants)
def calculate_inbreeding_coefficient(
self,
sample_id: str,
population_allele_freqs: Dict[str, float]
) -> float:
"""Calculate inbreeding coefficient (F) based on observed vs expected heterozygosity"""
variants = self.variant_data.get(sample_id, [])
if not variants:
return 0.0
observed_het = 0
expected_het = 0
n_sites = 0
for var in variants:
pos_key = f"{var.chrom}_{var.pos}"
if pos_key in population_allele_freqs:
p = population_allele_freqs[pos_key]
q = 1 - p
# Expected heterozygosity under HWE
expected_het += 2 * p * q
# Observed (simplified - assumes we have genotype data)
if 0 < var.allele_freq < 1:
observed_het += 1
n_sites += 1
if n_sites == 0 or expected_het == 0:
return 0.0
# F = 1 - (Ho/He)
F = 1 - (observed_het / expected_het)
return max(min(F, 1), -1)
def identify_adaptive_variants(self, sample_id: str) -> List[GeneticVariant]:
"""Identify variants in known adaptive loci"""
variants = self.variant_data.get(sample_id, [])
adaptive = []
for var in variants:
for snp_id, snp_info in self.ADAPTIVE_SNPS.items():
if (var.gene == snp_info['gene'] and
abs(var.pos - snp_info['pos']) < 1000): # Within 1kb
var.phenotype_association = f"adaptive_{snp_id}"
adaptive.append(var)
return adaptive
def count_resilience_alleles(
self,
sample_id: str,
category: str
) -> Dict[str, int]:
"""Count alleles in climate-resilience genes"""
variants = self.variant_data.get(sample_id, [])
gene_counts = {}
target_genes = self.RESILIENCE_GENES.get(category, {})
for gene_name in target_genes:
gene_info = target_genes[gene_name]
chrom = gene_info['chrom']
pos_range = gene_info['pos_range']
# Count variants in this gene
count = sum(1 for v in variants
if v.chrom == chrom and
pos_range[0] <= v.pos <= pos_range[1])
gene_counts[gene_name] = count
return gene_counts
def assign_population(
self,
sample_id: str,
reference_populations: Dict[str, List[str]] # pop -> sample_ids
) -> str:
"""Assign sample to population based on genetic similarity"""
if self.genotype_matrix is None:
return "unknown"
# Calculate genetic distance to each population
sample_genotypes = self.genotype_matrix[sample_id].values
pop_distances = {}
for pop_name, pop_samples in reference_populations.items():
pop_mean = self.genotype_matrix[pop_samples].mean(axis=1).values
distance = np.mean((sample_genotypes - pop_mean) ** 2)
pop_distances[pop_name] = distance
return min(pop_distances, key=pop_distances.get)
def create_genomic_profile(self, sample_id: str) -> GenomicProfile:
"""Create comprehensive genomic profile"""
thermal_alleles = self.count_resilience_alleles(sample_id, 'thermal')
disease_alleles = self.count_resilience_alleles(sample_id, 'disease')
symbiont_alleles = self.count_resilience_alleles(sample_id, 'symbiont')
heterozygosity = self.calculate_heterozygosity(sample_id)
adaptive_vars = self.identify_adaptive_variants(sample_id)
return GenomicProfile(
sample_id=sample_id,
thermal_tolerance_alleles=thermal_alleles,
disease_resistance_alleles=disease_alleles,
symbiont_compatibility_alleles=symbiont_alleles,
heterozygosity=heterozygosity,
inbreeding_coefficient=0.0, # Would need population data
population_assignment="unknown", # Would need reference populations
adaptive_variants=adaptive_vars
)
7. Multi-Omics Integration and Machine Learning
# coral_screening_pipeline/integration.py
import numpy as np
import pandas as pd
from dataclasses import dataclass
from typing import List, Dict, Optional, Tuple
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.model_selection import cross_val_score
from sklearn.feature_selection import SelectKBest, f_regression
import warnings
warnings.filterwarnings('ignore')
@dataclass
class ClimateResilienceScore:
"""Integrated climate resilience score"""
sample_id: str
overall_score: float # 0-100
thermal_component: float
disease_component: float
symbiont_component: float
genomic_component: float
confidence_interval: Tuple[float, float]
priority_rank: int
recommendations: List[str]
class MultiomicsIntegrator:
"""Integrate multi-omics data for climate resilience prediction"""
def __init__(self):
self.scalers = {}
self.models = {}
self.feature_importance = {}
self.training_data = None
def create_feature_matrix(
self,
thermal_results: Dict[str, 'ThermalToleranceResult'],
symbiont_results: Dict[Tuple[str, str], 'CompatibilityResult'],
disease_results: Dict[str, Dict[str, 'DiseaseResistanceResult']],
genomic_profiles: Dict[str, 'GenomicProfile'],
microbiome_data: Optional[Dict[str, pd.DataFrame]] = None
) -> pd.DataFrame:
"""Create unified feature matrix from all assays"""
all_sample_ids = set(thermal_results.keys())
features = {}
for sample_id in all_sample_ids:
sample_features = {}
# Thermal tolerance features
if sample_id in thermal_results:
tr = thermal_results[sample_id]
sample_features.update({
'thermal_ed50': tr.ed50_temp,
'thermal_ctmax': tr.critical_thermal_max,
'thermal_bleaching_threshold': tr.bleaching_threshold,
'thermal_recovery': tr.recovery_potential,
'thermal_hsr': tr.heat_shock_response_magnitude,
'thermal_index': tr.thermal_tolerance_index
})
# Disease resistance features (average across pathogens)
if sample_id in disease_results:
dr_values = list(disease_results[sample_id].values())
sample_features.update({
'disease_ld50': np.mean([d.ld50_dose for d in dr_values]),
'disease_survival': np.mean([d.survival_rate for d in dr_values]),
'disease_progression': np.mean([d.disease_progression_rate for d in dr_values]),
'disease_immune': np.mean([d.immune_response_magnitude for d in dr_values]),
'disease_index': np.mean([d.resistance_index for d in dr_values])
})
# Symbiont compatibility features
symbiont_matches = [r for (h, s), r in symbiont_results.items() if h == sample_id]
if symbiont_matches:
sample_features.update({
'symbiont_colonization': np.mean([s.colonization_success for s in symbiont_matches]),
'symbiont_growth_benefit': np.mean([s.growth_rate_benefit for s in symbiont_matches]),
'symbiont_protection': np.mean([s.stress_protection for s in symbiont_matches]),
'symbiont_carbon': np.mean([s.photosynthate_transfer for s in symbiont_matches]),
'symbiont_score': np.mean([s.compatibility_score for s in symbiont_matches])
})
# Genomic features
if sample_id in genomic_profiles:
gp = genomic_profiles[sample_id]
sample_features.update({
'genomic_thermal_alleles': sum(gp.thermal_tolerance_alleles.values()),
'genomic_disease_alleles': sum(gp.disease_resistance_alleles.values()),
'genomic_symbiont_alleles': sum(gp.symbiont_compatibility_alleles.values()),
'genomic_heterozygosity': gp.heterozygosity,
'genomic_adaptive_count': len(gp.adaptive_variants)
})
features[sample_id] = sample_features
# Convert to DataFrame
df = pd.DataFrame(features).T
# Add microbiome features if available
if microbiome_data:
for sample_id, mb_df in microbiome_data.items():
if sample_id in df.index:
# Alpha diversity
if 'alpha_diversity' in mb_df.columns:
df.loc[sample_id, 'microbiome_alpha'] = mb_df['alpha_diversity'].mean()
# Key taxa abundances
beneficial_taxa = ['Endozoicomonas', 'Candidatus_Amoebophilus', 'Alteromonas']
for taxa in beneficial_taxa:
if taxa in mb_df.columns:
df.loc[sample_id, f'mb_{taxa}'] = mb_df[taxa].mean()
return df.fillna(0)
def train_resilience_model(
self,
feature_matrix: pd.DataFrame,
phenotype_labels: pd.Series,
model_type: str = 'ensemble'
) -> Dict:
"""Train model to predict climate resilience"""
# Standardize features
scaler = StandardScaler()
X_scaled = scaler.fit_transform(feature_matrix)
self.scalers['resilience'] = scaler
# Feature selection
selector = SelectKBest(f_regression, k=min(20, feature_matrix.shape[1]))
X_selected = selector.fit_transform(X_scaled, phenotype_labels)
selected_features = feature_matrix.columns[selector.get_support()]
# Train model
if model_type == 'ensemble':
# Random Forest + Gradient Boosting ensemble
rf = RandomForestRegressor(
n_estimators=200,
max_depth=10,
min_samples_split=5,
random_state=42
)
gb = GradientBoostingRegressor(
n_estimators=150,
max_depth=6,
learning_rate=0.1,
random_state=42
)
rf_scores = cross_val_score(rf, X_selected, phenotype_labels, cv=5, scoring='r2')
gb_scores = cross_val_score(gb, X_selected, phenotype_labels, cv=5, scoring='r2')
rf.fit(X_selected, phenotype_labels)
gb.fit(X_selected, phenotype_labels)
self.models['rf'] = rf
self.models['gb'] = gb
# Feature importance
rf_importance = pd.Series(rf.feature_importances_, index=selected_features)
gb_importance = pd.Series(gb.feature_importances_, index=selected_features)
self.feature_importance = {
'rf': rf_importance.sort_values(ascending=False),
'gb': gb_importance.sort_values(ascending=False)
}
return {
'rf_cv_r2': rf_scores.mean(),
'gb_cv_r2': gb_scores.mean(),
'selected_features': list(selected_features)
}
return {}
def predict_resilience(
self,
sample_id: str,
feature_matrix: pd.DataFrame
) -> ClimateResilienceScore:
"""Predict climate resilience score for a sample"""
if sample_id not in feature_matrix.index:
raise ValueError(f"Sample {sample_id} not in feature matrix")
X = feature_matrix.loc[[sample_id]]
# Scale features
if 'resilience' in self.scalers:
X_scaled = self.scalers['resilience'].transform(X)
else:
X_scaled = X.values
# Get component scores
thermal_cols = [c for c in X.columns if c.startswith('thermal_')]
disease_cols = [c for c in X.columns if c.startswith('disease_')]
symbiont_cols = [c for c in X.columns if c.startswith('symbiont_')]
genomic_cols = [c for c in X.columns if c.startswith('genomic_')]
thermal_component = X[thermal_cols].mean().mean() if thermal_cols else 0
disease_component = X[disease_cols].mean().mean() if disease_cols else 0
symbiont_component = X[symbiont_cols].mean().mean() if symbiont_cols else 0
genomic_component = X[genomic_cols].mean().mean() if genomic_cols else 0
# Ensemble prediction
if 'rf' in self.models and 'gb' in self.models:
rf_pred = self.models['rf'].predict(X_scaled)[0]
gb_pred = self.models['gb'].predict(X_scaled)[0]
overall_score = (rf_pred + gb_pred) / 2
else:
# Fallback to weighted average of components
weights = {'thermal': 0.35, 'disease': 0.25, 'symbiont': 0.25, 'genomic': 0.15}
overall_score = (
weights['thermal'] * thermal_component +
weights['disease'] * disease_component +
weights['symbiont'] * symbiont_component +
weights['genomic'] * genomic_component
)
# Calculate confidence interval (simplified)
std_error = 5.0 # Assumed standard error
ci = (max(overall_score - 1.96*std_error, 0),
min(overall_score + 1.96*std_error, 100))
# Generate recommendations
recommendations = self._generate_recommendations(
thermal_component, disease_component, symbiont_component, genomic_component
)
return ClimateResilienceScore(
sample_id=sample_id,
overall_score=round(overall_score, 2),
thermal_component=round(thermal_component, 2),
disease_component=round(disease_component, 2),
symbiont_component=round(symbiont_component, 2),
genomic_component=round(genomic_component, 2),
confidence_interval=(round(ci[0], 2), round(ci[1], 2)),
priority_rank=0, # Will be set after ranking all samples
recommendations=recommendations
)
def _generate_recommendations(
self,
thermal: float,
disease: float,
symbiont: float,
genomic: float
) -> List[str]:
"""Generate recommendations based on component scores"""
recommendations = []
if thermal < 50:
recommendations.append("Consider thermal conditioning before outplanting to warm sites")
recommendations.append("Inoculate with Durusdinium spp. for enhanced thermal protection")
if disease < 50:
recommendations.append("Screen for beneficial microbiome inoculation")
recommendations.append("Avoid sites with high pathogen loads")
if symbiont < 50:
recommendations.append("Test alternative symbiont partnerships")
recommendations.append("Consider Cladocopium C15 for balanced performance")
if genomic < 50:
recommendations.append("Consider cross-breeding with high-performing genotypes")
recommendations.append("Prioritize genetic rescue approaches")
if thermal > 70 and disease > 70:
recommendations.append("High priority candidate for assisted gene flow")
recommendations.append("Suitable for warming reef restoration sites")
if not recommendations:
recommendations.append("Genotype shows balanced resilience profile")
return recommendations
def rank_samples(
self,
scores: Dict[str, ClimateResilienceScore]
) -> Dict[str, ClimateResilienceScore]:
"""Rank samples by climate resilience score"""
sorted_samples = sorted(
scores.items(),
key=lambda x: x[1].overall_score,
reverse=True
)
ranked_scores = {}
for rank, (sample_id, score) in enumerate(sorted_samples, 1):
score.priority_rank = rank
ranked_scores[sample_id] = score
return ranked_scores
def identify_top_performers(
self,
scores: Dict[str, ClimateResilienceScore],
percentile_threshold: float = 90.0
) -> List[str]:
"""Identify top performing genotypes above percentile threshold"""
all_scores = [s.overall_score for s in scores.values()]
threshold = np.percentile(all_scores, percentile_threshold)
return [sid for sid, s in scores.items() if s.overall_score >= threshold]
def generate_feature_importance_report(self, output_path: str):
"""Generate report on feature importance"""
if not self.feature_importance:
return
with open(output_path, 'w') as f:
f.write("# Feature Importance Report\n\n")
f.write("## Random Forest Feature Importance\n")
f.write(self.feature_importance['rf'].to_markdown())
f.write("\n\n")
f.write("## Gradient Boosting Feature Importance\n")
f.write(self.feature_importance['gb'].to_markdown())
f.write("\n")
8. Main Pipeline Orchestrator
# coral_screening_pipeline/pipeline.py
import asyncio
from pathlib import Path
from typing import List, Dict, Optional
from datetime import datetime
import json
import pandas as pd
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class CoralScreeningPipeline:
"""Main pipeline orchestrator for climate-resilient coral screening"""
def __init__(self, config: 'PipelineConfig'):
self.config = config
self.output_dir = Path(config.output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
# Initialize modules
from coral_screening_pipeline.thermal_assay import ThermalToleranceAssay
from coral_screening_pipeline.symbiont_assay import SymbiontCompatibilityAssay
from coral_screening_pipeline.disease_assay import DiseaseResistanceAssay
from coral_screening_pipeline.genomic_analysis import GenomicAnalyzer
from coral_screening_pipeline.integration import MultiomicsIntegrator
self.thermal_assay = ThermalToleranceAssay(config.thermal)
self.symbiont_assay = SymbiontCompatibilityAssay(config.symbiont)
self.disease_assay = DiseaseResistanceAssay(config.disease)
self.genomic_analyzer = GenomicAnalyzer(config.reference_genome)
self.integrator = MultiomicsIntegrator()
# Results storage
self.thermal_results: Dict[str, 'ThermalToleranceResult'] = {}
self.symbiont_results: Dict[Tuple[str, str], 'CompatibilityResult'] = {}
self.disease_results: Dict[str, Dict[str, 'DiseaseResistanceResult']] = {}
self.genomic_profiles: Dict[str, 'GenomicProfile'] = {}
self.resilience_scores: Dict[str, 'ClimateResilienceScore'] = {}
async def run_pipeline(
self,
sample_ids: List[str],
run_thermal: bool = True,
run_symbiont: bool = True,
run_disease: bool = True,
run_genomic: bool = True
) -> Dict[str, 'ClimateResilienceScore']:
"""Run complete screening pipeline"""
logger.info(f"Starting coral screening pipeline for {len(sample_ids)} samples")
start_time = datetime.now()
# Create results directory
run_dir = self.output_dir / f"run_{start_time.strftime('%Y%m%d_%H%M%S')}"
run_dir.mkdir(exist_ok=True)
# Run assays in parallel where possible
tasks = []
if run_thermal:
tasks.append(self._run_thermal_screening(sample_ids, run_dir))
if run_symbiont:
tasks.append(self._run_symbiont_screening(sample_ids, run_dir))
if run_disease:
tasks.append(self._run_disease_screening(sample_ids, run_dir))
if run_genomic:
tasks.append(self._run_genomic_analysis(sample_ids, run_dir))
await asyncio.gather(*tasks)
# Integrate results
logger.info("Integrating multi-omics data...")
feature_matrix = self.integrator.create_feature_matrix(
self.thermal_results,
self.symbiont_results,
self.disease_results,
self.genomic_profiles
)
# Save feature matrix
feature_matrix.to_csv(run_dir / "feature_matrix.csv")
# Calculate resilience scores
logger.info("Calculating climate resilience scores...")
for sample_id in sample_ids:
try:
score = self.integrator.predict_resilience(sample_id, feature_matrix)
self.resilience_scores[sample_id] = score
except Exception as e:
logger.warning(f"Could not calculate score for {sample_id}: {e}")
# Rank samples
self.resilience_scores = self.integrator.rank_samples(self.resilience_scores)
# Generate reports
self._generate_reports(run_dir)
# Save results
self._save_results(run_dir)
end_time = datetime.now()
duration = (end_time - start_time).total_seconds() / 60
logger.info(f"Pipeline completed in {duration:.1f} minutes")
return self.resilience_scores
async def _run_thermal_screening(self, sample_ids: List[str], run_dir: Path):
"""Run thermal tolerance screening"""
logger.info("Running thermal tolerance screening...")
thermal_dir = run_dir / "thermal_assay"
thermal_dir.mkdir(exist_ok=True)
for sample_id in sample_ids:
try:
# Analyze thermal data
result = self.thermal_assay.analyze_sample(sample_id)
self.thermal_results[sample_id] = result
# Generate individual report
self.thermal_assay.generate_thermal_profile_plot(
sample_id,
str(thermal_dir / f"{sample_id}_thermal_profile.png")
)
except Exception as e:
logger.warning(f"Thermal analysis failed for {sample_id}: {e}")
async def _run_symbiont_screening(self, sample_ids: List[str], run_dir: Path):
"""Run symbiont compatibility screening"""
logger.info("Running symbiont compatibility screening...")
symbiont_dir = run_dir / "symbiont_assay"
symbiont_dir.mkdir(exist_ok=True)
# Get symbiont cultures (would normally be loaded from database)
symbiont_cultures = [f"{g}_strain1" for g in self.config.symbiont.target_genera]
# Run cross-inoculation screen
self.symbiont_results = self.symbiont_assay.run_cross_inoculation_screen(
sample_ids, symbiont_cultures
)
async def _run_disease_screening(self, sample_ids: List[str], run_dir: Path):
"""Run disease resistance screening"""
logger.info("Running disease resistance screening...")
disease_dir = run_dir / "disease_assay"
disease_dir.mkdir(exist_ok=True)
for pathogen in self.config.disease.pathogens:
for sample_id in sample_ids:
try:
result = self.disease_assay.analyze_sample(sample_id, pathogen)
if sample_id not in self.disease_results:
self.disease_results[sample_id] = {}
self.disease_results[sample_id][pathogen] = result
except Exception as e:
logger.warning(f"Disease analysis failed for {sample_id}/{pathogen}: {e}")
# Generate survival curves
self.disease_assay.generate_survival_plot(
sample_ids,
self.config.disease.pathogens[0],
str(disease_dir / "survival_curves.png")
)
async def _run_genomic_analysis(self, sample_ids: List[str], run_dir: Path):
"""Run genomic analysis"""
logger.info("Running genomic analysis...")
genomic_dir = run_dir / "genomic_analysis"
genomic_dir.mkdir(exist_ok=True)
# Build genotype matrix
vcf_dir = Path("data/vcf")
for sample_id in sample_ids:
vcf_path = vcf_dir / f"{sample_id}.vcf"
if vcf_path.exists():
self.genomic_analyzer.load_vcf(sample_id, str(vcf_path))
# Create profiles
for sample_id in sample_ids:
if sample_id in self.genomic_analyzer.variant_data:
profile = self.genomic_analyzer.create_genomic_profile(sample_id)
self.genomic_profiles[sample_id] = profile
def _generate_reports(self, run_dir: Path):
"""Generate analysis reports"""
reports_dir = run_dir / "reports"
reports_dir.mkdir(exist_ok=True)
# Top performers report
top_performers = self.integrator.identify_top_performers(
self.resilience_scores, percentile_threshold=90
)
with open(reports_dir / "top_performers.txt", 'w') as f:
f.write("# Top Performing Coral Genotypes\n\n")
f.write(f"Generated: {datetime.now().isoformat()}\n\n")
for sample_id in top_performers:
score = self.resilience_scores[sample_id]
f.write(f"## Rank {score.priority_rank}: {sample_id}\n")
f.write(f"Overall Score: {score.overall_score}\n")
f.write(f"95% CI: [{score.confidence_interval[0]}, {score.confidence_interval[1]}]\n\n")
f.write("Component Scores:\n")
f.write(f" - Thermal: {score.thermal_component}\n")
f.write(f" - Disease: {score.disease_component}\n")
f.write(f" - Symbiont: {score.symbiont_component}\n")
f.write(f" - Genomic: {score.genomic_component}\n\n")
f.write("Recommendations:\n")
for rec in score.recommendations:
f.write(f" - {rec}\n")
f.write("\n" + "="*50 + "\n\n")
# Feature importance report
self.integrator.generate_feature_importance_report(
str(reports_dir / "feature_importance.md")
)
# Summary statistics
self._generate_summary_stats(reports_dir)
def _generate_summary_stats(self, reports_dir: Path):
"""Generate summary statistics"""
if not self.resilience_scores:
return
scores_df = pd.DataFrame([
{
'sample_id': sid,
'overall_score': s.overall_score,
'thermal': s.thermal_component,
'disease': s.disease_component,
'symbiont': s.symbiont_component,
'genomic': s.genomic_component,
'rank': s.priority_rank
}
for sid, s in self.resilience_scores.items()
])
summary = scores_df.describe()
summary.to_csv(reports_dir / "summary_statistics.csv")
# Distribution plots
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Overall score distribution
axes[0, 0].hist(scores_df['overall_score'], bins=20, edgecolor='black')
axes[0, 0].set_xlabel('Climate Resilience Score')
axes[0, 0].set_ylabel('Count')
axes[0, 0].set_title('Distribution of Overall Scores')
# Component correlations
components = ['thermal', 'disease', 'symbiont', 'genomic']
corr_matrix = scores_df[components].corr()
im = axes[0, 1].imshow(corr_matrix, cmap='coolwarm', vmin=-1, vmax=1)
axes[0, 1].set_xticks(range(len(components)))
axes[0, 1].set_yticks(range(len(components)))
axes[0, 1].set_xticklabels(components, rotation=45)
axes[0, 1].set_yticklabels(components)
axes[0, 1].set_title('Component Correlations')
plt.colorbar(im, ax=axes[0, 1])
# Top 20 scores
top20 = scores_df.nsmallest(20, 'rank')
axes[1, 0].barh(range(len(top20)), top20['overall_score'])
axes[1, 0].set_yticks(range(len(top20)))
axes[1, 0].set_yticklabels(top20['sample_id'], fontsize=8)
axes[1, 0].set_xlabel('Climate Resilience Score')
axes[1, 0].set_title('Top 20 Genotypes')
axes[1, 0].invert_yaxis()
# Component balance for top performers
top10 = scores_df.nsmallest(10, 'rank')
x = range(len(top10))
width = 0.2
axes[1, 1].bar([i - 1.5*width for i in x], top10['thermal'], width, label='Thermal')
axes[1, 1].bar([i - 0.5*width for i in x], top10['disease'], width, label='Disease')
axes[1, 1].bar([i + 0.5*width for i in x], top10['symbiont'], width, label='Symbiont')
axes[1, 1].bar([i + 1.5*width for i in x], top10['genomic'], width, label='Genomic')
axes[1, 1].set_xticks(x)
axes[1, 1].set_xticklabels(top10['sample_id'], rotation=45, ha='right', fontsize=8)
axes[1, 1].set_ylabel('Component Score')
axes[1, 1].set_title('Component Balance - Top 10')
axes[1, 1].legend()
plt.tight_layout()
plt.savefig(reports_dir / "summary_plots.png", dpi=300)
plt.close()
def _save_results(self, run_dir: Path):
"""Save all results to files"""
# Thermal results
thermal_df = pd.DataFrame([
{
'sample_id': sid,
'ed50_temp': r.ed50_temp,
'ctmax': r.critical_thermal_max,
'bleaching_threshold': r.bleaching_threshold,
'recovery_potential': r.recovery_potential,
'thermal_index': r.thermal_tolerance_index
}
for sid, r in self.thermal_results.items()
])
thermal_df.to_csv(run_dir / "thermal_results.csv", index=False)
# Symbiont results
symbiont_df = pd.DataFrame([
{
'host_id': host_id,
'symbiont_id': symbiont_id,
'colonization': r.colonization_success,
'growth_benefit': r.growth_rate_benefit,
'stress_protection': r.stress_protection,
'carbon_transfer': r.photosynthate_transfer,
'compatibility_score': r.compatibility_score
}
for (host_id, symbiont_id), r in self.symbiont_results.items()
])
symbiont_df.to_csv(run_dir / "symbiont_results.csv", index=False)
# Disease results
disease_records = []
for sample_id, pathogens in self.disease_results.items():
for pathogen, r in pathogens.items():
disease_records.append({
'sample_id': sample_id,
'pathogen': pathogen,
'ld50': r.ld50_dose,
'survival_rate': r.survival_rate,
'progression_rate': r.disease_progression_rate,
'immune_response': r.immune_response_magnitude,
'resistance_index': r.resistance_index
})
disease_df = pd.DataFrame(disease_records)
disease_df.to_csv(run_dir / "disease_results.csv", index=False)
# Final resilience scores
scores_df = pd.DataFrame([
{
'sample_id': sid,
'overall_score': s.overall_score,
'thermal_component': s.thermal_component,
'disease_component': s.disease_component,
'symbiont_component': s.symbiont_component,
'genomic_component': s.genomic_component,
'ci_lower': s.confidence_interval[0],
'ci_upper': s.confidence_interval[1],
'rank': s.priority_rank,
'recommendations': '; '.join(s.recommendations)
}
for sid, s in self.resilience_scores.items()
])
scores_df.to_csv(run_dir / "final_resilience_scores.csv", index=False)
logger.info(f"Results saved to {run_dir}")
# Main execution
async def main():
from coral_screening_pipeline.config import PipelineConfig
from coral_screening_pipeline.sample_management import SampleRegistry, CoralSample
from datetime import datetime
# Load configuration
config = PipelineConfig(
output_dir="results/coral_screening",
reference_genome="references/stylophora_pistillata_v2.fasta"
)
# Initialize pipeline
pipeline = CoralScreeningPipeline(config)
# Define samples (normally loaded from registry)
sample_ids = [f"COR_20240115_{i:04d}" for i in range(1, 97)] # 96-well plate
# Run pipeline
results = await pipeline.run_pipeline(
sample_ids,
run_thermal=True,
run_symbiont=True,
run_disease=True,
run_genomic=True
)
# Print top performers
print("\n=== TOP 10 CLIMATE-RESILIENT CORAL GENOTYPES ===\n")
for sample_id, score in sorted(results.items(), key=lambda x: x[1].priority_rank)[:10]:
print(f"Rank {score.priority_rank}: {sample_id}")
print(f" Overall Score: {score.overall_score}")
print(f" Components: T={score.thermal_component:.1f} D={score.disease_component:.1f} "
f"S={score.symbiont_component:.1f} G={score.genomic_component:.1f}")
print(f" Top Recommendation: {score.recommendations[0] if score.recommendations else 'N/A'}")
print()
if __name__ == "__main__":
asyncio.run(main())
9. Data Quality Control Module
# coral_screening_pipeline/qc.py
import numpy as np
import pandas as pd
from dataclasses import dataclass
from typing import List, Dict, Tuple, Optional
from pathlib import Path
@dataclass
class QCResult:
"""Quality control result"""
sample_id: str
assay_type: str
passed: bool
metrics: Dict[str, float]
warnings: List[str]
failures: List[str]
class QualityControl:
"""Quality control for screening data"""
# QC thresholds
THRESHOLDS = {
'thermal': {
'min_fv_fm': 0.4,
'max_bleaching_score': 5,
'min_replicates': 2,
'max_cv': 0.3
},
'genomic': {
'min_coverage': 20,
'min_mapping_rate': 0.8,
'max_duplicate_rate': 0.2,
'min_call_rate': 0.9
},
'rna_seq': {
'min_reads': 10_000_000,
'min_mapping_rate': 0.7,
'max_rrna_fraction': 0.3,
'min_genes_detected': 5000
},
'amplicon': {
'min_reads': 50000,
'min_asv_count': 100,
'max_singleton_fraction': 0.1
}
}
def __init__(self):
self.results: Dict[str, List[QCResult]] = {}
def check_thermal_assay(
self,
sample_id: str,
metrics: List['ThermalMetrics']
) -> QCResult:
"""QC for thermal tolerance assay data"""
thresholds = self.THRESHOLDS['thermal']
warnings = []
failures = []
# Check Fv/Fm values
fv_fm_values = [m.fv_fm for m in metrics]
if min(fv_fm_values) < thresholds['min_fv_fm']:
failures.append(f"Fv/Fm below threshold: {min(fv_fm_values):.3f}")
# Check coefficient of variation
cv = np.std(fv_fm_values) / np.mean(fv_fm_values)
if cv > thresholds['max_cv']:
warnings.append(f"High variability (CV={cv:.2f})")
# Check temperature progression
temps = sorted(set(m.temperature_c for m in metrics))
if len(temps) < 4:
warnings.append(f"Only {len(temps)} temperature points measured")
passed = len(failures) == 0
result = QCResult(
sample_id=sample_id,
assay_type='thermal',
passed=passed,
metrics={'cv': cv, 'min_fv_fm': min(fv_fm_values)},
warnings=warnings,
failures=failures
)
if sample_id not in self.results:
self.results[sample_id] = []
self.results[sample_id].append(result)
return result
def check_genomic_data(
self,
sample_id: str,
coverage_stats: Dict[str, float]
) -> QCResult:
"""QC for genomic sequencing data"""
thresholds = self.THRESHOLDS['genomic']
warnings = []
failures = []
# Check coverage
if coverage_stats.get('mean_coverage', 0) < thresholds['min_coverage']:
failures.append(f"Low coverage: {coverage_stats.get('mean_coverage', 0):.1f}X")
# Check mapping rate
if coverage_stats.get('mapping_rate', 0) < thresholds['min_mapping_rate']:
failures.append(f"Low mapping rate: {coverage_stats.get('mapping_rate', 0):.2%}")
# Check duplicate rate
if coverage_stats.get('duplicate_rate', 0) > thresholds['max_duplicate_rate']:
warnings.append(f"High duplicate rate: {coverage_stats.get('duplicate_rate', 0):.2%}")
# Check variant call rate
if coverage_stats.get('call_rate', 0) < thresholds['min_call_rate']:
warnings.append(f"Low call rate: {coverage_stats.get('call_rate', 0):.2%}")
passed = len(failures) == 0
result = QCResult(
sample_id=sample_id,
assay_type='genomic',
passed=passed,
metrics=coverage_stats,
warnings=warnings,
failures=failures
)
if sample_id not in self.results:
self.results[sample_id] = []
self.results[sample_id].append(result)
return result
def check_rna_seq(
self,
sample_id: str,
alignment_stats: Dict[str, float]
) -> QCResult:
"""QC for RNA-seq data"""
thresholds = self.THRESHOLDS['rna_seq']
warnings = []
failures = []
# Check read count
if alignment_stats.get('total_reads', 0) < thresholds['min_reads']:
failures.append(f"Low read count: {alignment_stats.get('total_reads', 0):,}")
# Check mapping rate
if alignment_stats.get('mapping_rate', 0) < thresholds['min_mapping_rate']:
failures.append(f"Low mapping rate: {alignment_stats.get('mapping_rate', 0):.2%}")
# Check rRNA fraction
if alignment_stats.get('rrna_fraction', 0) > thresholds['max_rrna_fraction']:
warnings.append(f"High rRNA fraction: {alignment_stats.get('rrma_fraction', 0):.2%}")
# Check genes detected
if alignment_stats.get('genes_detected', 0) < thresholds['min_genes_detected']:
warnings.append(f"Low gene count: {alignment_stats.get('genes_detected', 0):,}")
passed = len(failures) == 0
result = QCResult(
sample_id=sample_id,
assay_type='rna_seq',
passed=passed,
metrics=alignment_stats,
warnings=warnings,
failures=failures
)
if sample_id not in self.results:
self.results[sample_id] = []
self.results[sample_id].append(result)
return result
def generate_qc_report(self, output_path: str):
"""Generate comprehensive QC report"""
total_samples = len(self.results)
assay_stats = {}
for sample_id, results in self.results.items():
for result in results:
assay = result.assay_type
if assay not in assay_stats:
assay_stats[assay] = {'passed': 0, 'failed': 0, 'warnings': 0}
if result.passed:
assay_stats[assay]['passed'] += 1
else:
assay_stats[assay]['failed'] += 1
if result.warnings:
assay_stats[assay]['warnings'] += 1
with open(output_path, 'w') as f:
f.write("# Quality Control Report\n\n")
f.write(f"Total Samples: {total_samples}\n\n")
f.write("## Assay Summary\n\n")
f.write("| Assay | Passed | Failed | Warnings |\n")
f.write("|-------|--------|--------|----------|\n")
for assay, stats in assay_stats.items():
f.write(f"| {assay} | {stats['passed']} | {stats['failed']} | {stats['warnings']} |\n")
f.write("\n## Failed Samples\n\n")
for sample_id, results in self.results.items():
for result in results:
if not result.passed:
f.write(f"### {sample_id} - {result.assay_type}\n")
for failure in result.failures:
f.write(f"- FAIL: {failure}\n")
f.write("\n")
return assay_stats
def get_passing_samples(self) -> List[str]:
"""Get list of samples that passed all QC checks"""
passing = []
for sample_id, results in self.results.items():
if all(r.passed for r in results):
passing.append(sample_id)
return passing
Summary
This comprehensive pipeline provides:
-
Thermal Tolerance Screening: ED50 calculation, critical thermal maximum, bleaching thresholds, heat shock response quantification
-
Symbiont Compatibility: Cross-inoculation matrices, ITS2 metabarcoding analysis, colonization success, photosynthate transfer metrics
-
Disease Resistance: Multi-pathogen challenge assays, LD50 calculations, survival analysis, immune response profiling
-
Genomic Analysis: Variant calling, adaptive allele identification, heterozygosity assessment, population assignment
-
Multi-omics Integration: Machine learning ensemble models, feature importance analysis, composite resilience scoring
-
Quality Control: Automated QC checks for all data types, comprehensive reporting
The pipeline is designed for:
- High throughput: 96-well plate format with automated analysis
- Scalability: Async execution for parallel processing
- Reproducibility: Version-controlled configuration and standardized workflows
- Actionable outputs: Ranked candidate lists with specific recommendations for restoration