File size: 31,160 Bytes
06c7e2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
"""Compositional task that chains multiple atomic operations."""

import random
import pandas as pd
from pathlib import Path
from typing import Dict, List, Any, Callable, Optional

from tasks.base_task import BaseTask, TaskConfig


# =============================================================================
# Atomic Operations Registry
# =============================================================================

# Pure string operations (no external data needed)
STRING_OPERATIONS: Dict[str, Callable[[str], str]] = {
    "uppercase": lambda x: x.upper(),
    "lowercase": lambda x: x.lower(),
    "reverse": lambda x: x[::-1],
    "first_letter": lambda x: x[0] if x else "",
    "last_letter": lambda x: x[-1] if x else "",
}


def load_lookup_tables() -> Dict[str, Dict[str, str]]:
    """Load lookup-based operations from simple.csv.
    
    Returns a dictionary mapping operation names to their lookup tables.
    """
    csv_path = Path(__file__).parent.parent.parent / "dataset" / "simple.csv"
    if not csv_path.exists():
        return {}
    
    df = pd.read_csv(csv_path)
    
    # Categories that can be used as lookup operations
    lookup_categories = [
        "translate_eng_fr", "translate_fr_eng",
        "translate_eng_sp", "translate_sp_eng",
        "present_to_gerund", "singular_to_plural",
        "country_to_capital",
    ]
    
    lookup_tables = {}
    for category in lookup_categories:
        cat_data = df[df["category_name"] == category]
        if not cat_data.empty:
            lookup_tables[category] = dict(zip(cat_data["question"], cat_data["answer"]))

    # Backfill eng->sp from sp->eng when simple.csv lacks translate_eng_sp rows.
    # Keep the first observed Spanish form for each English token.
    if "translate_eng_sp" not in lookup_tables and "translate_sp_eng" in lookup_tables:
        sp_to_eng = lookup_tables["translate_sp_eng"]
        eng_to_sp: Dict[str, str] = {}
        for sp, eng in sp_to_eng.items():
            eng_norm = str(eng).strip().lower()
            if eng_norm and eng_norm not in eng_to_sp:
                eng_to_sp[eng_norm] = str(sp)
        if eng_to_sp:
            lookup_tables["translate_eng_sp"] = eng_to_sp
    
    return lookup_tables


# Global lookup tables (loaded once)
LOOKUP_TABLES: Dict[str, Dict[str, str]] = {}


def get_lookup_operation(op_name: str) -> Optional[Callable[[str], str]]:
    """Get a lookup-based operation function."""
    global LOOKUP_TABLES
    if not LOOKUP_TABLES:
        LOOKUP_TABLES = load_lookup_tables()
    
    if op_name in LOOKUP_TABLES:
        table = LOOKUP_TABLES[op_name]
        return lambda x: table.get(x, x)  # Return original if not found
    return None


def get_operation(op_name: str) -> Callable[[str], str]:
    """Get an operation function by name (string or lookup-based)."""
    if op_name in STRING_OPERATIONS:
        return STRING_OPERATIONS[op_name]
    
    lookup_op = get_lookup_operation(op_name)
    if lookup_op:
        return lookup_op
    
    raise ValueError(f"Unknown operation: {op_name}")


def apply_composition(input_str: str, operations: List[str]) -> str:
    """Apply a sequence of operations to an input string."""
    result = input_str
    for op_name in operations:
        op_func = get_operation(op_name)
        result = op_func(result)
    return result


def parse_operations(operations_str: str) -> List[str]:
    """Parse operations string like 'uppercase+reverse' into list."""
    return operations_str.split("+")


# =============================================================================
# Predefined Compositions
# =============================================================================

# Pure string compositions (any input works)
STRING_COMPOSITIONS = {
    # 2-operation: case + manipulation
    "upper_reverse": ["uppercase", "reverse"],
    "lower_reverse": ["lowercase", "reverse"],
    "upper_first": ["uppercase", "first_letter"],
    "lower_first": ["lowercase", "first_letter"],
    "upper_last": ["uppercase", "last_letter"],
    "lower_last": ["lowercase", "last_letter"],
    "reverse_first": ["reverse", "first_letter"],
    "reverse_last": ["reverse", "last_letter"],
    
    # 3-operation chains

}

