Domain: Business Operations & Analytics

Four data exports are at `/tmp/files/`: `export_a.csv`, `export_b.csv`, `export_c.csv`, `export_d.csv`. They describe flight operations, metrics, maintenance, and aircraft specifications for a regional carrier.

Restrict to January 2023 weekday revenue departures — exclude positioning and deadhead movements — that satisfy every condition: departure hour from 06 through 18 inclusive; odd calendar day; three-minute telemetry cycle aligned to half-minute boundaries (departure minute divisible by 3, departure second exactly 0 or 30); even numeric suffix on the flight identifier. Where duplicate operational records exist for the same flight, retain only the first entry. Consider only aircraft that appear in both the flight operations data and the pre-analysis baseline maintenance records (those logged before the analysis month).

Before computing any metrics, clean the data as follows. In `export_a.csv`, if a row's ops_code is not one of "R", "P", or "D" because the carrier field is missing and the remaining fields have shifted left, shift the affected fields right and infer carrier from the first two characters of "flight_id". In the merged flight table, keep only rows with binary delay flags (0 or 1), non-missing delay values with "delay >= 0", non-missing ground_time values with "ground_time > 0", and non-missing pax values with "pax > 0". In the maintenance data, keep only rows with non-missing flight hours and maintenance hours, both strictly greater than zero.

Compute carrier-normalized delay intensity per aircraft: for each flight, divide its delay by the mean turnaround of all qualifying flights sharing its carrier; then DI = (number of delayed flights / total flights) × mean(carrier-normalized delay) × 100. Rank all qualifying aircraft by DI ascending and divide into tertiles. In the high tertile, compute maintenance yield ratio per aircraft: MYR = Σ flight_hours / mean(maintenance_hours), using only pre-analysis baseline maintenance events (those logged before the analysis month). Select the aircraft with the lowest MYR (ties: lexicographically smallest tail number).

Compute the fleet-wide median delay among all qualifying flights that are flagged as delayed. For the selected aircraft, restrict to flights whose delay exceeds this fleet median and compute: normalized dispersion D = Σᵢ<ⱼ |xᵢ−xⱼ| / (n² x̄) over delay minutes; mean absolute deviation σ = (1/n) Σᵢ |xᵢ − x̄|; M = maximum delay in this restricted set. On all delayed flights for the selected aircraft (not restricted), compute load factor as round(passenger_count / seat_capacity × 100) (nearest integer) using seat capacity from the aircraft specifications file, then L = lower median of load factors — sort ascending, even count → index n//2−1, odd count → middle value. Composite reliability R = 100 (1−D)(1−σ/M)(L/100). Use full-precision (unrounded) D and σ when computing R.

Return a single Python list: [tail_number, D_3dp, σ_1dp, L_int, DI_1dp, MYR_1dp, R_2dp, fleet_median_1dp].

Grading rubric:
criterion: Does the first element equal N330AA?
weight: 5
criterion: Does D equal 0.022?
weight: 10
criterion: Does sigma equal 2.5?
weight: 10
criterion: Does L equal 68?
weight: 5
criterion: Does delay_intensity equal 82.8?
weight: 15
criterion: Does MYR equal 1.5?
weight: 10
criterion: Does R equal 63.75?
weight: 20
criterion: Does the output contain exactly 8 elements in a list?
weight: 10
criterion: Does fleet_median equal 40.0?
weight: 15

Golden answer:
# Explanation

1. Fix shifted rows in `export_a.csv`, deduplicate operational rows, and merge flight records from `export_a.csv` and `export_b.csv`.
2. Pivot `export_c.csv` into maintenance events with `flight_hours` and `maintenance_hours`, then keep only pre-analysis baseline maintenance events.
3. Apply the prompt's validity rules for delay flags, delay values, turnaround time, passenger counts, and maintenance hours.
4. Compute carrier-normalized delay intensity (DI), split aircraft into tertiles, and select the high-tertile aircraft with the lowest maintenance yield ratio (MYR).
5. Compute the fleet-wide delayed-flight median, then calculate `D`, `sigma`, `L`, and `R` for the selected aircraft.

