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
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
import pandas as pd
import argparse
import re
import os
import yaml
import numpy as np
import warnings
from pathlib import Path

from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder,KBinsDiscretizer
from skmultilearn.model_selection import iterative_train_test_split

def extract_index_from_filename(filename : str):
    """
    Extract the numeric index from the filename (after first underscore).

    Parameters:
        filename (str): Filename to extract index from.

    Returns:
        str: Extracted index or None if not found.
    """
    match = re.search(r'_(\d+)_', os.path.basename(filename))
    if match:
        return match.group(0).replace("_","") 
    else:
        raise NameError(f"Run file {filename} does not contain the necessary run index information")


def extract_ride_height_from_filename(filename:str):
    """
    Parses the filename to extract front and rear ride heights

    Parameters:
        filename (str): .case Filename

    Returns:
        list[int]: Extracted ride heights
    """
    if re.search(r'(\d+)_(\d+)',os.path.basename(filename)):
        rh = (os.path.basename(filename).split("_")[2][:2]) + (os.path.basename(filename).split("_")[2][2:4])
    else:
        raise NameError(f"Run file {filename} does not contain the necessary ride height information")
    return rh

def get_run_info(run_folder: str, prefix:str) -> list[str]:
        """
        Looks for .npz or .zarr or .vtp or .vtu files and returns a dictionary containing run information
        about the available files

        Parameters:
            run_folder (str): path to the folder containing the preprocessed run files

        Returns:
            available_labels (dict): dictionary containing information about the available run files
                Run # (list[str]): list of available run numbers
                Rh (list[list[int]]): list of available ride heights
        """
        # Find all run files
        patterns = [
            rf"^{re.escape(prefix)}(\d+)\.(?:npz|zarr|vtp|vtu)$",
            rf"^{re.escape(prefix)}(\d+)_(\d+)\.(?:npz|zarr|vtp|vtu)$"
        ]
        pattern = re.compile("(" + ")|(".join(patterns) + ")")
        run_files = [str(f) for f in Path(run_folder).rglob('*') if f.is_file() and re.match(pattern, f.name)]

        if len(run_files) == 0:
            raise ValueError("No valid files found. Exiting.")
        
        # Extract run ids and ride heighs
        run_ids = [extract_index_from_filename(r) for r in run_files]
        rhs = [extract_ride_height_from_filename(r) for r in run_files]

        # Combine the run info
        available_labels = [x + "_" + y for x,y in zip(run_ids,rhs)]

        return available_labels


def parse_cfd_db(csv_file:str,label_cols:list[str],available_labels:list[str])-> pd.DataFrame:
    """
    Reads the CFD result database and parses the necessary columns for train/val/test split
    
    Parameters:
        csv_file (str): path to the .csv file
        label_cols (list[str]): list of columns to extract for stratified splitting
        available_labels (list[str]): list of conjoined Run # and RH information for each available data file
    Returns:
        df (pandas.Dataframe): Dataframe containing only the necessary information for splitting the data
    """

    geometry_cols = ["P", "CA", "OA", "CS", "OS", "AF"]
    columns = list(dict.fromkeys(label_cols + geometry_cols))

    # Load csv reading only selected columns
    df = pd.read_csv(csv_file,sep=";",usecols=columns,dtype=str)

    # Create column joining necessary run information for database filtering 
    df["RH"] = df["FRH"] + df["RRH"]
    df["run_index"] = df["Run #"].str.replace("_","") + "_" + df["RH"]

    # Filter rows based on available vtk files
    df = df.loc[df["run_index"].isin(available_labels)]

    for column in geometry_cols:
        df[column] = pd.to_numeric(df[column], errors="coerce")

    df.reset_index(inplace=True,drop=True)

    return df

def add_rh_info(split: list[str], db: pd.DataFrame, rh: list[str] | None):
    """
        Recompiles the split list by adding ride height information back into the indexes
        Finds all runs matching the given run ids, and adds new elements corresponding to the available ride heights

        Parameters:
            split (list[str]): list of run prefixes without ride height information
            db (pd.DataFrame): database containing information about the available run files
            rh (list[str] | None): ride heights to include, or all available ride heights

        Returns:
            split (list[str]): list of run indexes with associated ride height information
    """
    run_prefixes = db["run_index"].str.split("_").str[0]
    matching_rows = db[run_prefixes.isin(split)]
    if rh:
        matching_rows = matching_rows[matching_rows["RH"].isin(rh)]
    return matching_rows["run_index"].to_list()