# Lookup-based compositions (require specific input domains)
# Format: (composition_name, operations, source_lookup_table)
# The source_lookup_table determines valid inputs
LOOKUP_COMPOSITIONS = {
    # Translation eng->fr + string ops (complete coverage)
    "translate_eng_fr_upper": (["translate_eng_fr", "uppercase"], "translate_eng_fr"),
    "translate_eng_fr_lower": (["translate_eng_fr", "lowercase"], "translate_eng_fr"),
    "translate_eng_fr_reverse": (["translate_eng_fr", "reverse"], "translate_eng_fr"),
    "translate_eng_fr_first": (["translate_eng_fr", "first_letter"], "translate_eng_fr"),
    "translate_eng_fr_last": (["translate_eng_fr", "last_letter"], "translate_eng_fr"),
    
    # Translation eng->sp + string ops (complete coverage)
    "translate_eng_sp_upper": (["translate_eng_sp", "uppercase"], "translate_eng_sp"),
    "translate_eng_sp_lower": (["translate_eng_sp", "lowercase"], "translate_eng_sp"),
    "translate_eng_sp_reverse": (["translate_eng_sp", "reverse"], "translate_eng_sp"),
    "translate_eng_sp_first": (["translate_eng_sp", "first_letter"], "translate_eng_sp"),
    "translate_eng_sp_last": (["translate_eng_sp", "last_letter"], "translate_eng_sp"),
    
    # Translation fr->eng + string ops (complete coverage)
    "translate_fr_eng_upper": (["translate_fr_eng", "uppercase"], "translate_fr_eng"),
    "translate_fr_eng_lower": (["translate_fr_eng", "lowercase"], "translate_fr_eng"),
    "translate_fr_eng_reverse": (["translate_fr_eng", "reverse"], "translate_fr_eng"),
    "translate_fr_eng_first": (["translate_fr_eng", "first_letter"], "translate_fr_eng"),
    "translate_fr_eng_last": (["translate_fr_eng", "last_letter"], "translate_fr_eng"),
    
    # Translation sp->eng + string ops (complete coverage)
    "translate_sp_eng_upper": (["translate_sp_eng", "uppercase"], "translate_sp_eng"),
    "translate_sp_eng_lower": (["translate_sp_eng", "lowercase"], "translate_sp_eng"),
    "translate_sp_eng_reverse": (["translate_sp_eng", "reverse"], "translate_sp_eng"),
    "translate_sp_eng_first": (["translate_sp_eng", "first_letter"], "translate_sp_eng"),
    "translate_sp_eng_last": (["translate_sp_eng", "last_letter"], "translate_sp_eng"),
    
    # Morphological + string ops (complete coverage)
    "gerund_upper": (["present_to_gerund", "uppercase"], "present_to_gerund"),
    "gerund_lower": (["present_to_gerund", "lowercase"], "present_to_gerund"),
    "gerund_reverse": (["present_to_gerund", "reverse"], "present_to_gerund"),
    "gerund_first": (["present_to_gerund", "first_letter"], "present_to_gerund"),
    "plural_upper": (["singular_to_plural", "uppercase"], "singular_to_plural"),
    "plural_lower": (["singular_to_plural", "lowercase"], "singular_to_plural"),
    "plural_reverse": (["singular_to_plural", "reverse"], "singular_to_plural"),
    "plural_first": (["singular_to_plural", "first_letter"], "singular_to_plural"),
    
    # Country-to-capital + string ops (complete non-trivial coverage)
    # Note: capitals are Title Case, so lowercase ops are non-trivial (unlike translate/gerund/plural)
    "capital_upper": (["country_to_capital", "uppercase"], "country_to_capital"),
    "capital_lower": (["country_to_capital", "lowercase"], "country_to_capital"),
    "capital_reverse": (["country_to_capital", "reverse"], "country_to_capital"),
    "capital_first": (["country_to_capital", "first_letter"], "country_to_capital"),
    "capital_last": (["country_to_capital", "last_letter"], "country_to_capital"),

    # 3-operation chains with lookup
    # Existing (uppercase+reverse pattern)
    "gerund_upper_reverse": (["present_to_gerund", "uppercase", "reverse"], "present_to_gerund"),
    "plural_upper_reverse": (["singular_to_plural", "uppercase", "reverse"], "singular_to_plural"),
    "translate_eng_fr_upper_reverse": (["translate_eng_fr", "uppercase", "reverse"], "translate_eng_fr"),
    "translate_eng_sp_upper_reverse": (["translate_eng_sp", "uppercase", "reverse"], "translate_eng_sp"),
    # Filling symmetric gaps: fr->eng and sp->eng uppercase+reverse
    "translate_fr_eng_upper_reverse": (["translate_fr_eng", "uppercase", "reverse"], "translate_fr_eng"),
    "translate_sp_eng_upper_reverse": (["translate_sp_eng", "uppercase", "reverse"], "translate_sp_eng"),
    # 3-chains ending in first_letter (depth-3 analog of 2-chain _first)
    "translate_eng_fr_upper_first": (["translate_eng_fr", "uppercase", "first_letter"], "translate_eng_fr"),
    "translate_eng_sp_upper_first": (["translate_eng_sp", "uppercase", "first_letter"], "translate_eng_sp"),
    "translate_fr_eng_upper_first": (["translate_fr_eng", "uppercase", "first_letter"], "translate_fr_eng"),
    "translate_sp_eng_upper_first": (["translate_sp_eng", "uppercase", "first_letter"], "translate_sp_eng"),
    # 3-chains ending in last_letter (key comparison: does depth-3 _last still fail?)
    "translate_eng_fr_upper_last": (["translate_eng_fr", "uppercase", "last_letter"], "translate_eng_fr"),
    "translate_eng_sp_upper_last": (["translate_eng_sp", "uppercase", "last_letter"], "translate_eng_sp"),
    "translate_fr_eng_upper_last": (["translate_fr_eng", "uppercase", "last_letter"], "translate_fr_eng"),
    "translate_sp_eng_upper_last": (["translate_sp_eng", "uppercase", "last_letter"], "translate_sp_eng"),
    # Country-to-capital 3-chains (mixed-case outputs enable both upper and lower variants)
    "capital_upper_reverse": (["country_to_capital", "uppercase", "reverse"], "country_to_capital"),
    "capital_lower_reverse": (["country_to_capital", "lowercase", "reverse"], "country_to_capital"),
    "capital_lower_first": (["country_to_capital", "lowercase", "first_letter"], "country_to_capital"),
    "capital_upper_last": (["country_to_capital", "uppercase", "last_letter"], "country_to_capital"),
}


