File size: 4,095 Bytes
34e468d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import argparse
import random
import re


def parse_count(value):
    """Parse integers with optional K/M/B suffixes (e.g., 50K, 3M)."""
    if isinstance(value, int):
        return value
    if isinstance(value, str):
        text = value.strip().replace('_', '').lower()
        match = re.fullmatch(r'(\d+(?:\.\d+)?)([kmb]?)', text)
        if not match:
            raise argparse.ArgumentTypeError(f"Invalid count: {value}")
        number, suffix = match.groups()
        multipliers = {'': 1, 'k': 1_000, 'm': 1_000_000, 'b': 1_000_000_000}
        return int(float(number) * multipliers[suffix])
    raise argparse.ArgumentTypeError(f"Invalid count type: {type(value)}")


def format_count(value):
    """Format an integer count using K/M/B suffixes for filenames (e.g., 3000 -> 3K)."""
    n = int(value)
    for suffix, factor in [('B', 1_000_000_000), ('M', 1_000_000), ('K', 1_000)]:
        if n >= factor:
            if n % factor == 0:
                return f"{n // factor}{suffix}"
            short = n / factor
            return f"{short:.1f}".rstrip('0').rstrip('.') + suffix
    return str(n)


def parse_task_distribution(tasks_str, default_task='A'):
    """Parse task weights like 'A1C1' into a dict of task -> weight."""
    if tasks_str is None or tasks_str == '':
        return {default_task: 1}
    matches = re.findall(r'([A-I])(\d+)', tasks_str)
    if not matches:
        raise ValueError(f"Invalid task specification: '{tasks_str}'. Expected format like 'A1' or 'A1C1'.")

    weights = {}
    for task, count_str in matches:
        if task in weights:
            raise ValueError(f"Duplicate task ID: {task}")
        count = int(count_str)
        if count <= 0:
            raise ValueError(f"Task {task} ratio must be positive, got {count}")
        weights[task] = count
    return weights if weights else {default_task: 1}


def sample_task(weights, allowed_tasks=None, default_task='A'):
    """Sample a task ID from a weight dict, respecting an allowed set."""
    allowed_set = set(allowed_tasks) if allowed_tasks else set(weights.keys())
    filtered = {k: v for k, v in weights.items() if k in allowed_set}
    if not filtered:
        filtered = {default_task: weights.get(default_task, 1)}

    total = sum(filtered.values())
    r = random.uniform(0, total)
    upto = 0
    for task, weight in filtered.items():
        upto += weight
        if upto >= r:
            return task
    return next(iter(filtered))


def directions_to_turns(direction_seq, start_orientation='E'):
    """Convert absolute NESW directions into relative turns (L/R/F/T) assuming starting orientation east."""
    orientation = start_orientation
    turns = []
    left_of = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
    right_of = {v: k for k, v in left_of.items()}
    opposite_of = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}

    for direction in direction_seq:
        if direction == orientation:
            turn = 'F'
        elif left_of[orientation] == direction:
            turn = 'L'
        elif right_of[orientation] == direction:
            turn = 'R'
        else:
            turn = 'T'
        turns.append(turn)
        orientation = direction

    return turns


def turns_to_directions(turn_seq, start_orientation='E'):
    """Convert relative turns back to absolute NESW directions."""
    orientation = start_orientation
    directions = []
    left_of = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
    right_of = {v: k for k, v in left_of.items()}
    opposite_of = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}

    for turn in turn_seq:
        if turn == 'F':
            new_orientation = orientation
        elif turn == 'L':
            new_orientation = left_of[orientation]
        elif turn == 'R':
            new_orientation = right_of[orientation]
        else:  # 'T'
            new_orientation = opposite_of[orientation]
        directions.append(new_orientation)
        orientation = new_orientation

    return directions