RBCeq2 2.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rbceq2/IO/PDF_reports.py +540 -0
- rbceq2/IO/__init__.py +0 -0
- rbceq2/IO/record_data.py +114 -0
- rbceq2/IO/validation.py +132 -0
- rbceq2/IO/vcf.py +363 -0
- rbceq2/__init__.py +0 -0
- rbceq2/core_logic/__init__.py +0 -0
- rbceq2/core_logic/alleles.py +516 -0
- rbceq2/core_logic/co_existing.py +654 -0
- rbceq2/core_logic/constants.py +343 -0
- rbceq2/core_logic/data_procesing.py +999 -0
- rbceq2/core_logic/utils.py +314 -0
- rbceq2/db/__init__.py +0 -0
- rbceq2/db/db.py +282 -0
- rbceq2/filters/__init__.py +0 -0
- rbceq2/filters/geno.py +1234 -0
- rbceq2/main.py +332 -0
- rbceq2/phenotype/__init__.py +0 -0
- rbceq2/phenotype/antigens.py +455 -0
- rbceq2/phenotype/choose_pheno.py +1145 -0
- rbceq2/resources/db.tsv +1869 -0
- rbceq2-2.1.0.dist-info/METADATA +141 -0
- rbceq2-2.1.0.dist-info/RECORD +27 -0
- rbceq2-2.1.0.dist-info/WHEEL +5 -0
- rbceq2-2.1.0.dist-info/entry_points.txt +2 -0
- rbceq2-2.1.0.dist-info/licenses/LICENSE +7 -0
- rbceq2-2.1.0.dist-info/top_level.txt +1 -0
rbceq2/IO/PDF_reports.py
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List, Optional, Set, Tuple
|
|
6
|
+
|
|
7
|
+
import pandas as pd
|
|
8
|
+
from loguru import logger
|
|
9
|
+
from reportlab.lib import colors
|
|
10
|
+
from reportlab.lib.pagesizes import letter
|
|
11
|
+
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
|
|
12
|
+
from reportlab.lib.units import inch
|
|
13
|
+
from reportlab.pdfgen import canvas
|
|
14
|
+
from reportlab.platypus import (
|
|
15
|
+
BaseDocTemplate,
|
|
16
|
+
Flowable,
|
|
17
|
+
Frame,
|
|
18
|
+
PageTemplate,
|
|
19
|
+
Paragraph,
|
|
20
|
+
Spacer,
|
|
21
|
+
Table,
|
|
22
|
+
TableStyle,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
from rbceq2.core_logic.constants import DB_VERSION, VERSION
|
|
26
|
+
|
|
27
|
+
# --- Helper Functions ---
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _normalize_sample_id(sample_id: str) -> str:
|
|
31
|
+
"""Removes common suffixes from sample IDs for consistent matching.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
sample_id: The original sample identifier string.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
The normalized sample identifier string.
|
|
38
|
+
"""
|
|
39
|
+
# Ensure input is string before regex
|
|
40
|
+
sample_id_str = str(sample_id)
|
|
41
|
+
# Remove the common long suffix first, including optional .vcf
|
|
42
|
+
normalized = re.sub(
|
|
43
|
+
r"_GRCh38_1_22_v4\.2\.1_benchmark_filtered(\.vcf)?$", "", sample_id_str
|
|
44
|
+
)
|
|
45
|
+
# Example: remove just .vcf if the long suffix wasn't present
|
|
46
|
+
normalized = re.sub(r"\.vcf$", "", normalized)
|
|
47
|
+
# Add any other normalization rules here if needed
|
|
48
|
+
return normalized
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _format_cell_content(text: Optional[Any], separator: Optional[str] = None) -> str:
|
|
52
|
+
"""Formats cell text for PDF tables, handling N/A, line breaks, and HTML escaping.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
text: The content of the cell (can be string, number, NaN, None).
|
|
56
|
+
separator: The character(s) used to split the text for line breaks (e.g., ',').
|
|
57
|
+
If None, no splitting occurs, only escaping and N/A handling.
|
|
58
|
+
|
|
59
|
+
Returns:
|
|
60
|
+
A string formatted for use in a ReportLab Paragraph, with <br/> for line breaks
|
|
61
|
+
and escaped HTML characters, or "N/A" if the input is missing/empty.
|
|
62
|
+
"""
|
|
63
|
+
if pd.isna(text) or text == "" or text is None:
|
|
64
|
+
return "N/A"
|
|
65
|
+
|
|
66
|
+
text_str = str(text)
|
|
67
|
+
# Escape HTML special characters first to avoid breaking tags later
|
|
68
|
+
# Using standard library for robust escaping
|
|
69
|
+
import html
|
|
70
|
+
|
|
71
|
+
escaped_text = html.escape(text_str)
|
|
72
|
+
|
|
73
|
+
if separator:
|
|
74
|
+
# Split the original unescaped text by the separator
|
|
75
|
+
items = text_str.split(separator)
|
|
76
|
+
# Escape *each item* after splitting and strip whitespace
|
|
77
|
+
escaped_items = [html.escape(item.strip()) for item in items]
|
|
78
|
+
# Join the individually escaped items with <br/>
|
|
79
|
+
return "<br/>".join(escaped_items)
|
|
80
|
+
else:
|
|
81
|
+
# Return the fully escaped text if no separator provided
|
|
82
|
+
return escaped_text
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# --- Data Preparation ---
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _prepare_dataframes(
|
|
89
|
+
df_genotypes: Optional[pd.DataFrame],
|
|
90
|
+
df_pheno_alpha: Optional[pd.DataFrame],
|
|
91
|
+
df_pheno_num: Optional[pd.DataFrame],
|
|
92
|
+
) -> Tuple[Dict[str, Optional[pd.DataFrame]], Set[str], Dict[str, str]]:
|
|
93
|
+
"""Normalizes sample IDs in DataFrames and identifies unique samples.
|
|
94
|
+
|
|
95
|
+
Adds a 'SampleID_Normalized' column to each input DataFrame.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
df_genotypes: DataFrame with genotype data. Index should be SampleID.
|
|
99
|
+
df_pheno_alpha: DataFrame with alphanumeric phenotype data. Index should be SampleID.
|
|
100
|
+
df_pheno_num: DataFrame with numeric phenotype data. Index should be SampleID.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
A tuple containing:
|
|
104
|
+
- A dictionary mapping data type ('genotype', 'alpha', 'numeric') to the
|
|
105
|
+
corresponding DataFrame (or None if input was None/empty). DataFrames
|
|
106
|
+
will have the 'SampleID_Normalized' column added and index reset.
|
|
107
|
+
- A set of unique normalized sample IDs found across all DataFrames.
|
|
108
|
+
- A dictionary mapping normalized sample IDs to the first encountered
|
|
109
|
+
original sample ID.
|
|
110
|
+
"""
|
|
111
|
+
dfs = {"genotype": df_genotypes, "alpha": df_pheno_alpha, "numeric": df_pheno_num}
|
|
112
|
+
processed_dfs: Dict[str, Optional[pd.DataFrame]] = {}
|
|
113
|
+
original_id_map: Dict[str, str] = {} # Map normalized ID -> first original ID
|
|
114
|
+
all_normalized_ids: Set[str] = set()
|
|
115
|
+
|
|
116
|
+
for df_type, df in dfs.items():
|
|
117
|
+
if df is not None and not df.empty:
|
|
118
|
+
df_processed = df.copy()
|
|
119
|
+
original_ids = df_processed.index.astype(
|
|
120
|
+
str
|
|
121
|
+
).tolist() # Get original IDs before potentially changing index
|
|
122
|
+
df_processed["SampleID_Normalized"] = df_processed.index.map(
|
|
123
|
+
_normalize_sample_id
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
all_normalized_ids.update(df_processed["SampleID_Normalized"].unique())
|
|
127
|
+
|
|
128
|
+
# Store mapping: normalized -> original
|
|
129
|
+
for i, norm_id in enumerate(df_processed["SampleID_Normalized"]):
|
|
130
|
+
if norm_id not in original_id_map:
|
|
131
|
+
original_id_map[norm_id] = original_ids[
|
|
132
|
+
i
|
|
133
|
+
] # Map normalized to the first original ID encountered
|
|
134
|
+
|
|
135
|
+
processed_dfs[df_type] = df_processed
|
|
136
|
+
else:
|
|
137
|
+
processed_dfs[df_type] = None
|
|
138
|
+
|
|
139
|
+
return processed_dfs, all_normalized_ids, original_id_map
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# --- PDF Styling and Content Generation ---
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# def _setup_styles() -> Dict[str, ParagraphStyle]:
|
|
146
|
+
# """Creates and returns a dictionary of ReportLab ParagraphStyle objects.
|
|
147
|
+
|
|
148
|
+
# Returns:
|
|
149
|
+
# A dictionary mapping style names (e.g., 'body', 'title', 'warning')
|
|
150
|
+
# to their corresponding ParagraphStyle objects.
|
|
151
|
+
# """
|
|
152
|
+
# styles = getSampleStyleSheet()
|
|
153
|
+
# # Reduce body text size slightly for potentially better table fit
|
|
154
|
+
# body_style = ParagraphStyle(
|
|
155
|
+
# name="BodyTextSmall", parent=styles["BodyText"], fontSize=9
|
|
156
|
+
# )
|
|
157
|
+
# table_cell_style = ParagraphStyle(
|
|
158
|
+
# name="TableCell",
|
|
159
|
+
# parent=body_style,
|
|
160
|
+
# leading=11,
|
|
161
|
+
# fontSize=8, # Smaller font, tighter leading for cells
|
|
162
|
+
# )
|
|
163
|
+
# footer_style = ParagraphStyle(
|
|
164
|
+
# name="FooterStyle",
|
|
165
|
+
# parent=styles["Normal"],
|
|
166
|
+
# alignment=1,
|
|
167
|
+
# fontSize=7,
|
|
168
|
+
# textColor=colors.grey, # Centered footer
|
|
169
|
+
# )
|
|
170
|
+
|
|
171
|
+
# custom_styles = {
|
|
172
|
+
# "body": body_style,
|
|
173
|
+
# "heading": styles["h2"],
|
|
174
|
+
# "title": styles["h1"],
|
|
175
|
+
# "report_title": ParagraphStyle(
|
|
176
|
+
# name="ReportTitle",
|
|
177
|
+
# parent=styles["h1"],
|
|
178
|
+
# alignment=1,
|
|
179
|
+
# fontSize=16, # Centered H1
|
|
180
|
+
# ),
|
|
181
|
+
# "warning": ParagraphStyle(
|
|
182
|
+
# name="Warning",
|
|
183
|
+
# parent=styles["Heading1"],
|
|
184
|
+
# textColor=colors.red,
|
|
185
|
+
# alignment=1,
|
|
186
|
+
# fontSize=14,
|
|
187
|
+
# ),
|
|
188
|
+
# "table_header": ParagraphStyle(
|
|
189
|
+
# name="TableHeader",
|
|
190
|
+
# parent=styles["BodyText"],
|
|
191
|
+
# fontName="Helvetica-Bold",
|
|
192
|
+
# fontSize=8, # Smaller header
|
|
193
|
+
# ),
|
|
194
|
+
# "table_cell": table_cell_style,
|
|
195
|
+
# "footer": footer_style,
|
|
196
|
+
# }
|
|
197
|
+
# return custom_styles
|
|
198
|
+
|
|
199
|
+
def _setup_styles() -> Dict[str, ParagraphStyle]:
|
|
200
|
+
"""Creates and returns a dictionary of ReportLab ParagraphStyle objects.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
A dictionary mapping style names (e.g., 'body', 'title', 'warning')
|
|
204
|
+
to their corresponding ParagraphStyle objects.
|
|
205
|
+
"""
|
|
206
|
+
styles = getSampleStyleSheet()
|
|
207
|
+
body_style = ParagraphStyle(name='BodyTextSmall', parent=styles['BodyText'], fontSize=9)
|
|
208
|
+
|
|
209
|
+
table_cell_style = ParagraphStyle(
|
|
210
|
+
name="TableCell",
|
|
211
|
+
parent=body_style,
|
|
212
|
+
fontSize=7,
|
|
213
|
+
leading=9,
|
|
214
|
+
)
|
|
215
|
+
# ****************************************************************
|
|
216
|
+
|
|
217
|
+
footer_style = ParagraphStyle(
|
|
218
|
+
name='FooterStyle', parent=styles['Normal'], alignment=1, fontSize=7, textColor=colors.grey # Centered footer
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
custom_styles = {
|
|
222
|
+
"body": body_style,
|
|
223
|
+
"heading": styles["h2"],
|
|
224
|
+
"title": styles["h1"],
|
|
225
|
+
"report_title": ParagraphStyle(
|
|
226
|
+
name="ReportTitle", parent=styles["h1"], alignment=1, fontSize=16 # Centered H1
|
|
227
|
+
),
|
|
228
|
+
"warning": ParagraphStyle(
|
|
229
|
+
name="Warning", parent=styles["Heading1"], textColor=colors.red, alignment=1, fontSize=14
|
|
230
|
+
),
|
|
231
|
+
"table_header": ParagraphStyle(
|
|
232
|
+
# Keep header size reasonable or reduce slightly if needed too
|
|
233
|
+
name="TableHeader", parent=styles["BodyText"], fontName="Helvetica-Bold", fontSize=8
|
|
234
|
+
),
|
|
235
|
+
"table_cell": table_cell_style, # Use the modified style
|
|
236
|
+
"footer": footer_style,
|
|
237
|
+
}
|
|
238
|
+
return custom_styles
|
|
239
|
+
|
|
240
|
+
def _add_page_footer(
|
|
241
|
+
canvas: canvas.Canvas,
|
|
242
|
+
doc: BaseDocTemplate,
|
|
243
|
+
styles: Dict[str, ParagraphStyle],
|
|
244
|
+
UUID: str,
|
|
245
|
+
) -> None:
|
|
246
|
+
"""Draws the footer on each page."""
|
|
247
|
+
canvas.saveState()
|
|
248
|
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
|
249
|
+
footer_text = (
|
|
250
|
+
f"Generated: {timestamp} | Code: v{VERSION} | DB: {DB_VERSION} | UUID: {UUID}"
|
|
251
|
+
)
|
|
252
|
+
p = Paragraph(footer_text, styles["footer"])
|
|
253
|
+
w, h = p.wrap(doc.width, doc.bottomMargin) # Use doc.width available space
|
|
254
|
+
p.drawOn(
|
|
255
|
+
canvas, doc.leftMargin, doc.bottomMargin - h - 5
|
|
256
|
+
) # Position below bottom margin
|
|
257
|
+
canvas.restoreState()
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _create_report_header(
|
|
261
|
+
story: List[Flowable], original_id_display: str, styles: Dict[str, ParagraphStyle]
|
|
262
|
+
) -> None:
|
|
263
|
+
"""Adds standard header elements to the PDF story.
|
|
264
|
+
|
|
265
|
+
Args:
|
|
266
|
+
story: The list of ReportLab Flowables to append to.
|
|
267
|
+
original_id_display: The sample ID to display in the header.
|
|
268
|
+
styles: Dictionary containing the required ParagraphStyles.
|
|
269
|
+
"""
|
|
270
|
+
story.append(Paragraph("RBCeq2", styles["report_title"]))
|
|
271
|
+
story.append(Spacer(1, 0.1 * inch))
|
|
272
|
+
story.append(Paragraph("Not for clinical use", styles["warning"]))
|
|
273
|
+
story.append(Spacer(1, 0.2 * inch))
|
|
274
|
+
story.append(Paragraph(f"Sample ID: {original_id_display}", styles["heading"]))
|
|
275
|
+
story.append(Spacer(1, 0.1 * inch)) # Reduced space before table title
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _get_data_for_sample(
|
|
279
|
+
norm_id: str, processed_dfs: Dict[str, Optional[pd.DataFrame]]
|
|
280
|
+
) -> Tuple[Dict[str, Optional[pd.Series]], Set[str]]:
|
|
281
|
+
"""Retrieves data rows for a specific normalized sample ID from processed dfs.
|
|
282
|
+
|
|
283
|
+
Args:
|
|
284
|
+
norm_id: The normalized sample ID to retrieve data for.
|
|
285
|
+
processed_dfs: Dictionary mapping data type to processed DataFrame
|
|
286
|
+
(must contain 'SampleID_Normalized' column).
|
|
287
|
+
|
|
288
|
+
Returns:
|
|
289
|
+
A tuple containing:
|
|
290
|
+
- A dictionary mapping data type ('genotype', 'alpha', 'numeric')
|
|
291
|
+
to the pd.Series containing the sample's data (or None if not found).
|
|
292
|
+
The Series index will be the gene/system names.
|
|
293
|
+
- A set of all unique gene/system keys found for this sample across
|
|
294
|
+
all data types.
|
|
295
|
+
"""
|
|
296
|
+
sample_data: Dict[str, Optional[pd.Series]] = {}
|
|
297
|
+
all_keys_for_sample: Set[str] = set()
|
|
298
|
+
|
|
299
|
+
for df_type, df in processed_dfs.items():
|
|
300
|
+
row_data: Optional[pd.Series] = None
|
|
301
|
+
if df is not None:
|
|
302
|
+
# Find rows matching the normalized ID
|
|
303
|
+
matching_rows = df[df["SampleID_Normalized"] == norm_id]
|
|
304
|
+
if not matching_rows.empty:
|
|
305
|
+
# Select the first match (assuming one row per normalized ID per df type)
|
|
306
|
+
# Drop the helper column to get only gene/system data
|
|
307
|
+
row_data = matching_rows.iloc[0].drop(
|
|
308
|
+
"SampleID_Normalized", errors="ignore"
|
|
309
|
+
) # Ignore error if column somehow missing
|
|
310
|
+
all_keys_for_sample.update(row_data.index)
|
|
311
|
+
|
|
312
|
+
sample_data[df_type] = row_data
|
|
313
|
+
|
|
314
|
+
return sample_data, all_keys_for_sample
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _create_consolidated_table(
|
|
318
|
+
sample_data: Dict[str, Optional[pd.Series]],
|
|
319
|
+
all_keys_for_sample: Set[str],
|
|
320
|
+
styles: Dict[str, ParagraphStyle],
|
|
321
|
+
) -> Flowable:
|
|
322
|
+
"""Creates the main data table combining genotype and phenotypes.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
sample_data: Dict mapping data type to the sample's data Series.
|
|
326
|
+
all_keys_for_sample: Set of all gene/system keys for this sample.
|
|
327
|
+
styles: Dictionary containing the required ParagraphStyles.
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
A ReportLab Table object or a Paragraph indicating no data.
|
|
331
|
+
"""
|
|
332
|
+
if not all_keys_for_sample:
|
|
333
|
+
return Paragraph("No data available for this sample.", styles["body"])
|
|
334
|
+
|
|
335
|
+
# Prepare table header row
|
|
336
|
+
header_content = ["System/Gene", "Genotype", "Phenotype (Alpha)", "Phenotype (Num)"]
|
|
337
|
+
# Wrap header text in Paragraphs using the header style
|
|
338
|
+
header_row: List[Paragraph] = [
|
|
339
|
+
Paragraph(text, styles["table_header"]) for text in header_content
|
|
340
|
+
]
|
|
341
|
+
combined_table_data: List[List[Flowable]] = [header_row]
|
|
342
|
+
|
|
343
|
+
# Sort keys alphabetically for consistent row order
|
|
344
|
+
sorted_keys = sorted(list(all_keys_for_sample))
|
|
345
|
+
|
|
346
|
+
for key in sorted_keys:
|
|
347
|
+
# Safely get data using .get(key, default_value) for robustness
|
|
348
|
+
geno_val = (
|
|
349
|
+
sample_data["genotype"].get(key, None)
|
|
350
|
+
if sample_data["genotype"] is not None
|
|
351
|
+
else None
|
|
352
|
+
)
|
|
353
|
+
alpha_val = (
|
|
354
|
+
sample_data["alpha"].get(key, None)
|
|
355
|
+
if sample_data["alpha"] is not None
|
|
356
|
+
else None
|
|
357
|
+
)
|
|
358
|
+
num_val = (
|
|
359
|
+
sample_data["numeric"].get(key, None)
|
|
360
|
+
if sample_data["numeric"] is not None
|
|
361
|
+
else None
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
# Format values for the table cells
|
|
365
|
+
# Check data examples to decide on separators if needed
|
|
366
|
+
# Assuming genotype might contain '\n' which _format_cell_content should handle
|
|
367
|
+
formatted_geno = _format_cell_content(geno_val, separator="\n")
|
|
368
|
+
# Use newline as separator if present in data
|
|
369
|
+
formatted_alpha = _format_cell_content(alpha_val)
|
|
370
|
+
# No separator assumed for alpha
|
|
371
|
+
formatted_num = _format_cell_content(
|
|
372
|
+
num_val
|
|
373
|
+
) # No separator assumed for numeric
|
|
374
|
+
|
|
375
|
+
# Create Paragraphs for body cells using the cell style
|
|
376
|
+
combined_table_data.append(
|
|
377
|
+
[
|
|
378
|
+
Paragraph(str(key), styles["table_cell"]),
|
|
379
|
+
Paragraph(formatted_geno, styles["table_cell"]),
|
|
380
|
+
Paragraph(formatted_alpha, styles["table_cell"]),
|
|
381
|
+
Paragraph(formatted_num, styles["table_cell"]),
|
|
382
|
+
]
|
|
383
|
+
)
|
|
384
|
+
|
|
385
|
+
# Slightly adjusted widths
|
|
386
|
+
col_widths = [1.5 * inch, 2.5 * inch, 2.0 * inch, 1.5 * inch]
|
|
387
|
+
|
|
388
|
+
# Create the table
|
|
389
|
+
combined_table = Table(combined_table_data, colWidths=col_widths, splitByRow=1)
|
|
390
|
+
|
|
391
|
+
# Apply styling (using your original style block)
|
|
392
|
+
combined_table.setStyle(
|
|
393
|
+
TableStyle(
|
|
394
|
+
[
|
|
395
|
+
("BACKGROUND", (0, 0), (-1, 0), colors.grey),
|
|
396
|
+
("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
|
|
397
|
+
("ALIGN", (0, 0), (-1, 0), "CENTER"), # Header alignment
|
|
398
|
+
("ALIGN", (0, 1), (0, -1), "LEFT"), # Gene name left aligned
|
|
399
|
+
("ALIGN", (1, 1), (-1, -1), "LEFT"), # Other columns LEFT aligned
|
|
400
|
+
("VALIGN", (0, 0), (-1, -1), "MIDDLE"), # Vertical alignment
|
|
401
|
+
("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
|
|
402
|
+
("BOTTOMPADDING", (0, 0), (-1, 0), 8), # Padding for header
|
|
403
|
+
("TOPPADDING", (0, 0), (-1, 0), 4),
|
|
404
|
+
("BOTTOMPADDING", (0, 1), (-1, -1), 4), # Padding for cells
|
|
405
|
+
("TOPPADDING", (0, 1), (-1, -1), 4),
|
|
406
|
+
("BACKGROUND", (0, 1), (-1, -1), colors.beige),
|
|
407
|
+
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
|
408
|
+
("LEFTPADDING", (0, 0), (-1, -1), 4),
|
|
409
|
+
("RIGHTPADDING", (0, 0), (-1, -1), 4),
|
|
410
|
+
]
|
|
411
|
+
)
|
|
412
|
+
)
|
|
413
|
+
return combined_table
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _generate_pdf_report_for_sample(
|
|
417
|
+
norm_id: str,
|
|
418
|
+
original_id_display: str,
|
|
419
|
+
processed_dfs: Dict[str, Optional[pd.DataFrame]],
|
|
420
|
+
styles: Dict[str, ParagraphStyle],
|
|
421
|
+
output_dir: Path,
|
|
422
|
+
UUID: str,
|
|
423
|
+
) -> None:
|
|
424
|
+
"""Generates and saves a single PDF report for one sample.
|
|
425
|
+
|
|
426
|
+
Args:
|
|
427
|
+
norm_id: The normalized sample ID.
|
|
428
|
+
original_id_display: The original sample ID to use for display and filename.
|
|
429
|
+
processed_dfs: Dict mapping data type to the processed DataFrame.
|
|
430
|
+
styles: Dictionary of required ParagraphStyles.
|
|
431
|
+
output_dir: The directory to save the PDF file.
|
|
432
|
+
"""
|
|
433
|
+
# Sanitize original ID for filename
|
|
434
|
+
safe_original_id = "".join(
|
|
435
|
+
c if c.isalnum() or c in ("_", "-") else "_" for c in original_id_display
|
|
436
|
+
)
|
|
437
|
+
pdf_filename = os.path.join(output_dir, f"{safe_original_id}_BloodGroupReport.pdf")
|
|
438
|
+
|
|
439
|
+
# Use BaseDocTemplate to allow page footers
|
|
440
|
+
doc = BaseDocTemplate(
|
|
441
|
+
pdf_filename,
|
|
442
|
+
pagesize=letter, # Use letter size as per your original code
|
|
443
|
+
leftMargin=0.75 * inch,
|
|
444
|
+
rightMargin=0.75 * inch,
|
|
445
|
+
topMargin=0.75 * inch, # Increased top margin slightly
|
|
446
|
+
bottomMargin=0.75 * inch,
|
|
447
|
+
)
|
|
448
|
+
|
|
449
|
+
# Define the frame for content flow
|
|
450
|
+
frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id="normal")
|
|
451
|
+
# Create a PageTemplate that uses the footer function
|
|
452
|
+
template = PageTemplate(
|
|
453
|
+
id="main",
|
|
454
|
+
frames=[frame],
|
|
455
|
+
onPage=lambda canvas, doc: _add_page_footer(canvas, doc, styles, UUID),
|
|
456
|
+
)
|
|
457
|
+
doc.addPageTemplates([template])
|
|
458
|
+
|
|
459
|
+
story: List[Flowable] = []
|
|
460
|
+
|
|
461
|
+
# 1. Add Header (after PageTemplate setup)
|
|
462
|
+
_create_report_header(story, original_id_display, styles)
|
|
463
|
+
|
|
464
|
+
# 2. Get Data for this sample
|
|
465
|
+
sample_data, all_keys_for_sample = _get_data_for_sample(norm_id, processed_dfs)
|
|
466
|
+
|
|
467
|
+
# 3. Add Main Table Title
|
|
468
|
+
story.append(
|
|
469
|
+
Paragraph("Blood Group Genotype & Predicted Phenotype", styles["heading"])
|
|
470
|
+
)
|
|
471
|
+
story.append(Spacer(1, 0.1 * inch))
|
|
472
|
+
|
|
473
|
+
# 4. Create and add the data table (or "No data" message)
|
|
474
|
+
table_flowable = _create_consolidated_table(
|
|
475
|
+
sample_data, all_keys_for_sample, styles
|
|
476
|
+
)
|
|
477
|
+
story.append(table_flowable)
|
|
478
|
+
# Removed spacer after table to maximize space
|
|
479
|
+
|
|
480
|
+
# 5. Build the PDF
|
|
481
|
+
try:
|
|
482
|
+
doc.build(story)
|
|
483
|
+
except Exception as e:
|
|
484
|
+
logger.error(f"ERROR generating PDF for {norm_id} ({original_id_display}): {e}")
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
# --- Main Orchestration Function ---
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def generate_all_reports(
|
|
491
|
+
df_genotypes: Optional[pd.DataFrame],
|
|
492
|
+
df_pheno_alpha: Optional[pd.DataFrame],
|
|
493
|
+
df_pheno_num: Optional[pd.DataFrame],
|
|
494
|
+
output_name: Path,
|
|
495
|
+
UUID: str,
|
|
496
|
+
) -> None:
|
|
497
|
+
"""
|
|
498
|
+
Generates consolidated PDF blood group reports for all samples found in input DataFrames.
|
|
499
|
+
|
|
500
|
+
Args:
|
|
501
|
+
df_genotypes: DataFrame with genotype data. Index must be SampleID.
|
|
502
|
+
df_pheno_alpha: DataFrame with alphanumeric phenotype data. Index must be SampleID.
|
|
503
|
+
df_pheno_num: DataFrame with numeric phenotype data. Index must be SampleID.
|
|
504
|
+
output_dir: Directory where the generated PDF files will be saved.
|
|
505
|
+
"""
|
|
506
|
+
|
|
507
|
+
# 1. Prepare Data & Get Unique IDs
|
|
508
|
+
processed_dfs, all_normalized_ids, original_id_map = _prepare_dataframes(
|
|
509
|
+
df_genotypes, df_pheno_alpha, df_pheno_num
|
|
510
|
+
)
|
|
511
|
+
|
|
512
|
+
if not all_normalized_ids:
|
|
513
|
+
logger.warning("No samples found in the input DataFrames. Exiting.")
|
|
514
|
+
return
|
|
515
|
+
|
|
516
|
+
num_samples = len(all_normalized_ids)
|
|
517
|
+
logger.info(f"Found {num_samples} unique normalized sample IDs.")
|
|
518
|
+
output_dir = f"{output_name}_PDFs"
|
|
519
|
+
# 2. Create output directory
|
|
520
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
521
|
+
logger.info(f"Reports will be saved to '{os.path.abspath(output_dir)}'.")
|
|
522
|
+
|
|
523
|
+
# 3. Setup Styles
|
|
524
|
+
styles = _setup_styles()
|
|
525
|
+
|
|
526
|
+
# 4. Iterate Through Each Sample and Generate PDF
|
|
527
|
+
for norm_id in sorted(list(all_normalized_ids)):
|
|
528
|
+
original_id_display = original_id_map.get(
|
|
529
|
+
norm_id, norm_id
|
|
530
|
+
) # Fallback to norm_id if mapping failed
|
|
531
|
+
|
|
532
|
+
try:
|
|
533
|
+
_generate_pdf_report_for_sample(
|
|
534
|
+
norm_id, original_id_display, processed_dfs, styles, output_dir, UUID
|
|
535
|
+
)
|
|
536
|
+
except Exception as e:
|
|
537
|
+
# Catch potential errors during individual PDF generation
|
|
538
|
+
logger.error(
|
|
539
|
+
f"Unhandled exception during PDF generation for {original_id_display}: {e}"
|
|
540
|
+
)
|
rbceq2/IO/__init__.py
ADDED
|
File without changes
|
rbceq2/IO/record_data.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from loguru import logger
|
|
8
|
+
|
|
9
|
+
from rbceq2.core_logic.constants import DB_VERSION, VERSION, AlleleState
|
|
10
|
+
from rbceq2.IO.validation import validate_vcf
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def configure_logging(args) -> str:
|
|
14
|
+
"""
|
|
15
|
+
Configures the logging for the application.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
args: Command-line arguments containing debug flag and log file path.
|
|
19
|
+
"""
|
|
20
|
+
log_level = "DEBUG" if args.debug else "INFO"
|
|
21
|
+
logger.remove() # Remove default logger configuration
|
|
22
|
+
logger.add(
|
|
23
|
+
f"{args.out}_log.txt", # Log file path from arguments
|
|
24
|
+
level=log_level,
|
|
25
|
+
format="{time} {level} {message}",
|
|
26
|
+
rotation="50 MB", # Rotate the file when it reaches 10 MB
|
|
27
|
+
compression="zip", # Compress old logs
|
|
28
|
+
)
|
|
29
|
+
UUID = str(uuid.uuid4())
|
|
30
|
+
logger.info("NOT FOR CLINICAL USE")
|
|
31
|
+
logger.info(f"RBCeq2 Version: {VERSION}")
|
|
32
|
+
logger.info(f"RBCeq2 database Version: {DB_VERSION}")
|
|
33
|
+
logger.info(f"Session UUID: {UUID}")
|
|
34
|
+
|
|
35
|
+
return UUID
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def record_filtered_data(results: tuple[Any]) -> None:
|
|
39
|
+
"""Record filtered data by logging debug information for each blood group.
|
|
40
|
+
|
|
41
|
+
This function unpacks the results tuple into sample identifier, numeric and
|
|
42
|
+
alphanumeric phenotypes, and a mapping of blood group names to BloodGroup
|
|
43
|
+
objects. For each blood group with filtered out data, it logs details including
|
|
44
|
+
genotypes, numeric and alphanumeric phenotypes, variant pool, raw allele data,
|
|
45
|
+
and the filters applied.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
results (tuple[Any]): A tuple containing the following elements:
|
|
49
|
+
- sample: The sample identifier.
|
|
50
|
+
- _: An unused placeholder.
|
|
51
|
+
- numeric_phenos: A dict mapping blood group names to numeric phenotypes.
|
|
52
|
+
- alphanumeric_phenos: A dict mapping blood group names to
|
|
53
|
+
alphanumeric phenotypes.
|
|
54
|
+
- res: A dict mapping blood group names to BloodGroup objects.
|
|
55
|
+
"""
|
|
56
|
+
sample, _, numeric_phenos, alphanumeric_phenos, res = results
|
|
57
|
+
for bg_name, bg_data in res.items():
|
|
58
|
+
if bg_data.filtered_out:
|
|
59
|
+
logger.debug(
|
|
60
|
+
f"Sample: {sample} BG Name: {bg_name}\n"
|
|
61
|
+
f"\n#Results:\n"
|
|
62
|
+
f"Genotypes: {'\n'.join(bg_data.genotypes)}\n"
|
|
63
|
+
f"Phenotypes (numeric): {numeric_phenos.get(bg_name, '')}\n"
|
|
64
|
+
f"Phenotypes (alphanumeric): {alphanumeric_phenos.get(bg_name, '')}\n"
|
|
65
|
+
f"\n#Data:\n"
|
|
66
|
+
f"Vars: {bg_data.variant_pool}\n"
|
|
67
|
+
f"Raw: {'\n' + '\n'.join(map(str, bg_data.alleles[AlleleState.RAW]))}\n"
|
|
68
|
+
f"\n#Filters applied:\n"
|
|
69
|
+
)
|
|
70
|
+
no_filters = True
|
|
71
|
+
for k, v in bg_data.filtered_out.items():
|
|
72
|
+
if v:
|
|
73
|
+
logger.debug(f"\n{k}: {'\n'.join(map(str, v))}\n")
|
|
74
|
+
no_filters = False
|
|
75
|
+
if no_filters:
|
|
76
|
+
logger.debug('No filters were applied\n')
|
|
77
|
+
logger.debug('\n______\n')
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def check_VCF(VCF_file):
|
|
81
|
+
return validate_vcf(VCF_file), VCF_file
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def log_validation(result, VCF_file):
|
|
85
|
+
"""Log the validation result for a VCF file.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
result (Any): An object representing the validation result. It must have
|
|
89
|
+
attributes 'is_valid' (bool) and 'errors' (iterable of str).
|
|
90
|
+
VCF_file (str): The path or identifier of the VCF file being validated.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
None
|
|
94
|
+
"""
|
|
95
|
+
if result.is_valid:
|
|
96
|
+
logger.info(f"VCF file {VCF_file} passed all checks. Proceed with analysis.")
|
|
97
|
+
else:
|
|
98
|
+
logger.error(f"VCF file {VCF_file} failed validation:")
|
|
99
|
+
for error in result.errors:
|
|
100
|
+
logger.warning(f" - {error}")
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def save_df(df: pd.DataFrame, name: str, UUID: str) -> None:
|
|
104
|
+
"""Sorts the columns of a DataFrame in alphabetical order then writes
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
df (pd.DataFrame): Data to reorder.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
A DataFrame with columns sorted alphabetically.
|
|
111
|
+
"""
|
|
112
|
+
df = df.reindex(sorted(df.columns), axis=1)
|
|
113
|
+
df.index.name = f"UUID: {UUID}"
|
|
114
|
+
df.to_csv(name, sep="\t")
|