# =============================================================================
# Input Pools
# =============================================================================


def load_atomic_operation_inputs() -> Dict[str, List[str]]:
    """Load actual input examples for each atomic operation from simple.csv.
    
    This ensures compositional tasks use in-distribution inputs from component tasks.
    
    Returns:
        Dictionary mapping operation names to their input pools from simple.csv
    """
    csv_path = Path(__file__).parent.parent.parent / "dataset" / "simple.csv"
    if not csv_path.exists():
        return {}
    
    df = pd.read_csv(csv_path)
    
    # Map simple.csv category names to operation names
    category_to_op = {
        "uppercase": "uppercase",
        "lowercase": "lowercase",
        "first_letter": "first_letter",
        "last_letter": "last_letter",
        "reverse": "reverse",  # May not exist in simple.csv
    }
    
    operation_inputs = {}
    for category, op_name in category_to_op.items():
        cat_data = df[df["category_name"] == category]
        if not cat_data.empty:
            operation_inputs[op_name] = cat_data["question"].unique().tolist()
    
    return operation_inputs


def load_generic_string_inputs() -> List[str]:
    """Load a broad in-domain word pool for pure string compositions.

    This stays grounded in simple.csv rather than introducing synthetic strings.
    Restrict to single-token alphabetic strings longer than one character so
    reverse/first/last operations remain meaningful.
    """
    csv_path = Path(__file__).parent.parent.parent / "dataset" / "simple.csv"
    if not csv_path.exists():
        return []

    df = pd.read_csv(csv_path)
    questions = df["question"].dropna().astype(str)
    values = {
        value
        for value in questions
        if " " not in value and len(value) > 1 and all(ch.isalpha() for ch in value)
    }
    return sorted(values)