def split_by_drag(run_prefixes: list[str], db: pd.DataFrame, drag_rh: str, val_size: float,
                   test_size: float, random_state: int) -> tuple[list[str], list[str], list[str]]:
    """
    Splits run prefixes into train/validation/test using drag coefficient (SCxav) outliers
    measured at one ride height. Outliers (lowest/highest SCxav) fill half of validation and
    half of test; the remaining quota of every split is filled randomly.

    Parameters:
        run_prefixes (list[str]): unique run prefixes to split
        db (pd.DataFrame): database containing run_index, RH and SCxav columns
        drag_rh (str): ride height used to compare SCxav values
        val_size (float): fraction of run_prefixes assigned to validation
        test_size (float): fraction of run_prefixes assigned to test
        random_state (int): seed for the random allocation of non-outlier runs

    Returns:
        train, validation, test (list[str]): run prefixes assigned to each split
    """
    drag_rows = db[db["RH"] == drag_rh].copy()
    drag_rows["run_prefix"] = drag_rows["run_index"].str.split("_").str[0]
    drag_rows = drag_rows[drag_rows["run_prefix"].isin(run_prefixes)]
    if len(drag_rows) != len(run_prefixes):
        raise ValueError(
            f"Expected one {drag_rh} row per run prefix, found "
            f"{len(drag_rows)} rows for {len(run_prefixes)} run prefixes"
        )

    drag_rows["SCxav"] = pd.to_numeric(drag_rows["SCxav"], errors="coerce")
    if drag_rows["SCxav"].isna().any():
        raise ValueError(f"SCxav contains missing or non-numeric values at RH {drag_rh}")

    n = len(drag_rows)
    validation_count = round(n * val_size)
    test_count = round(n * test_size)
    outlier_count = round(n * (val_size + test_size) / 2)
    outlier_count -= outlier_count % 2

    ranked = drag_rows.sort_values("SCxav")
    outliers = pd.concat([ranked.head(outlier_count // 2), ranked.tail(outlier_count // 2)])
    median = drag_rows["SCxav"].median()
    outliers = outliers.assign(distance=(outliers["SCxav"] - median).abs()).sort_values("distance", ascending=False)
    outlier_prefixes = outliers["run_prefix"].to_numpy()
    remaining_prefixes = drag_rows.loc[~drag_rows["run_prefix"].isin(outlier_prefixes), "run_prefix"].to_numpy()

    rng = np.random.default_rng(random_state)
    rng.shuffle(remaining_prefixes)

    validation_outlier_count = validation_count // 2
    test_outlier_count = test_count // 2
    required_outliers = validation_outlier_count + test_outlier_count
    if required_outliers > len(outlier_prefixes):
        raise ValueError("Not enough drag outliers for 50% validation/test allocation")

    # Alternate outliers by extremity, test getting the biggest one first
    ordered_outliers = outlier_prefixes[:required_outliers]
    test = ordered_outliers[0::2].tolist()
    validation = ordered_outliers[1::2].tolist()

    remaining_pool = np.concatenate([remaining_prefixes, outlier_prefixes[required_outliers:]])
    rng.shuffle(remaining_pool)

    validation_fill_count = validation_count - len(validation)
    test_fill_count = test_count - len(test)
    validation.extend(remaining_pool[:validation_fill_count].tolist())
    test.extend(remaining_pool[validation_fill_count:validation_fill_count + test_fill_count].tolist())

    assigned = set(validation) | set(test)
    train = [prefix for prefix in drag_rows["run_prefix"] if prefix not in assigned]
    return train, validation, test


def filter_by_samples(db: pd.DataFrame, samples_csv: str, geometry_cols: list[str]) -> pd.DataFrame:
    """
    Keeps only the runs whose geometry parameters are present in the provided samples file.

    Parameters:
        db (pd.DataFrame): database with geometry parameter columns already extracted
        samples_csv (str): path to a csv listing the desired samples (one row per sample,
            columns ordered as geometry_cols, '#' lines are treated as comments)
        geometry_cols (list[str]): geometry parameter columns to match on

    Returns:
        db (pd.DataFrame): filtered database containing only the requested samples
    """
    samples = pd.read_csv(samples_csv, sep=",", comment="#", header=None, names=geometry_cols)
    samples = samples.astype(float).drop_duplicates()

    db = db.copy()
    db[geometry_cols] = db[geometry_cols].astype(float)

    db = db.merge(samples, on=geometry_cols, how="inner")
    db.reset_index(inplace=True, drop=True)

    if len(db) == 0:
        raise ValueError(f"No runs match the samples listed in {samples_csv}")

    return db

def parse_run_range(run_range_str: str) -> list[str]:
    """
    Parse a run range string into a list of run indices.

    Parameters:
        run_range_str (str): Run range in format 'start-end' (e.g., '100-200')
                            or comma-separated list (e.g., '100,150,200')

    Returns:
        list[str]: List of run indices as strings
    """
    if '-' in run_range_str and ',' not in run_range_str:
        # Handle range format: 'start-end'
        start, end = run_range_str.split('-')
        return [str(i) for i in range(int(start), int(end) + 1)]
    elif ',' in run_range_str:
        # Handle comma-separated list: '100,150,200'
        return [s.strip() for s in run_range_str.split(',')]
    else:
        # Single value
        return [run_range_str.strip()]

def write_split_to_yaml(yaml_dict,output_path):

    for key in yaml_dict.keys():
        yaml_dict[key] = [str(r) if not isinstance(r,str) else r for r in yaml_dict[key] ]

    with open(output_path, 'w') as f:
        yaml.safe_dump(yaml_dict, f, default_flow_style=False,sort_keys=False)

    print(f"YAML split written to {output_path}")

def main():
    # Define default columns to read from csv file
    geometry_cols = ["P","CA","OA","CS","OS","AF"]
    default_cols = ["Run #","FRH","RRH","Body geometry"] + geometry_cols

    parser = argparse.ArgumentParser(
        description="Produces a .yaml file with train/val/test split for the given run files using stratified splitting"
    )
    parser.add_argument("run_folder", help="Folder with e.g. 'run_<id>.npy' files")
    parser.add_argument("csv_file", help="Path to the cfd database")
    parser.add_argument("config_file", type=str, help="save path for the YAML file")
    parser.add_argument("--label_cols",nargs="+",default=default_cols,help="Columns from the cfd database to use for stratification")
    parser.add_argument("--prefix",default="run_",help="Prefix of the files to split. Defaults to 'run_'")
    parser.add_argument("--ignore_rh",action="store_true",help="Ignore ride height information when splitting data")
    parser.add_argument("--samples_csv",help="Optional csv listing the samples to keep (one row per sample, columns ordered P,CA,OA,CS,OS,AF). Only matching runs are split.")
    parser.add_argument("--rh",nargs='+', type=str,help="Ride heights to add to the splits. Ignored when --ignore_rh is not enabled.")
    parser.add_argument("--split_by_drag", action="store_true", help="Split unique geometries using SCxav drag-coefficient outliers instead of stratified sampling.")
    parser.add_argument("--drag_rh", default="3030", help="Ride height used to compare SCxav for --split_by_drag. Defaults to 3030.")
    parser.add_argument("--random_state", type=int, default=42, help="Random seed for --split_by_drag outlier allocation. Defaults to 42.")
    parser.add_argument("--test_run_range",type=str,help="Run index range to assign to test set. Format: 'start-end' (e.g., '100-200') or comma-separated list (e.g., '100,150,200')")

    args = parser.parse_args()

    if args.split_by_drag and args.test_run_range:
        parser.error("--split_by_drag cannot be combined with --test_run_range")

    # Find actually available files
    available_runs = get_run_info(args.run_folder,args.prefix)

    # Ensure necessary columns are parsed from the csv
    label_cols = args.label_cols + [col for col in default_cols if col not in args.label_cols]
    if args.split_by_drag and "SCxav" not in label_cols:
        label_cols.append("SCxav")

    # Parse database
    db = parse_cfd_db(args.csv_file,label_cols,available_runs)

    # Keep only the samples listed in the provided csv file
    if args.samples_csv:
        db = filter_by_samples(db, args.samples_csv, geometry_cols)

    # Copy database for data splitting
    df = db.copy(deep=True)

    # Unique geometries must stay together across splits when RH is ignored or comparing drag
    if args.ignore_rh or args.split_by_drag:
        df.drop_duplicates(subset="Body geometry",inplace=True)
        df["run_index"] = df["run_index"].apply(lambda x: x.split("_")[0])

    if args.split_by_drag:
        val_size = 0.1
        test_size = 0.1
        train, validation, test = split_by_drag(
            df["run_index"].to_list(), db, args.drag_rh, val_size, test_size, args.random_state
        )
    else:
        # Keep only columns necessary from splitting
        keep_cols = ["run_index"] + (["RH"] if not args.ignore_rh else []) + geometry_cols
        df = df[keep_cols]

        # Prepare data for splitting
        continuos_cols = [c for c in geometry_cols if c != "P"]

        with warnings.catch_warnings(record=True) as rw:
            bin_numeric = KBinsDiscretizer(n_bins=15,encode="ordinal",strategy='uniform')
            one_hot_encode = OneHotEncoder(handle_unknown="error",sparse_output=False,)
            col_trans1 = ColumnTransformer(transformers=[("bin_numeric",bin_numeric,continuos_cols)],remainder="passthrough",verbose_feature_names_out=False)
            col_trans2 = ColumnTransformer(transformers=[("one_hot_encode",one_hot_encode,[c for c in df.columns if c != "run_index"])],remainder="drop",verbose_feature_names_out=False)
            pp = Pipeline([("col_trans1",col_trans1),("col_trans2",col_trans2)])
            pp.set_output(transform="pandas")
            one_hot_labels : pd.DataFrame = pp.fit_transform(df) # type: ignore

        # Converting to numpy
        df_run_index = df["run_index"].to_numpy().reshape(-1,1)
        one_hot_labels = one_hot_labels.to_numpy() # type: ignore

        # Handle manual test set assignment if specified
        if args.test_run_range:
            # Parse the run range
            test_run_indices = parse_run_range(args.test_run_range)

            # Clean Run # by removing leading zeros and trailing underscores
            df_cleaned_run_numbers = db["Run #"].str.replace("_","").str.lstrip("0")

            # Create mask for test runs based on cleaned Run # column
            test_mask = np.isin(df_cleaned_run_numbers.to_numpy(), test_run_indices)

            # Split data based on mask
            test = df_run_index[test_mask]
            remaining_df = df_run_index[~test_mask]
            remaining_labels = one_hot_labels[~test_mask]

            if len(test) == 0:
                raise ValueError(f"No runs found in specified test range: {args.test_run_range}")

            # Setup split parameters for train/val only
            train_size = 0.8
            val_size = 0.1

            # Split remaining data into train and validation
            train,_,val,_ = iterative_train_test_split(remaining_df, remaining_labels, test_size=val_size/(train_size+val_size))

            # Flatten ndArrays
            train = train.flatten().tolist()
            validation = val.flatten().tolist()
            test = test.flatten().tolist()
        else:
            # Original splitting logic when no test range is specified
            # Setup split parameters
            train_size = 0.8
            val_size = 0.1
            test_size = (1-val_size-train_size)/(1-train_size)

            # Split data twice
            train,_,x_test_val,y_test_val = iterative_train_test_split(df_run_index,one_hot_labels,test_size=1-train_size)
            val,_,test,_ = iterative_train_test_split(x_test_val,y_test_val,test_size=test_size)

            # Flatten ndArrays
            train = train.flatten().tolist()
            validation = val.flatten().tolist()
            test = test.flatten().tolist()

    # Add ride height information back into the splits
    if args.ignore_rh or args.split_by_drag:
        train = add_rh_info(train,db,args.rh)
        validation = add_rh_info(validation,db,args.rh)
        test = add_rh_info(test,db,args.rh)

    # Print to yaml
    yaml_dict = {
        "train" : train,
        "validation" : validation,
        "test" : test,
    }

    total_entries = sum(len(split) for split in yaml_dict.values())
    entry_proportions = {
        key: 100 * len(split) / total_entries
        for key, split in yaml_dict.items()
    }
    if args.ignore_rh or args.split_by_drag:
        total_prefixes = len({run_id.split("_")[0] for split in yaml_dict.values() for run_id in split})
        prefix_proportions = {
            key: 100 * len({run_id.split("_")[0] for run_id in split}) / total_prefixes
            for key, split in yaml_dict.items()
        }
        print(
            "Split proportions: "
            f"train={prefix_proportions['train']:.1f}%/{entry_proportions['train']:.1f}% "
            f"validation={prefix_proportions['validation']:.1f}%/{entry_proportions['validation']:.1f}% "
            f"test={prefix_proportions['test']:.1f}%/{entry_proportions['test']:.1f}% "
            "(prefixes/entries)"
        )
    else:
        print(
            "Split proportions: "
            f"train={entry_proportions['train']:.1f}% "
            f"validation={entry_proportions['validation']:.1f}% "
            f"test={entry_proportions['test']:.1f}%"
        )

    write_split_to_yaml(yaml_dict, args.config_file)

if __name__ == "__main__":
    main()