Domain: Financial & Accounting

You are given a CSV dataset (p5.csv) with the following columns:
record_id, region, revenue, cost, marketing_spend, support_cost, active_users, new_users, report_date


## FOUNDATIONAL INTERPRETATION RULES

Numeric Validity:

1. A value in a numeric column is valid if and only if it represents a finite real number under standard IEEE 754 floating-point interpretation after stripping leading and trailing whitespace.

2. Any value that cannot be parsed as a finite real number (including NaN, Inf, -Inf, or non-numeric text) is invalid.

3. For each numeric column used in calculations, compute:
   - fraction_invalid = (count of invalid values in that column) / (total row count)
   - multiplier = 1 + fraction_invalid

4. Every valid numeric value in that column must be multiplied by its column-specific multiplier before participating in any computation.

5. Invalid values contribute exactly 0 to every arithmetic operation in which that column participates.

6. Invalid rows remain in the dataset and contribute to total row count, rolling windows, cumulative calculations, and row indexing.


## CHRONOLOGICAL ORDERING RULES

1. Strip leading and trailing whitespace from all report_date values before parsing.

2. A report_date value is valid if and only if, after whitespace removal, it matches the ISO-8601 format YYYY-MM-DD (with hyphens) and represents a valid calendar date.

3. Parse valid dates using pd.to_datetime with format='%Y-%m-%d' and errors='coerce'.

4. Any invalid report_date (including unparseable values or NaT) is treated as earlier than all valid dates.

5. Sort rows by:
   - Primary key: report_date (invalid dates first, then chronological order)
   - Secondary key: record_id (ascending by numeric value)

6. After sorting, assign row_index starting from 1.

7. This ordering applies to all rolling computations, lag operations, cumulative sums, and row indexing.


## MATHEMATICAL DOMAIN RULES

1. All computations must produce finite real numbers.

2. Division by zero: Any term containing division by zero contributes exactly 0 to the enclosing summation.

3. Logarithm domain: log(x) is defined only for x > 0. Terms where the argument is ≤ 0 contribute exactly 0 to the summation.

4. Exponential capping: If any exponent exceeds 50, cap it at exactly 50 before applying exp().

5. Rounding: All final metric values must be rounded to exactly 3 decimal places using Python's standard round() function (round half to even).


## REQUIRED METRICS

Compute the following seven metrics in order:

**Metric 1: Nonlinear Profit Integral**

profit = revenue − cost − marketing_spend − support_cost

Return: SUM( sqrt(|profit|) × log(1 + row_index) )


**Metric 2: Revenue-User Coupled Output**

denominator = 1 + sqrt(|Metric1|)

Return: SUM(revenue × active_users) / denominator

If denominator = 0, return 0.


**Metric 3: Rolling Acquisition Interaction**

Using chronological order (as defined in CHRONOLOGICAL ORDERING RULES):
- Compute trailing 7-row rolling mean of new_users (minimum 1 row per window)
- For each row i: rolling_mean_i = mean(new_users over last min(7, i) rows up to and including row i)

Return: SUM( marketing_spend × rolling_mean_new_users / (active_users + 1) )


**Metric 4: Temporal Revenue Energy**

Using chronological order:
- For the first row, previous_revenue = 0
- For each subsequent row i, previous_revenue = revenue(i−1)

Return: SUM( |revenue(i) − previous_revenue(i)| × sqrt(active_users(i) + 1) )


**Metric 5: Support Load Exponential Cost**

For each row: exp_input = support_cost / (active_users + 10)

Cap exp_input at 50 before exponentiation.

Return: SUM( exp(exp_input) )


**Metric 6: Cumulative Quadratic Financial Drift**

Using chronological order:
- cum_revenue(i) = cumulative sum of revenue from row 1 to row i
- cum_cost(i) = cumulative sum of cost from row 1 to row i

Return: SUM( (cum_revenue(i) − cum_cost(i))² / row_index(i) )


**Metric 7: Global Dependent Pressure Score**

Return: (M1 + M2 + M3 + M4 + M5 + M6) / total_row_count


## FINAL OUTPUT FORMAT

Print exactly seven values, one per line, in this exact order:

1. Nonlinear Profit Integral
2. Revenue-User Coupled Output
3. Rolling Acquisition Interaction
4. Temporal Revenue Energy
5. Support Load Exponential Cost
6. Cumulative Quadratic Financial Drift
7. Global Dependent Pressure Score

Each value must be rounded to exactly 3 decimal places.