def get_seed_string_inputs(operations: List[str], operation_inputs: Dict[str, List[str]]) -> List[str]:
    """Choose a meaningful input pool for pure string compositions.

    Using the first operation's atomic dataset directly makes chains like
    lowercase+reverse collapse into one-character examples because the lowercase
    task only contains A-Z. Use a richer in-domain word pool instead, and bias
    its casing so case-conversion operations still do real work.
    """
    generic_inputs = load_generic_string_inputs()
    first_op = operations[0]

    if not generic_inputs:
        return operation_inputs.get(first_op, [])

    if "lowercase" in operations and "uppercase" not in operations:
        return [value.upper() for value in generic_inputs]

    if "uppercase" in operations and "lowercase" not in operations:
        return [value.lower() for value in generic_inputs]

    return generic_inputs


def get_string_composition_inputs(operations: List[str], strict_chain: bool = False) -> List[str]:
    """Get input pool for a string composition.
    
    Args:
        operations: List of operation names in the composition
        strict_chain: If True, only use inputs where intermediate results are also 
                     in-distribution (Approach B). If False, use a broad in-domain string pool.
    
    Returns:
        List of valid input strings for this composition
    """
    operation_inputs = load_atomic_operation_inputs()
    
    first_op = operations[0]
    inputs = get_seed_string_inputs(operations, operation_inputs)
    if not inputs:
        return []
    
    # Approach A (default): Use the richer seed inputs.
    if not strict_chain:
        return inputs
    
    # Approach B (strict): Only keep inputs where entire chain is in-distribution
    if len(operations) < 2:
        return inputs
    
    second_op = operations[1]
    
    # If the next op has no atomic pool, keep the richer seed inputs.
    if second_op not in operation_inputs:
        return inputs
    
    valid_for_op2 = set(operation_inputs[second_op])
    
    # Filter to inputs where intermediate result is in-distribution for op2
    valid_inputs = []
    for inp in inputs:
        try:
            op_func = get_operation(first_op)
            intermediate = op_func(inp)
            if intermediate in valid_for_op2:
                valid_inputs.append(inp)
        except Exception:
            continue
    
    return valid_inputs  # May return empty list if no inputs satisfy strict chain requirement


# Operations that benefit from character spacing
SPACING_BENEFITS = {"reverse", "first_letter", "last_letter"}


def add_spaces(s: str) -> str:
    """Add spaces between each character."""
    return " ".join(list(s))


def remove_spaces(s: str) -> str:
    """Remove spaces from a string."""
    return s.replace(" ", "")


def composition_benefits_from_spacing(operations: List[str]) -> bool:
    """Check if a composition would benefit from character spacing."""
    return any(op in SPACING_BENEFITS for op in operations)


def get_lookup_inputs(lookup_name: str) -> List[str]:
    """Get valid inputs for a lookup-based operation."""
    global LOOKUP_TABLES
    if not LOOKUP_TABLES:
        LOOKUP_TABLES = load_lookup_tables()
    
    if lookup_name in LOOKUP_TABLES:
        return list(LOOKUP_TABLES[lookup_name].keys())
    return []


