# create_latex_table.py – parses concept from experiment_id # ---------------------------------------------------------- from __future__ import annotations import re from pathlib import Path from typing import Dict, List, Tuple, Optional from dataclasses import dataclass import pandas as pd # needs pyarrow OR fastparquet @dataclass class TableConfig: """Configuration for LaTeX table generation.""" concepts: List[str] metric_map: Dict[str, str] # friendly_name -> column_name latex_labels: Dict[str, str] # friendly_name -> latex_label @classmethod def evaluation_results(cls) -> TableConfig: """Create evaluation results configuration.""" return cls( concepts=[f"C{i}" for i in range(1, 6)], # C1 through C5 metric_map={ "F1_ma": "Macro_F1", "F1_w": "Weighted_F1", "QWK": "QWK", }, latex_labels={ "F1_ma": r"F1$_{ma}$", "F1_w": r"F1$_{w}$", "QWK": r"QWK", } ) @classmethod def bootstrap(cls) -> TableConfig: """Create configuration for bootstrap confidence intervals.""" return cls( concepts=[f"C{i}" for i in range(1, 6)], # C1 through C5 metric_map={ "QWK_lower": "QWK_lower_95ci", "QWK_upper": "QWK_upper_95ci", }, latex_labels={ "QWK_lower": r"QWK$_{\text{lower-bound}}$", "QWK_upper": r"QWK$_{\text{upper-bound}}$", } ) @classmethod def bootstrap_qwk(cls) -> TableConfig: """Create configuration for QWK bootstrap confidence intervals.""" return cls.bootstrap() # Alias for backward compatibility @classmethod def bootstrap_macro_f1(cls) -> TableConfig: """Create configuration for Macro F1 bootstrap confidence intervals.""" return cls( concepts=[f"C{i}" for i in range(1, 6)], # C1 through C5 metric_map={ "F1_ma_lower": "Macro_F1_lower_95ci", "F1_ma_upper": "Macro_F1_upper_95ci", }, latex_labels={ "F1_ma_lower": r"F1-Macro$_{\text{-lower-bound}}$", "F1_ma_upper": r"F1-Macro$_{\text{-upper-bound}}$", } ) @classmethod def bootstrap_weighted_f1(cls) -> TableConfig: """Create configuration for Weighted F1 bootstrap confidence intervals.""" return cls( concepts=[f"C{i}" for i in range(1, 6)], # C1 through C5 metric_map={ "F1_w_lower": "Weighted_F1_lower_95ci", "F1_w_upper": "Weighted_F1_upper_95ci", }, latex_labels={ "F1_w_lower": r"F1-Weighted$_{\text{-lower-bound}}$", "F1_w_upper": r"F1-Weighted$_{\text{-upper-bound}}$", } ) class ExperimentIdParser: """Handles parsing and manipulation of experiment IDs.""" CONCEPT_PATTERN = re.compile(r"(?:^|-)(C[1-5])(?:-|$)", flags=re.IGNORECASE) VARIANT_SUFFIX_PATTERN = re.compile( r"-(essay[-_]only|full[-_]context|full)$", flags=re.IGNORECASE ) AGGREGATION_SUFFIX_PATTERN = re.compile( r"-(onlyA|onlyB|avg\(A,B\)|concat\(A,B\))$", flags=re.IGNORECASE ) # Group definitions GROUP_1_PREFIXES = ["bertimbau", "bertugues", "mbert", "albertina"] GROUP_2_PREFIXES = ["phi3.5", "phi4", "llama3.1", "tucano2b4"] GROUP_3_PREFIXES = ["sabia3", "deepseekr1", "gpt4o"] @classmethod def get_experiment_group(cls, experiment_id: str) -> int: """ Classify experiment into groups based on model name. Returns: 1, 2, or 3 for the respective groups, or 4 for unclassified """ exp_lower = experiment_id.lower() for prefix in cls.GROUP_1_PREFIXES: if exp_lower.startswith(prefix): return 1 for prefix in cls.GROUP_2_PREFIXES: if exp_lower.startswith(prefix): return 2 for prefix in cls.GROUP_3_PREFIXES: if exp_lower.startswith(prefix): return 3 return 4 # Unclassified experiments @classmethod def split_experiment_id(cls, experiment_id: str) -> Tuple[str, str]: """ Extract base ID and concept from experiment ID. Args: experiment_id: Full experiment ID string Returns: Tuple of (base_id_without_concept, concept) Example: 'deepseekR1-extractor-C3-full_context' → ('deepseekR1-extractor-full_context', 'C3') """ match = cls.CONCEPT_PATTERN.search(experiment_id) if not match: raise ValueError( f"Could not find C1–C5 token in experiment_id='{experiment_id}'" ) concept = match.group(1).upper() # Replace the concept token with a single dash to maintain separation base_id = cls.CONCEPT_PATTERN.sub("-", experiment_id) # Clean up any resulting double dashes or leading/trailing dashes base_id = re.sub(r"-+", "-", base_id).strip("-") return base_id, concept @classmethod def extract_family_name(cls, experiment_id: str) -> str: """ Extract family name by removing variant suffixes. Collapses variations like: - 'phi3.5-mini-lora-essay-only-A' - 'phi3.5-mini-lora-full-context-B' into the same family: 'phi3.5-mini-lora' """ # Remove aggregation suffixes family = cls.AGGREGATION_SUFFIX_PATTERN.sub("", experiment_id) # Remove variant suffixes family = cls.VARIANT_SUFFIX_PATTERN.sub("", family) return family class DataProcessor: """Handles data loading and transformation.""" def __init__(self, config: TableConfig): self.config = config self.parser = ExperimentIdParser() def load_and_prepare_data(self, file_path: Path, metric_group_filter: Optional[str] = None) -> pd.DataFrame: """Load parquet file and add experiment metadata. Args: file_path: Path to the parquet file metric_group_filter: If provided, only keep rows with this metric_group value """ df = pd.read_parquet(file_path) # Check if metric_group column exists if "metric_group" in df.columns: # Filter by metric_group if specified if metric_group_filter: df = df[df["metric_group"] == metric_group_filter].copy() # Combine experiment_id with metric_group df["experiment_id"] = df.apply( lambda x: f"{x['experiment_id']}-{x['metric_group']}", axis=1 ) # If no metric_group column, experiment_id remains unchanged (bootstrap case) # Parse experiment IDs base_ids, concepts = zip(*df["experiment_id"].map(self.parser.split_experiment_id)) df = df.assign(__base_id=base_ids, __concept=concepts) return df def create_pivot_table(self, df: pd.DataFrame) -> pd.DataFrame: """Create pivoted table with one row per base ID and columns for each metric/concept.""" value_columns = list(self.config.metric_map.values()) # Melt data for pivoting melted = ( df[["__base_id", "__concept"] + value_columns] .melt( id_vars=["__base_id", "__concept"], var_name="metric_real", value_name="value" ) ) # Map back to friendly metric names reverse_metric_map = {v: k for k, v in self.config.metric_map.items()} melted["metric"] = melted["metric_real"].map(reverse_metric_map) # Create pivot table pivot = melted.pivot_table( index="__base_id", columns=["__concept", "metric"], values="value", aggfunc="mean" # handle rare duplicates ) # Ensure consistent column order ordered_columns = pd.MultiIndex.from_product( [self.config.concepts, list(self.config.metric_map.keys())] ) pivot = pivot.reindex(columns=ordered_columns, fill_value=pd.NA) # Add group information for sorting pivot["__group"] = pivot.index.map(self.parser.get_experiment_group) # Sort by group first, then by experiment name pivot = pivot.sort_values(["__group", "__base_id"]) # Remove the temporary group column pivot = pivot.drop(columns=["__group"]) return pivot class LaTeXTableGenerator: """Generates LaTeX table from processed data.""" def __init__(self, config: TableConfig): self.config = config self.parser = ExperimentIdParser() @staticmethod def escape_latex(text: str) -> str: """Escape special LaTeX characters.""" replacements = { "_": r"\_", "%": r"\%", "&": r"\&", } for char, escaped in replacements.items(): text = text.replace(char, escaped) return text def _generate_header(self) -> List[str]: """Generate table header lines.""" lines = [] # Table opening with column specifications num_metrics = len(self.config.metric_map) column_spec = "c|" + " ".join([" ".join(["c"] * num_metrics) + "|" for _ in self.config.concepts[:-1]]) + " " + " ".join(["c"] * num_metrics) lines.append(rf"\begin{{tabular}}{{{column_spec}}}") lines.append(r"\hline\hline") # First header row - concept names concept_headers = [""] for concept in self.config.concepts: concept_headers.append(rf"\multicolumn{{{num_metrics}}}{{c|}}{{\textbf{{{concept}}}}}") concept_headers[-1] = concept_headers[-1].rstrip("|") lines.append(" & ".join(concept_headers) + r" \\ \hline") # Second header row - metric labels metric_headers = [""] for _ in self.config.concepts: metric_headers.extend([ self.config.latex_labels[metric] for metric in self.config.metric_map ]) lines.append(" & ".join(metric_headers) + r" \\ \hline") return lines def _generate_body(self, data: pd.DataFrame) -> List[str]: """Generate table body lines.""" lines = [] previous_family = None previous_group = None for base_id, row in data.iterrows(): family = self.parser.extract_family_name(base_id) current_group = self.parser.get_experiment_group(base_id) # Add double line separator between different groups if previous_group is not None and current_group != previous_group: lines.append(r"\hline\hline") # Add single line separator between different families within same group elif previous_family is not None and family != previous_family: lines.append(r"\hline") previous_family = family previous_group = current_group # Build row values row_values = [self.escape_latex(base_id)] for concept in self.config.concepts: for metric in self.config.metric_map: value = row[(concept, metric)] row_values.append("--" if pd.isna(value) else f"{value:.2f}") lines.append(" & ".join(row_values) + r" \\") return lines def generate_table(self, data: pd.DataFrame) -> str: """Generate complete LaTeX table.""" lines = [] lines.extend(self._generate_header()) lines.extend(self._generate_body(data)) lines.append(r"\hline\hline") lines.append(r"\end{tabular}%") return "\n".join(lines) def main(): """Main entry point for the script.""" # Configuration for evaluation results config = TableConfig.evaluation_results() input_file = Path("evaluation_results-00000-of-00001.parquet") output_file_full = Path("evaluation_table_full.txt") output_file_avg = Path("evaluation_table_avg_only.txt") # Process data for full table processor = DataProcessor(config) df_full = processor.load_and_prepare_data(input_file) pivot_data_full = processor.create_pivot_table(df_full) # Process data for avg(A,B) only df_avg = processor.load_and_prepare_data(input_file, metric_group_filter="avg(A,B)") pivot_data_avg = processor.create_pivot_table(df_avg) # Generate LaTeX tables generator = LaTeXTableGenerator(config) latex_table_full = generator.generate_table(pivot_data_full) latex_table_avg = generator.generate_table(pivot_data_avg) # Save outputs output_file_full.write_text(latex_table_full, encoding="utf-8") output_file_avg.write_text(latex_table_avg, encoding="utf-8") print(f"✅ Wrote {output_file_full} – full table with all metric groups") print(f"✅ Wrote {output_file_avg} – filtered table with only avg(A,B) metric group") # Process bootstrap confidence intervals input_file_bootstrap = Path("bootstrap_confidence_intervals-00000-of-00001.parquet") # 1. QWK bootstrap confidence intervals config_bootstrap_qwk = TableConfig.bootstrap_qwk() output_file_bootstrap_qwk = Path("bootstrap_confidence_intervals_QWK_table.txt") processor_bootstrap_qwk = DataProcessor(config_bootstrap_qwk) df_bootstrap = processor_bootstrap_qwk.load_and_prepare_data(input_file_bootstrap) pivot_data_bootstrap_qwk = processor_bootstrap_qwk.create_pivot_table(df_bootstrap) generator_bootstrap_qwk = LaTeXTableGenerator(config_bootstrap_qwk) latex_table_bootstrap_qwk = generator_bootstrap_qwk.generate_table(pivot_data_bootstrap_qwk) output_file_bootstrap_qwk.write_text(latex_table_bootstrap_qwk, encoding="utf-8") print(f"✅ Wrote {output_file_bootstrap_qwk} – QWK bootstrap confidence intervals table") # 2. Macro F1 bootstrap confidence intervals config_bootstrap_macro_f1 = TableConfig.bootstrap_macro_f1() output_file_bootstrap_macro_f1 = Path("bootstrap_confidence_intervals_Macro_F1_table.txt") processor_bootstrap_macro_f1 = DataProcessor(config_bootstrap_macro_f1) # Reuse the already loaded dataframe pivot_data_bootstrap_macro_f1 = processor_bootstrap_macro_f1.create_pivot_table(df_bootstrap) generator_bootstrap_macro_f1 = LaTeXTableGenerator(config_bootstrap_macro_f1) latex_table_bootstrap_macro_f1 = generator_bootstrap_macro_f1.generate_table(pivot_data_bootstrap_macro_f1) output_file_bootstrap_macro_f1.write_text(latex_table_bootstrap_macro_f1, encoding="utf-8") print(f"✅ Wrote {output_file_bootstrap_macro_f1} – Macro F1 bootstrap confidence intervals table") # 3. Weighted F1 bootstrap confidence intervals config_bootstrap_weighted_f1 = TableConfig.bootstrap_weighted_f1() output_file_bootstrap_weighted_f1 = Path("bootstrap_confidence_intervals_Weighted_F1_table.txt") processor_bootstrap_weighted_f1 = DataProcessor(config_bootstrap_weighted_f1) # Reuse the already loaded dataframe pivot_data_bootstrap_weighted_f1 = processor_bootstrap_weighted_f1.create_pivot_table(df_bootstrap) generator_bootstrap_weighted_f1 = LaTeXTableGenerator(config_bootstrap_weighted_f1) latex_table_bootstrap_weighted_f1 = generator_bootstrap_weighted_f1.generate_table(pivot_data_bootstrap_weighted_f1) output_file_bootstrap_weighted_f1.write_text(latex_table_bootstrap_weighted_f1, encoding="utf-8") print(f"✅ Wrote {output_file_bootstrap_weighted_f1} – Weighted F1 bootstrap confidence intervals table") if __name__ == "__main__": main()