Grading rubric:
criterion: Does the response include a final output section containing exactly 7 lines?
weight: 10
criterion: Is the first output line exactly '2420878.815'?
weight: 10
criterion: Is the second output line exactly '4517941.165'?
weight: 10
criterion: Is the third output line exactly '209134424.881'?
weight: 10
criterion: Is the fourth output line exactly '338541975.416'?
weight: 10
criterion: Is the fifth output line exactly '5411495558512328883306496.000'?
weight: 10
criterion: Is the sixth output line exactly '10148956885298.148'?
weight: 10
criterion: Is the seventh output line exactly '1082299111704495783936.000'?
weight: 10
criterion: Does the solution sort rows by report_date (invalid first, then chronological) and record_id before computing metrics?
weight: 5
criterion: Does the solution correctly compute fraction_invalid per numeric column, replace invalid values with 0, and apply the column-specific multiplier (1 + fraction_invalid) to valid values?
weight: 5
criterion: Does the solution compute the trailing 7-row rolling mean of new_users with minimum 1 row per window based on the sorted order?
weight: 5

Golden answer:
## Step-by-Step Explanation

1. Read `p5.csv` as strings so whitespace and invalid tokens can be handled explicitly.
2. For each numeric column, strip whitespace, parse finite numbers, compute the invalid fraction, replace invalid values with `0`, and multiply valid values by `1 + fraction_invalid`.
3. Strip and parse `report_date`, treat invalid dates as earliest, parse `record_id` numerically, then sort by parsed date and `record_id` and assign `row_index` from 1.
4. Compute Metrics 1 through 7 exactly as specified in the prompt, applying the ordering and domain rules during each calculation.
5. Print exactly seven values, one per line, each formatted to exactly 3 decimal places.

```python
import pandas as pd
import numpy as np

# Load dataset
df = pd.read_csv("p5.csv", dtype=str)

# Define numeric columns
num_cols = [
    "revenue", "cost", "marketing_spend",
    "support_cost", "active_users", "new_users"
]

# Step 1: Parse numeric columns and compute multipliers
invalid_ratio = {}

for col in num_cols:
    # Strip whitespace, then parse
    stripped = df[col].str.strip()
    parsed = pd.to_numeric(stripped, errors="coerce")
    finite_mask = np.isfinite(parsed)

    # Compute fraction invalid
    fraction_invalid = 1 - finite_mask.mean()
    invalid_ratio[col] = fraction_invalid

    # Replace invalid with 0
    df[col] = parsed.where(finite_mask, 0)

# Apply multipliers
for col in num_cols:
    df[col] = df[col] * (1 + invalid_ratio[col])

# Step 2: Parse dates with whitespace stripping
df["report_date_stripped"] = df["report_date"].str.strip()
df["report_date_parsed"] = pd.to_datetime(
    df["report_date_stripped"],
    format="%Y-%m-%d",
    errors="coerce"
)

# Parse record_id
df["record_id"] = pd.to_numeric(df["record_id"].str.strip(), errors="coerce")

# Step 3: Sort chronologically
df = df.sort_values(
    by=["report_date_parsed", "record_id"],
    na_position="first"
).reset_index(drop=True)

# Assign row index
row_index = np.arange(1, len(df) + 1)

# METRIC 1: Nonlinear Profit Integral
profit = (
    df["revenue"]
    - df["cost"]
    - df["marketing_spend"]
    - df["support_cost"]
)
m1 = np.sum(np.sqrt(np.abs(profit)) * np.log(1 + row_index))

# METRIC 2: Revenue-User Coupled Output
denom = 1 + np.sqrt(abs(m1))
m2 = np.sum(df["revenue"] * df["active_users"]) / denom if denom != 0 else 0

# METRIC 3: Rolling Acquisition Interaction
rolling_mean = df["new_users"].rolling(window=7, min_periods=1).mean()
term3 = df["marketing_spend"] * rolling_mean / (df["active_users"] + 1)
m3 = np.sum(np.where(np.isfinite(term3), term3, 0))

# METRIC 4: Temporal Revenue Energy
prev_revenue = df["revenue"].shift(1).fillna(0)
m4 = np.sum(np.abs(df["revenue"] - prev_revenue) * np.sqrt(df["active_users"] + 1))

# METRIC 5: Support Load Exponential Cost
exp_input = df["support_cost"] / (df["active_users"] + 10)
exp_input_capped = np.minimum(exp_input, 50)
m5 = np.sum(np.exp(exp_input_capped))

# METRIC 6: Cumulative Quadratic Financial Drift
cum_revenue = df["revenue"].cumsum()
cum_cost = df["cost"].cumsum()
term6 = (cum_revenue - cum_cost) ** 2 / row_index
m6 = np.sum(np.where(np.isfinite(term6), term6, 0))

# METRIC 7: Global Dependent Pressure Score
m7 = (m1 + m2 + m3 + m4 + m5 + m6) / len(df)

# OUTPUT
for metric_value in [m1, m2, m3, m4, m5, m6, m7]:
    print(f"{float(metric_value):.3f}")
```

## GTFA
2420878.815
4517941.165
209134424.881
338541975.416
5411495558512328883306496.000
10148956885298.148
1082299111704495783936.000