def build_lookup_example(input_str: str, operations: List[str]) -> tuple[str, str]:
    """Build a lookup-based example input/output pair for a composition.

    For lookup chains ending with lowercase (and no uppercase op), expose an
    uppercase input so the lowercase step is not a no-op while preserving lookup
    validity via the original key.
    """
    display_input = input_str

    if "lowercase" in operations and "uppercase" not in operations:
        display_input = input_str.upper()

        # Keep lookup domain valid with the original key, then force lowercase
        # to do real work by uppercasing the intermediate string first.
        result = get_operation(operations[0])(input_str)
        result = result.upper()
        for op_name in operations[1:]:
            result = get_operation(op_name)(result)
        return display_input, result

    return display_input, apply_composition(input_str, operations)


# =============================================================================
# Compositional Task Implementation
# =============================================================================

class CompositionalTask(BaseTask):
    """A task that chains multiple atomic operations.
    
    This task supports:
    - Loading from CSV file (dataset/compositional.csv)
    - Auto-generating data if CSV doesn't exist
    - Subtask filtering via category_name (e.g., compositional:upper_reverse)
    - Spaced mode for character-level operations (spaced=True)
    
    Examples:
        # Load all compositional tasks
        task = get_task("compositional")
        
        # Load specific composition
        task = get_task("compositional:upper_reverse")
        
        # Load with spacing for character-level operations
        task = get_task("compositional:upper_reverse", spaced=True)
    """
    
    TASK_NAME = "compositional"  # Auto-registration name
    
    def __init__(self, config: TaskConfig, spaced: bool = False):
        """Initialize compositional task.
        
        Args:
            config: Task configuration
            spaced: If True, add spaces between characters in input/output
        """
        self.spaced = spaced
        super().__init__(config)
    
    def _load_data(self):
        """Load compositional task data from CSV or generate it."""
        # Use spaced CSV if in spaced mode
        if self.spaced:
            data_path = Path(__file__).parent.parent.parent / "dataset" / "compositional_spaced.csv"
        else:
            data_path = Path(__file__).parent.parent.parent / "dataset" / "compositional.csv"
        
        if data_path.exists():
            df = pd.read_csv(data_path)
            df = df.fillna("")
            self.data = df.to_dict("records")
        else:
            # Generate data if CSV doesn't exist
            self._generate_data()
            # Optionally save to CSV for future runs
            self._save_data(data_path)
    
    def _generate_data(self, strict_chain: bool = False):
        """Generate compositional examples programmatically.
        
        Args:
            strict_chain: If True, use Approach B (only inputs where entire chain is in-distribution).
                         If False, use Approach A (use first operation's inputs).
        """
        examples = []
        
        # Generate examples for pure string compositions
        for comp_name, ops in STRING_COMPOSITIONS.items():
            # Get appropriate input pool based on approach
            valid_inputs = get_string_composition_inputs(ops, strict_chain=strict_chain)
            
            for input_str in valid_inputs:
                try:
                    output = apply_composition(input_str, ops)
                    
                    if self.spaced:
                        examples.append({
                            "input": add_spaces(input_str),
                            "output": add_spaces(output),
                            "original_input": input_str,
                            "original_output": output,
                            "category_name": comp_name,
                            "operations": "+".join(ops),
                            "spaced": True,
                        })
                    else:
                        examples.append({
                            "input": input_str,
                            "output": output,
                            "category_name": comp_name,
                            "operations": "+".join(ops),
                        })
                except Exception as e:
                    print(f"Warning: Failed to generate {comp_name} for '{input_str}': {e}")
                    continue
        
        # Generate examples for lookup-based compositions
        for comp_name, (ops, source_lookup) in LOOKUP_COMPOSITIONS.items():
            valid_inputs = get_lookup_inputs(source_lookup)
            for input_str in valid_inputs:
                try:
                    display_input, output = build_lookup_example(input_str, ops)
                    # Skip if lookup returned original (meaning lookup failed)
                    if ops[0] in LOOKUP_TABLES and output == input_str:
                        continue
                    
                    if self.spaced:
                        examples.append({
                            "input": add_spaces(display_input),
                            "output": add_spaces(output),
                            "original_input": display_input,
                            "original_output": output,
                            "category_name": comp_name,
                            "operations": "+".join(ops),
                            "spaced": True,
                        })
                    else:
                        examples.append({
                            "input": display_input,
                            "output": output,
                            "category_name": comp_name,
                            "operations": "+".join(ops),
                        })
                except Exception as e:
                    print(f"Warning: Failed to generate {comp_name} for '{input_str}': {e}")
                    continue
        
        self.data = examples
    
    def _save_data(self, path: Path):
        """Save generated data to CSV for reproducibility."""
        path.parent.mkdir(parents=True, exist_ok=True)
        df = pd.DataFrame(self.data)
        df.to_csv(path, index=False)
        print(f"Saved compositional data to {path}")
    
    def build_prompt(self, instance: Dict[str, Any], num_shots: int = 5) -> str:
        """Build ICL prompt with demonstrations from same category.
        
        Args:
            instance: Test instance with 'input', 'output', 'category_name'
            num_shots: Number of demonstration examples
            
        Returns:
            Formatted prompt string
        """
        category = instance.get("category_name", "")
        
        # Get demos from same category, excluding test instance
        demos = [
            ex for ex in self.data 
            if ex.get("category_name") == category and ex["input"] != instance["input"]
        ]
        random.shuffle(demos)
        demos = demos[:num_shots]
        
        # Build prompt with simple arrow format (like simple_icl)
        prompt_parts = []
        
        # Add demonstrations
        for demo in demos:
            prompt_parts.append(f"{demo['input']} -> {demo['output']}")
        
        # Add test instance (without answer)
        prompt_parts.append(f"{instance['input']} ->")
        
        return "\n".join(prompt_parts)
    
    def evaluate(self, predictions: List[str], split: str = "test", **kwargs) -> Dict[str, float]:
        """Evaluate predictions against ground truth.
        
        Args:
            predictions: List of model predictions
            split: Data split to evaluate on
            
        Returns:
            Dictionary with evaluation metrics
        """
        ground_truth = self.get_ground_truth(split)
        task_data = self.get_split(split)
        
        if len(predictions) != len(ground_truth):
            raise ValueError(f"Prediction count ({len(predictions)}) doesn't match ground truth count ({len(ground_truth)})")
        
        # Preprocess predictions
        processed_predictions = []
        for pred in predictions:
            # Clean prediction: take first line, strip whitespace
            pred_clean = pred.strip().split("\n")[0].strip()
            
            # Remove leading arrow if present
            if pred_clean.startswith("->"):
                pred_clean = pred_clean[2:].strip()
            
            # For spaced mode, keep spaces; otherwise take first word
            if self.spaced:
                # Keep the full spaced output
                processed_predictions.append(pred_clean)
            else:
                # Take first word only
                pred_clean = pred_clean.split()[0] if pred_clean.split() else pred_clean
                processed_predictions.append(pred_clean)
        
        def matches(pred: str, gt: str) -> bool:
            """Check if prediction matches ground truth, handling spaced mode."""
            pred_norm = pred.lower().strip()
            gt_norm = gt.lower().strip()
            
            if pred_norm == gt_norm:
                return True
            
            # For spaced mode, also try comparing without spaces
            if self.spaced:
                pred_unspaced = remove_spaces(pred_norm)
                gt_unspaced = remove_spaces(gt_norm)
                return pred_unspaced == gt_unspaced
            
            return False
        
        # Overall accuracy
        correct = sum(1 for pred, gt in zip(processed_predictions, ground_truth) 
                     if matches(pred, gt))
        accuracy = correct / len(ground_truth)
        
        results = {
            "accuracy": accuracy,
            "correct": correct,
            "total": len(ground_truth)
        }
        
        # Per-category accuracy
        category_stats = {}
        for pred, gt, item in zip(processed_predictions, ground_truth, task_data):
            category = item.get("category_name", "unknown")
            if category not in category_stats:
                category_stats[category] = {"correct": 0, "total": 0}
            
            category_stats[category]["total"] += 1
            if matches(pred, gt):
                category_stats[category]["correct"] += 1
        
        # Calculate per-category accuracy
        for category, stats in category_stats.items():
            results[f"accuracy_{category}"] = stats["correct"] / stats["total"]
            results[f"correct_{category}"] = stats["correct"]
            results[f"total_{category}"] = stats["total"]
        
        return results
    
    @property
    def task_type(self) -> str:
        return "compositional_spaced" if self.spaced else "compositional"
    
    @property
    def description(self) -> str:
        return "Compositional task that chains multiple atomic string operations"


