Please write the code in Python to read the dataset, fit the functional models mentioned, output the values of intermediate variables and the final result table. If possible, you can also draw some statistics figure to visualize the model and evaluate the quality of the model with necessary statistics figures (such as R-square, MAE, RMSE and etc.)
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Mathematical Modeling for BMI Interval Grouping and NIPT Time Point Determination
I'll create a comprehensive Python solution that implements the mathematical model for determining BMI intervals and NIPT time points. Let's start by loading the data and implementing the model step by step.
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
from sklearn.tree import DecisionTreeRegressor
import statsmodels.api as sm
from scipy import stats
import warnings
warnings.filterwarnings('ignore')
# Load the data
data = """
序号,孕妇代码,年龄,身高,体重,末次月经,IVF妊娠,检测日期,检测抽血次数,检测孕周,孕妇BMI,原始读段数,在参考基因组上比对的比例,重复读段的比例,唯一比对的读段数 ,GC含量,13号染色体的Z值,18号染色体的Z值,21号染色体的Z值,X染色体的Z值,Y染色体的Z值,Y染色体浓度,X染色体浓度,13号染色体的GC含量,18号染色体的GC含量,21号染色体的GC含量,被过滤掉读段数的比例,染色体的非整倍体,怀孕次数,生产次数,胎儿是否健康
1,A001,31,160,72,2023-2-1,自然受孕,20230429,1,11w+6,28.125,5040534,0.8067259,0.0276035,3845411,0.3992619,0.782096634,-2.321211659,-1.026002604,-0.062103083,-1.035610255,0.02593584,0.038061019,0.377068639,0.389803052,0.399399221,0.027483794,,1,0,是
2,A001,31,160,73,2023-2-1,自然受孕,20230531,2,15w+6,28.515625,3198810,0.8063927,0.02827083,2457402,0.3932988,0.692855699,1.168520758,-2.595098987,0.582182673,-0.363518671,0.034886856,0.059572251,0.3715415,0.384770662,0.391706139,0.01961667,,1,0,是
3,A001,31,160,73,2023-2-1,自然受孕,20230625,3,20w+1,28.515625,3848846,0.8038578,0.03259621,2926292,0.3998897,-0.888701998,-1.01823645,-1.308661706,-0.342563969,-0.734502556,0.066171003,0.075994548,0.377449453,0.390582472,0.399479687,0.022312402,,1,0,是
4,A001,31,160,74,2023-2-1,自然受孕,20230716,4,22w+6,28.90625,5960269,0.8025347,0.0347616,4509561,0.3979775,0.498030978,0.770401229,-1.476955143,1.141241591,0.476199842,0.061191623,0.052304751,0.375613302,0.389251351,0.397211552,0.023280157,,1,0,是
5,A002,32,149,74,2023-11-9,自然受孕,20240219,1,13w+6,33.3318319,4154302,0.8050077,0.02885505,3169114,0.40306,-2.268038556,-1.004014711,0.863198247,-0.441235167,-0.889422117,0.059230127,0.059708123,0.380259901,0.393617839,0.404868305,0.024211528,,2,1,否
6,A002,32,149,76,2023-11-9,自然受孕,20240310,2,16w+5,34.23269222,5108640,0.789433944,0.03029017,3809027,0.3994663,-0.101007647,0.857094616,-0.080881433,0.489396003,-0.355106905,0.042401417,0.040477405,0.37738663,0.390281558,0.399466574,0.026017492,,2,1,否
7,A002,32,149,75,2023-11-9,自然受孕,20240401,3,19w+5,33.78226206,5316264,0.7988666,0.02946763,4036843,0.3966289,2.218453681,2.748077329,-0.374887523,2.668303993,1.702886328,0.047824846,0.012477775,0.375590861,0.38777861,0.395050377,0.020620496,,2,1,否
8,A002,32,149,76,2023-11-9,自然受孕,20240429,4,23w+4,34.23269222,6048355,0.8059561,0.03119377,4592406,0.3988559,2.097944904,2.860484949,-0.665511791,1.088384312,0.19120273,0.042674699,0.030226764,0.377183467,0.39021945,0.397856206,0.027578242,T18,2,1,否
9,A002,32,149,76,2023-11-9,自然受孕,20240503,4,23w+4,34.23269222,2868426,0.7916365,0.02855916,2146451,0.4071893,3.178192775,3.590727756,-0.469923175,-0.102283343,-0.73254817,0.047362214,0.025030132,0.386809319,0.398356378,0.409254968,0.026949972,T13T18,2,1,否
10,A003,35,160,78.7,2023-2-20,自然受孕,20230522,1,13w,30.7421875,4890500,0.7876009,0.03065529,3654763,0.403697,0.264484504,0.659325291,2.277738619,0.232680546,-0.394139812,0.05471245,0.039109475,0.381177843,0.394178093,0.403653413,0.02113792,T21,≥3,1,是
11,A003,35,160,78.7,2023-2-20,自然受孕,20230526,1,13w,30.7421875,3811511,0.802652,0.03056164,2903813,0.4035087,0.157044352,2.949829532,0.457317248,-0.106656728,-0.660888238,0.056711486,0.045044466,0.382032991,0.394653052,0.402891219,0.020906932,T18,≥3,1,是
12,A003,35,160,78.7,2023-2-20,自然受孕,20230526,1,13w,30.7421875,4656559,0.8030206,0.03054991,3550546,0.404156,0.516549492,0.154161383,1.045079075,0.873100694,0.320996616,0.065184837,0.033093396,0.38248533,0.395127416,0.405796945,0.020559817,,≥3,1,是
13,A003,35,160,79.72,2023-2-20,自然受孕,20230617,2,16w+5,31.140625,4387822,0.7982068,0.02966877,3323334,0.4011541,-1.053252424,0.929247491,2.553661664,0.940317514,0.330456427,0.063249404,0.04508197,0.377922148,0.391794235,0.401705176,0.02211097,T21,≥3,1,是
14,A003,35,160,81.62,2023-2-20,自然受孕,20230710,3,20w+2,31.8828125,4904188,0.8045821,0.03083594,3738907,0.4036022,-0.35970848,0.427620227,1.750310887,-0.295190931,-0.86251951,0.052252975,0.048962235,0.381531835,0.393619567,0.405541956,0.022290336,,≥3,1,是
15,A003,35,160,82.2,2023-2-20,自然受孕,20230730,4,23w+1,32.109375,3206682,0.8004625,0.02844189,2441783,0.3988536,2.859133505,2.520675204,-0.437330179,2.432942922,1.716977414,0.066498894,0.029758678,0.377228111,0.390149713,0.398328304,0.020867676,T13,≥3,1,是
"""
# Create DataFrame from the string data
from io import StringIO
df = pd.read_csv(StringIO(data))
# Convert gestational age to decimal weeks
def convert_gestational_age(ga_str):
if 'w' in ga_str:
parts = ga_str.split('w')
weeks = int(parts[0])
days = 0
if '+' in parts[1]:
days = int(parts[1].split('+')[1])
return weeks + days/7
return float(ga_str)
df['检测孕周数值'] = df['检测孕周'].apply(convert_gestational_age)
# Filter data for male fetuses (Y chromosome concentration > 0)
df_male = df[df['Y染色体浓度'] > 0].copy()
# For each pregnancy, find the first time Y chromosome concentration exceeds 4%
first_mature_times = []
for woman_id in df_male['孕妇代码'].unique():
woman_data = df_male[df_male['孕妇代码'] == woman_id].sort_values('检测孕周数值')
mature_data = woman_data[woman_data['Y染色体浓度'] > 0.04]
if len(mature_data) > 0:
first_mature = mature_data.iloc[0]
first_mature_times.append({
'孕妇代码': woman_id,
'BMI': first_mature['孕妇BMI'],
'成熟孕周': first_mature['检测孕周数值'],
'Y浓度': first_mature['Y染色体浓度']
})
mature_df = pd.DataFrame(first_mature_times)
print("First mature times for each pregnancy:")
print(mature_df)
print("\n")
# Fit logistic growth model
def logistic_growth(t, K, r, t50):
"""Logistic growth function"""
return K / (1 + np.exp(-r * (t - t50)))
# Prepare data for logistic growth fitting
all_data = []
for woman_id in df_male['孕妇代码'].unique():
woman_data = df_male[df_male['孕妇代码'] == woman_id].sort_values('检测孕周数值')
bmi = woman_data['孕妇BMI'].mean() # Use average BMI for this woman
for _, row in woman_data.iterrows():
all_data.append({
'BMI': bmi,
'GA': row['检测孕周数值'],
'Y_concentration': row['Y染色体浓度']
})
logistic_df = pd.DataFrame(all_data)
# Fit BMI-dependent parameters using nonlinear regression
def bmi_dependent_logistic(t, a0, a1, r0, r1, bmi):
"""Logistic growth with BMI-dependent parameters"""
t50 = a0 + a1 * bmi
r = r0 + r1 * bmi
K = 0.10 # Fixed asymptotic maximum based on biological knowledge
return K / (1 + np.exp(-r * (t - t50)))
# Prepare data for curve fitting
x_data = logistic_df[['GA', 'BMI']].values
y_data = logistic_df['Y_concentration'].values
# Initial parameter guesses
p0 = [10, 0.2, 0.3, -0.005] # a0, a1, r0, r1
# Fit the model
popt, pcov = curve_fit(
lambda t, a0, a1, r0, r1: bmi_dependent_logistic(t, a0, a1, r0, r1, x_data[:, 1]),
x_data[:, 0], y_data, p0=p0, maxfev=10000
)
a0, a1, r0, r1 = popt
print(f"Fitted parameters: a0={a0:.4f}, a1={a1:.4f}, r0={r0:.4f}, r1={r1:.4f}")
# Calculate t(BMI) - the time when Y concentration reaches 4%
K = 0.10
threshold = 0.04
log_term = np.log(K/threshold - 1)
def t_bmi(bmi):
"""Calculate maturation time for a given BMI"""
t50 = a0 + a1 * bmi
r = r0 + r1 * bmi
return t50 - log_term / r
# Calculate predicted maturation times for each BMI in our data
mature_df['预测成熟孕周'] = mature_df['BMI'].apply(t_bmi)
# Evaluate model performance
r2 = r2_score(mature_df['成熟孕周'], mature_df['预测成熟孕周'])
mae = mean_absolute_error(mature_df['成熟孕周'], mature_df['预测成熟孕周'])
rmse = np.sqrt(mean_squared_error(mature_df['成熟孕周'], mature_df['预测成熟孕周']))
print(f"\nModel Performance:")
print(f"R²: {r2:.4f}")
print(f"MAE: {mae:.4f} weeks")
print(f"RMSE: {rmse:.4f} weeks")
# Determine BMI intervals using change point detection
# We'll use a decision tree regressor to find optimal splits
X = mature_df['BMI'].values.reshape(-1, 1)
y = mature_df['预测成熟孕周'].values
# Fit decision tree to find optimal splits
tree = DecisionTreeRegressor(max_leaf_nodes=4, min_samples_leaf=2)
tree.fit(X, y)
# Get the split points (BMI thresholds)
thresholds = np.sort(tree.tree_.threshold[tree.tree_.threshold != -2])
bmi_thresholds = [min(mature_df['BMI'])] + list(thresholds) + [max(mature_df['BMI'])]
bmi_intervals = [(bmi_thresholds[i], bmi_thresholds[i+1]) for i in range(len(bmi_thresholds)-1)]
print(f"\nBMI Intervals: {bmi_intervals}")
# For each interval, calculate the recommended NIPT time
recommendations = []
for i, (bmi_low, bmi_high) in enumerate(bmi_intervals):
# Get data points in this interval
interval_data = mature_df[(mature_df['BMI'] >= bmi_low) & (mature_df['BMI'] <= bmi_high)]
if len(interval_data) > 0:
# Fit linear model for this interval
X_interval = sm.add_constant(interval_data['BMI'])
model = sm.OLS(interval_data['预测成熟孕周'], X_interval).fit()
p, q = model.params
# Calculate 90th percentile of residuals as safety margin
residuals = interval_data['预测成熟孕周'] - model.predict(X_interval)
delta_90 = np.percentile(np.abs(residuals), 90)
# Calculate maximum time in this interval
max_time = max(p + q * bmi_low, p + q * bmi_high)
# Recommended time
recommended_time = max_time + delta_90
recommendations.append({
'BMI Interval': f"[{bmi_low:.2f}, {bmi_high:.2f})",
'Linear Model': f"t = {p:.2f} + {q:.2f}*BMI",
'90% Residual Margin (weeks)': f"{delta_90:.2f}",
'Recommended GA (weeks)': f"{recommended_time:.2f}"
})
# Create results table
results_df = pd.DataFrame(recommendations)
print("\nNIPT Time Recommendations by BMI Interval:")
print(results_df)
# Visualization
plt.figure(figsize=(12, 8))
# Plot 1: Actual vs Predicted maturation times
plt.subplot(2, 2, 1)
plt.scatter(mature_df['BMI'], mature_df['成熟孕周'], alpha=0.7, label='Actual')
plt.scatter(mature_df['BMI'], mature_df['预测成熟孕周'], alpha=0.7, label='Predicted')
plt.xlabel('BMI')
plt.ylabel('Gestational Age (weeks)')
plt.title('Actual vs Predicted Maturation Times')
plt.legend()
plt.grid(True, alpha=0.3)
# Plot 2: Logistic growth curves for different BMIs
plt.subplot(2, 2, 2)
bmi_values = np.linspace(min(mature_df['BMI']), max(mature_df['BMI']), 3)
weeks = np.linspace(10, 25, 100)
for bmi in bmi_values:
t50 = a0 + a1 * bmi
r_val = r0 + r1 * bmi
y_vals = logistic_growth(weeks, K, r_val, t50)
plt.plot(weeks, y_vals, label=f'BMI = {bmi:.1f}')
plt.axhline(y=0.04, color='r', linestyle='--', label='4% Threshold')
plt.xlabel('Gestational Age (weeks)')
plt.ylabel('Y Chromosome Concentration')
plt.title('Logistic Growth Model for Different BMIs')
plt.legend()
plt.grid(True, alpha=0.3)
# Plot 3: Maturation time vs BMI with intervals
plt.subplot(2, 2, 3)
plt.scatter(mature_df['BMI'], mature_df['预测成熟孕周'], alpha=0.7)
# Draw vertical lines for BMI intervals
for threshold in thresholds:
plt.axvline(x=threshold, color='r', linestyle='--', alpha=0.7)
# Draw the continuous t(BMI) function
bmi_range = np.linspace(min(mature_df['BMI']), max(mature_df['BMI']), 100)
t_values = [t_bmi(bmi) for bmi in bmi_range]
plt.plot(bmi_range, t_values, 'g-', alpha=0.7, label='t(BMI) function')
plt.xlabel('BMI')
plt.ylabel('Predicted Maturation Time (weeks)')
plt.title('BMI Intervals and Maturation Time Function')
plt.grid(True, alpha=0.3)
# Plot 4: Residual analysis
plt.subplot(2, 2, 4)
residuals = mature_df['成熟孕周'] - mature_df['预测成熟孕周']
plt.hist(residuals, bins=10, alpha=0.7, edgecolor='black')
plt.axvline(x=0, color='r', linestyle='--')
plt.xlabel('Residuals (weeks)')
plt.ylabel('Frequency')
plt.title('Residual Distribution')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Print model explanation
print("\n" + "="*80)
print("MODEL EXPLANATION")
print("="*80)
print("1. BIOLOGICAL BASIS:")
print(" - Y chromosome concentration follows a logistic growth pattern during pregnancy")
print(" - Higher maternal BMI dilutes fetal cell-free DNA, delaying maturation time")
print(" - The 4% threshold indicates sufficient fetal DNA for accurate NIPT testing")
print()
print("2. MATHEMATICAL MODEL:")
print(" - Logistic growth function: C_Y(t) = K / (1 + exp(-r*(t - t50)))")
print(" - BMI-dependent parameters: t50 = a0 + a1*BMI, r = r0 + r1*BMI")
print(" - Maturation time: t(BMI) = t50(BMI) - (1/r(BMI)) * ln(K/0.04 - 1)")
print()
print("3. STATISTICAL METHODS:")
print(" - Nonlinear regression to estimate parameters a0, a1, r0, r1")
print(" - Decision tree regression to determine optimal BMI intervals")
print(" - Linear modeling within each BMI interval with safety margin based on residuals")
print()
print("4. CLINICAL APPLICATION:")
print(" - For each BMI interval, NIPT is recommended at the calculated gestational age")
print(" - Safety margin ensures >90% of cases have sufficient fetal DNA at recommended time")
print(" - This approach minimizes false negatives and need for retesting")
This code implements the complete mathematical model as described in the blueprint. Let me explain the key components:
Data Preparation: Converts gestational age to decimal weeks and filters for male fetuses.
Logistic Growth Modeling:
Fits a BMI-dependent logistic growth model to the Y chromosome concentration data
Estimates parameters that describe how maturation time changes with BMI
Maturation Time Calculation:
For each BMI, calculates when Y concentration reaches the 4% threshold