# Code
```python
import pandas as pd
import numpy as np
from itertools import combinations

# Load all four exports
export_a = pd.read_csv("export_a.csv")
export_b = pd.read_csv("export_b.csv")
export_c = pd.read_csv("export_c.csv")
export_d = pd.read_csv("export_d.csv")

# Pandas 3.x is stricter about dtype-preserving assignment, so cast to object
# before repairing rows whose fields shifted left after a missing carrier value.
for col in export_a.columns:
    export_a[col] = export_a[col].astype(object)

shifted = ~export_a["ops_code"].astype(str).str.strip().isin(["R", "P", "D"])
if shifted.any():
    cols = ["carrier", "origin", "destination", "aircraft_type", "ops_code", "sched_delay_min"]
    for i in range(len(cols) - 1, 0, -1):
        export_a.loc[shifted, cols[i]] = export_a.loc[shifted, cols[i - 1]].values
    export_a.loc[shifted, "carrier"] = export_a.loc[shifted, "flight_id"].str[:2]

for col in export_d.select_dtypes(include=["object", "string"]).columns:
    export_d[col] = export_d[col].astype(str).str.strip()

# Keep the first duplicate operational record per flight_id.
export_b = export_b.drop_duplicates(subset="fid", keep="first")

flights = export_a.merge(export_b, left_on="flight_id", right_on="fid", how="inner")
flights = flights.rename(
    columns={
        "flag": "delay_flag",
        "delay": "delay_minutes",
        "ground_time": "turnaround_minutes",
        "pax": "passenger_count",
    }
)
flights = flights.drop(columns=["fid"])

maint_long = export_c[export_c["dimension"].isin(["airborne", "ground"])].copy()
maint = maint_long.pivot_table(
    index=["aircraft", "event_ref", "obs_date", "station", "check_level"],
    columns="dimension",
    values="measure",
    aggfunc="first",
).reset_index()
maint.columns.name = None
maint = maint.rename(
    columns={
        "aircraft": "tail_number",
        "airborne": "flight_hours",
        "ground": "maintenance_hours",
    }
)

for col in flights.select_dtypes(include=["object", "string"]).columns:
    flights[col] = flights[col].astype(str).str.strip()
for col in maint.select_dtypes(include=["object", "string"]).columns:
    maint[col] = maint[col].astype(str).str.strip()

flights = flights[flights["tail_number"].ne("") & flights["tail_number"].ne("nan")]
maint = maint[maint["tail_number"].ne("") & maint["tail_number"].ne("nan")]

flights = flights[flights["ops_code"] == "R"]

flights["departure_ts"] = pd.to_datetime(flights["departure_ts"], errors="coerce")
flights = flights.dropna(subset=["departure_ts"])
flights["departure_date"] = pd.to_datetime(flights["departure_date"], errors="coerce")
flights = flights.dropna(subset=["departure_date"])
flights = flights[flights["departure_ts"].dt.date == flights["departure_date"].dt.date]

flights["delay_flag"] = pd.to_numeric(flights["delay_flag"], errors="coerce")
flights = flights[flights["delay_flag"].isin([0, 1])]


def clean_numeric(series):
    stripped = series.astype(str).str.replace(r"[^0-9.\-]", "", regex=True)
    return pd.to_numeric(stripped, errors="coerce")


for col in ["delay_minutes", "turnaround_minutes", "passenger_count"]:
    flights[col] = clean_numeric(flights[col])
for col in ["flight_hours", "maintenance_hours"]:
    maint[col] = clean_numeric(maint[col])

flights = flights[flights["delay_minutes"].notna() & (flights["delay_minutes"] >= 0)]
flights = flights[flights["turnaround_minutes"].notna() & (flights["turnaround_minutes"] > 0)]
flights = flights[flights["passenger_count"].notna() & (flights["passenger_count"] > 0)]
maint = maint[maint["flight_hours"].notna() & (maint["flight_hours"] > 0)]
maint = maint[maint["maintenance_hours"].notna() & (maint["maintenance_hours"] > 0)]

flights = flights[(flights["departure_ts"].dt.year == 2023) & (flights["departure_ts"].dt.month == 1)]
flights = flights[flights["departure_ts"].dt.dayofweek < 5]
flights = flights[flights["departure_ts"].dt.day % 2 == 1]
flights = flights[flights["departure_ts"].dt.hour.between(6, 18)]
flights = flights[flights["departure_ts"].dt.minute % 3 == 0]
flights = flights[flights["departure_ts"].dt.second.isin([0, 30])]
flights["fid_num"] = flights["flight_id"].str.extract(r"(\d+)$").astype(float)
flights = flights[flights["fid_num"] % 2 == 0].drop(columns=["fid_num"])

maint["obs_date_dt"] = pd.to_datetime(maint["obs_date"], errors="coerce")
maint = maint[maint["obs_date_dt"] < "2023-01-01"]

common = set(flights["tail_number"].unique()) & set(maint["tail_number"].unique())
flights = flights[flights["tail_number"].isin(common)]
maint_f = maint[maint["tail_number"].isin(common)]

carrier_stats = flights.groupby("carrier").agg(
    carrier_mean_turn=("turnaround_minutes", "mean")
).reset_index()
flights = flights.merge(carrier_stats, on="carrier", how="left")
flights["norm_delay"] = flights["delay_minutes"] / flights["carrier_mean_turn"]

di = flights.groupby("tail_number").agg(
    total=("flight_id", "count"),
    delayed=("delay_flag", "sum"),
    mean_norm=("norm_delay", "mean"),
).reset_index()
di["di"] = (di["delayed"] / di["total"]) * di["mean_norm"] * 100.0
di = di.sort_values("di").reset_index(drop=True)

n = len(di)
b = n // 3
r = n % 3
if r == 0:
    sizes = [b, b, b]
elif r == 1:
    sizes = [b, b, b + 1]
else:
    sizes = [b, b + 1, b + 1]
di["tertile"] = ["Low"] * sizes[0] + ["Mid"] * sizes[1] + ["High"] * sizes[2]
high = di[di["tertile"] == "High"]

myr_rows = []
for tail_number in high["tail_number"]:
    m = maint_f[maint_f["tail_number"] == tail_number]
    myr_rows.append(
        {
            "tail_number": tail_number,
            "myr": m["flight_hours"].sum() / m["maintenance_hours"].mean(),
        }
    )
myr_df = pd.DataFrame(myr_rows).sort_values(["myr", "tail_number"]).reset_index(drop=True)
selected = myr_df.iloc[0]["tail_number"]

fleet_median_delay = float(flights[flights["delay_flag"] == 1]["delay_minutes"].median())

sel = flights[flights["tail_number"] == selected]
sel_above = sel[sel["delay_minutes"] > fleet_median_delay]
vals = sel_above["delay_minutes"].values
mean_v = np.mean(vals)

if mean_v > 0 and len(vals) >= 2:
    pair_sum = sum(abs(vals[i] - vals[j]) for i, j in combinations(range(len(vals)), 2))
    D = pair_sum / (len(vals) ** 2 * mean_v)
else:
    D = 0.0

sigma = float(np.mean(np.abs(vals - mean_v)))
M = float(np.max(vals))

ac_type = sel["aircraft_type"].iloc[0].strip()
max_pax_row = export_d[export_d["type_code"] == ac_type]
max_pax = int(max_pax_row.iloc[0]["max_pax"]) if len(max_pax_row) > 0 else 200

delayed_pax = sel[sel["delay_flag"] == 1]["passenger_count"].values
load_factors = np.sort(np.array([int(round(p / max_pax * 100)) for p in delayed_pax]))
if len(load_factors) % 2 == 1:
    L = int(load_factors[len(load_factors) // 2])
else:
    L = int(load_factors[len(load_factors) // 2 - 1])

di_val = round(float(high[high["tail_number"] == selected]["di"].values[0]), 1)
myr_val = round(float(myr_df[myr_df["tail_number"] == selected]["myr"].values[0]), 1)
R = 100.0 * (1.0 - D) * (1.0 - sigma / M) * (L / 100.0)

result = [
    selected,
    float(round(D, 3)),
    float(round(sigma, 1)),
    int(L),
    float(di_val),
    float(myr_val),
    float(round(R, 2)),
    float(round(fleet_median_delay, 1)),
]
print(result)
```

# Output
```text
['N330AA', 0.022, 2.5, 68, 82.8, 1.5, 63.75, 40.0]
```