# =============================================================================
# Utility Functions
# =============================================================================

def generate_compositional_csv(output_path: str = None, spaced: bool = False, strict_chain: bool = False):
    """Generate the compositional.csv or compositional_spaced.csv file.
    
    Args:
        output_path: Path to save CSV. Defaults to dataset/compositional.csv or compositional_spaced.csv
        spaced: If True, generate spaced version with spaces between characters
        strict_chain: If True, use Approach B (strict in-distribution chains). 
                     If False, use Approach A (first op's inputs).
    """
    if output_path is None:
        if spaced:
            output_path = Path(__file__).parent.parent.parent / "dataset" / "compositional_spaced.csv"
        else:
            output_path = Path(__file__).parent.parent.parent / "dataset" / "compositional.csv"
    else:
        output_path = Path(output_path)
    
    # Ensure lookup tables are loaded
    global LOOKUP_TABLES
    if not LOOKUP_TABLES:
        LOOKUP_TABLES = load_lookup_tables()
    
    examples = []
    
    # Generate pure string compositions using Approach A or B
    for comp_name, ops in STRING_COMPOSITIONS.items():
        valid_inputs = get_string_composition_inputs(ops, strict_chain=strict_chain)
        
        for input_str in valid_inputs:
            try:
                output = apply_composition(input_str, ops)
                
                if spaced:
                    examples.append({
                        "input": add_spaces(input_str),
                        "output": add_spaces(output),
                        "original_input": input_str,
                        "original_output": output,
                        "category_name": comp_name,
                        "operations": "+".join(ops),
                        "spaced": True,
                    })
                else:
                    examples.append({
                        "input": input_str,
                        "output": output,
                        "category_name": comp_name,
                        "operations": "+".join(ops),
                    })
            except Exception:
                continue
    
    # Generate lookup-based compositions
    for comp_name, (ops, source_lookup) in LOOKUP_COMPOSITIONS.items():
        valid_inputs = get_lookup_inputs(source_lookup)
        for input_str in valid_inputs:
            try:
                display_input, output = build_lookup_example(input_str, ops)
                
                if spaced:
                    examples.append({
                        "input": add_spaces(display_input),
                        "output": add_spaces(output),
                        "original_input": display_input,
                        "original_output": output,
                        "category_name": comp_name,
                        "operations": "+".join(ops),
                        "spaced": True,
                    })
                else:
                    examples.append({
                        "input": display_input,
                        "output": output,
                        "category_name": comp_name,
                        "operations": "+".join(ops),
                    })
            except Exception:
                continue
    
    df = pd.DataFrame(examples)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    df.to_csv(output_path, index=False)
    
    # Summary
    string_comps = len(STRING_COMPOSITIONS)
    lookup_comps = len(LOOKUP_COMPOSITIONS)
    total_comps = string_comps + lookup_comps
    
    mode = "spaced" if spaced else "normal"
    approach = "Approach B (strict chains)" if strict_chain else "Approach A (first op's inputs)"
    print(f"Generated {len(examples)} {mode} examples across {total_comps} compositions using {approach}")
    print(f"  - {string_comps} string compositions (pure string ops)")
    print(f"  - {lookup_comps} lookup compositions (translation/morphological + string ops)")
    print(f"Saved to: {output_path}")
    return df


if __name__ == "__main__":
    import sys
    # Generate both normal and spaced CSV files
    if len(sys.argv) > 1 and sys.argv[1] == "--spaced":
        generate_compositional_csv(spaced=True)
    elif len(sys.argv) > 1 and sys.argv[1] == "--all":
        generate_compositional_csv(spaced=False)
        generate_compositional_csv(spaced=True)
    else:
        generate_compositional_csv(spaced=False)