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.
Here's a comprehensive Python implementation of the mathematical model described above:
python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.optimize import curve_fit, minimize
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
from sklearn.linear_model import LinearRegression
import warnings
warnings.filterwarnings('ignore')
# Set plotting style
plt.style.use('seaborn-v0_8')
sns.set_palette("husl")
class NIPTTimingModel:
def __init__(self):
self.K = 0.10 # Asymptotic max Y-fraction
self.fitted_params = None
self.bmi_intervals = None
self.interval_models = {}
def parse_gestational_age(self, ga_str):
"""Convert gestational age string like '11w+6' to decimal weeks"""
try:
if 'w+' in ga_str:
weeks, days = ga_str.replace('w+', ' ').split()
return float(weeks) + float(days) / 7
elif 'w' in ga_str:
return float(ga_str.replace('w', ''))
else:
return float(ga_str)
except:
return np.nan
def logistic_growth(self, t, r, t50):
"""Logistic growth function for Y-chromosome concentration"""
return self.K / (1 + np.exp(-r * (t - t50)))
def logistic_growth_bmi(self, params, t, bmi):
"""BMI-dependent logistic growth"""
alpha0, alpha1, rho0, rho1 = params
t50 = alpha0 + alpha1 * bmi
r = rho0 + rho1 * bmi
return self.K / (1 + np.exp(-r * (t - t50)))
def objective_function(self, params, t_data, bmi_data, cy_data):
"""Objective function for fitting BMI-dependent model"""
predictions = []
for i in range(len(t_data)):
pred = self.logistic_growth_bmi(params, t_data[i], bmi_data[i])
predictions.append(pred)
predictions = np.array(predictions)
return np.sum((cy_data - predictions) ** 2)
def fit_model(self, df):
"""Fit the BMI-dependent logistic growth model"""
print("Fitting BMI-dependent logistic growth model...")
# Filter for valid Y-chromosome data (assuming male fetuses have Y > 0)
df_male = df[df['Y染色体浓度'] > 0].copy()
t_data = df_male['gestational_age_weeks'].values
bmi_data = df_male['孕妇BMI'].values
cy_data = df_male['Y染色体浓度'].values
# Initial parameter guess
initial_params = [12.0, 0.1, 0.5, -0.01] # alpha0, alpha1, rho0, rho1
# Fit the model
result = minimize(self.objective_function, initial_params,
args=(t_data, bmi_data, cy_data),
method='Nelder-Mead')
self.fitted_params = result.x
alpha0, alpha1, rho0, rho1 = self.fitted_params
print(f"Fitted parameters:")
print(f"α₀ (baseline t₅₀): {alpha0:.3f}")
print(f"α₁ (BMI effect on t₅₀): {alpha1:.3f}")
print(f"ρ₀ (baseline growth rate): {rho0:.3f}")
print(f"ρ₁ (BMI effect on growth rate): {rho1:.3f}")
return self.fitted_params
def predict_maturation_time(self, bmi):
"""Predict maturation time for given BMI"""
if self.fitted_params is None:
raise ValueError("Model not fitted yet")
alpha0, alpha1, rho0, rho1 = self.fitted_params
t50 = alpha0 + alpha1 * bmi
r = rho0 + rho1 * bmi
# Solve for t when C_Y(t) = 0.04
maturation_time = t50 + (1/r) * np.log(self.K/0.04 - 1)
return maturation_time
def find_bmi_intervals(self, df, max_intervals=4):
"""Find optimal BMI intervals using change-point analysis"""
print("Finding optimal BMI intervals...")
# Calculate maturation times for each subject
df_unique = df.groupby('孕妇代码').agg({
'孕妇BMI': 'first',
'Y染色体浓度': 'max' # Use max concentration as proxy
}).reset_index()
# Filter for male fetuses
df_unique = df_unique[df_unique['Y染色体浓度'] > 0]
# Predict maturation times
maturation_times = []
for bmi in df_unique['孕妇BMI']:
try:
mat_time = self.predict_maturation_time(bmi)
maturation_times.append(mat_time)
except:
maturation_times.append(np.nan)
df_unique['maturation_time'] = maturation_times
df_unique = df_unique.dropna()
# Simple approach: use quantiles for BMI intervals
bmi_values = df_unique['孕妇BMI'].values
bmi_25 = np.percentile(bmi_values, 25)
bmi_50 = np.percentile(bmi_values, 50)
bmi_75 = np.percentile(bmi_values, 75)
self.bmi_intervals = [
(bmi_values.min(), bmi_25, "Low BMI"),
(bmi_25, bmi_50, "Normal BMI"),
(bmi_50, bmi_75, "High BMI"),
(bmi_75, bmi_values.max(), "Very High BMI")
]
print(f"BMI intervals identified:")
for i, (lower, upper, label) in enumerate(self.bmi_intervals):
print(f"Interval {i+1}: {lower:.1f} - {upper:.1f} kg/m² ({label})")
return self.bmi_intervals
def fit_interval_models(self, df):
"""Fit linear models within each BMI interval"""
print("Fitting models within BMI intervals...")
df_unique = df.groupby('孕妇代码').agg({
'孕妇BMI': 'first',
'Y染色体浓度': 'max'
}).reset_index()
df_unique = df_unique[df_unique['Y染色体浓度'] > 0]
# Calculate maturation times
maturation_times = []
for bmi in df_unique['孕妇BMI']:
try:
mat_time = self.predict_maturation_time(bmi)
maturation_times.append(mat_time)
except:
maturation_times.append(np.nan)
df_unique['maturation_time'] = maturation_times
df_unique = df_unique.dropna()
for i, (lower, upper, label) in enumerate(self.bmi_intervals):
mask = (df_unique['孕妇BMI'] >= lower) & (df_unique['孕妇BMI'] < upper)
interval_data = df_unique[mask]
if len(interval_data) < 3: # Need minimum data points
continue
X = interval_data['孕妇BMI'].values.reshape(-1, 1)
y = interval_data['maturation_time'].values
model = LinearRegression()
model.fit(X, y)
# Calculate safety margin (90th percentile of residuals)
predictions = model.predict(X)
residuals = np.abs(y - predictions)
safety_margin = np.percentile(residuals, 90)
# Recommended NIPT time (max in interval + safety margin)
max_bmi_in_interval = interval_data['孕妇BMI'].max()
recommended_time = model.predict([[max_bmi_in_interval]])[0] + safety_margin
self.interval_models[i] = {
'model': model,
'safety_margin': safety_margin,
'recommended_time': recommended_time,
'r2': r2_score(y, predictions),
'mae': mean_absolute_error(y, predictions),
'rmse': np.sqrt(mean_squared_error(y, predictions)),
'n_samples': len(interval_data)
}
print(f"Interval {i+1} ({label}): R² = {self.interval_models[i]['r2']:.3f}, "
f"RMSE = {self.interval_models[i]['rmse']:.3f}")
def generate_recommendations(self):
"""Generate final NIPT timing recommendations"""
recommendations = []
for i, (lower, upper, label) in enumerate(self.bmi_intervals):
if i in self.interval_models:
model_info = self.interval_models[i]
recommendations.append({
'BMI_Range': f"{lower:.1f} - {upper:.1f}",
'Label': label,
'Recommended_GA_weeks': f"{model_info['recommended_time']:.1f}",
'Safety_Margin_weeks': f"{model_info['safety_margin']:.1f}",
'R_squared': f"{model_info['r2']:.3f}",
'RMSE_weeks': f"{model_info['rmse']:.3f}",
'Sample_Size': model_info['n_samples']
})
return pd.DataFrame(recommendations)
def evaluate_model(self, df):
"""Evaluate overall model performance"""
df_eval = df[df['Y染色体浓度'] > 0].copy()
# Get predictions
predictions = []
actuals = []
for _, row in df_eval.iterrows():
try:
pred = self.logistic_growth_bmi(self.fitted_params,
row['gestational_age_weeks'],
row['孕妇BMI'])
predictions.append(pred)
actuals.append(row['Y染色体浓度'])
except:
continue
predictions = np.array(predictions)
actuals = np.array(actuals)
r2 = r2_score(actuals, predictions)
mae = mean_absolute_error(actuals, predictions)
rmse = np.sqrt(mean_squared_error(actuals, predictions))
print(f"\nOverall Model Performance:")
print(f"R² Score: {r2:.4f}")
print(f"Mean Absolute Error: {mae:.4f}")
print(f"Root Mean Square Error: {rmse:.4f}")
return {'r2': r2, 'mae': mae, 'rmse': rmse}
def plot_results(self, df):
"""Create comprehensive visualization of results"""
fig, axes = plt.subplots(2, 3, figsize=(18, 12))
# Plot 1: Y-concentration vs Gestational Age
df_male = df[df['Y染色体浓度'] > 0]
axes[0,0].scatter(df_male['gestational_age_weeks'], df_male['Y染色体浓度'],
c=df_male['孕妇BMI'], cmap='viridis', alpha=0.6)
axes[0,0].axhline(y=0.04, color='red', linestyle='--', label='4% threshold')
axes[0,0].set_xlabel('Gestational Age (weeks)')
axes[0,0].set_ylabel('Y-chromosome Concentration')
axes[0,0].set_title('Y-chromosome Concentration vs Gestational Age')
axes[0,0].legend()
# Plot 2: Model fit visualization
ga_range = np.linspace(10, 25, 100)
bmi_examples = [25, 30, 35]
colors = ['blue', 'green', 'red']
for bmi, color in zip(bmi_examples, colors):
y_pred = [self.logistic_growth_bmi(self.fitted_params, ga, bmi) for ga in ga_range]
axes[0,1].plot(ga_range, y_pred, color=color, label=f'BMI={bmi}')
axes[0,1].axhline(y=0.04, color='red', linestyle='--', alpha=0.7)
axes[0,1].set_xlabel('Gestational Age (weeks)')
axes[0,1].set_ylabel('Predicted Y-concentration')
axes[0,1].set_title('Model Predictions for Different BMI Values')
axes[0,1].legend()
# Plot 3: BMI vs Predicted Maturation Time
bmi_range = np.linspace(df_male['孕妇BMI'].min(), df_male['孕妇BMI'].max(), 100)
maturation_times = [self.predict_maturation_time(bmi) for bmi in bmi_range]
axes[0,2].plot(bmi_range, maturation_times, 'b-', linewidth=2)
axes[0,2].set_xlabel('BMI (kg/m²)')
axes[0,2].set_ylabel('Predicted Maturation Time (weeks)')
axes[0,2].set_title('BMI vs Predicted Y-chromosome Maturation Time')
# Plot 4: Residuals
df_eval = df[df['Y染色体浓度'] > 0].copy()
predictions = []
actuals = []
for _, row in df_eval.iterrows():
try:
pred = self.logistic_growth_bmi(self.fitted_params,
row['gestational_age_weeks'],
row['孕妇BMI'])
predictions.append(pred)
actuals.append(row['Y染色体浓度'])
except:
continue
residuals = np.array(actuals) - np.array(predictions)
axes[1,0].scatter(predictions, residuals, alpha=0.6)
axes[1,0].axhline(y=0, color='red', linestyle='--')
axes[1,0].set_xlabel('Predicted Values')
axes[1,0].set_ylabel('Residuals')
axes[1,0].set_title('Residual Plot')
# Plot 5: BMI distribution with intervals
axes[1,1].hist(df_male['孕妇BMI'], bins=20, alpha=0.7, edgecolor='black')
for i, (lower, upper, label) in enumerate(self.bmi_intervals):
axes[1,1].axvline(x=lower, color='red', linestyle='--', alpha=0.7)
if i == len(self.bmi_intervals) - 1:
axes[1,1].axvline(x=upper, color='red', linestyle='--', alpha=0.7)
axes[1,1].set_xlabel('BMI (kg/m²)')
axes[1,1].set_ylabel('Frequency')
axes[1,1].set_title('BMI Distribution with Identified Intervals')
# Plot 6: Predicted vs Actual
axes[1,2].scatter(actuals, predictions, alpha=0.6)
min_val = min(min(actuals), min(predictions))
max_val = max(max(actuals), max(predictions))
axes[1,2].plot([min_val, max_val], [min_val, max_val], 'r--', linewidth=2)
axes[1,2].set_xlabel('Actual Y-concentration')
axes[1,2].set_ylabel('Predicted Y-concentration')
axes[1,2].set_title('Predicted vs Actual Values')
plt.tight_layout()
plt.show()
# Main execution
def main():
# Read 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 io import StringIO
df = pd.read_csv(StringIO(data))
# Initialize and run the model
model = NIPTTimingModel()
# Parse gestational age
df['gestational_age_weeks'] = df['检测孕周'].apply(model.parse_gestational_age)
print("Dataset Overview:")
print(f"Total samples: {len(df)}")
print(f"Unique pregnancies: {df['孕妇代码'].nunique()}")
print(f"Male fetus samples (Y > 0): {len(df[df['Y染色体浓度'] > 0])}")
print(f"BMI range: {df['孕妇BMI'].min():.1f} - {df['孕妇BMI'].max():.1f}")
print(f"Gestational age range: {df['gestational_age_weeks'].min():.1f} - {df['gestational_age_weeks'].max():.1f} weeks")
print()
# Fit the model
fitted_params = model.fit_model(df)
print()
# Evaluate model performance
performance = model.evaluate_model(df)
print()
# Find BMI intervals
intervals = model.find_bmi_intervals(df)
print()
# Fit interval models
model.fit_interval_models(df)
print()
# Generate recommendations
recommendations = model.generate_recommendations()
print("Final NIPT Timing Recommendations:")
print("=" * 80)
print(recommendations.to_string(index=False))
print()
# Show some example predictions
print("Example predictions for different BMI values:")
print("-" * 50)
example_bmis = [25, 30, 35]
for bmi in example_bmis:
mat_time = model.predict_maturation_time(bmi)
print(f"BMI {bmi:2d}: Predicted maturation at {mat_time:.1f} weeks")
print()
# Create visualizations
model.plot_results(df)
return model, df, recommendations
if __name__ == "__main__":
model, df, recommendations = main()
This comprehensive implementation includes:
Key Features:
Data Preprocessing: Converts gestational age strings to decimal weeks and filters for relevant data
BMI-Dependent Logistic Model: Implements the mathematical model where both growth rate and inflection point depend on BMI
Model Fitting: Uses numerical optimization to fit the 4-parameter model (α₀, α₁, ρ₀, ρ₁)
BMI Interval Detection: Uses quantile-based approach to identify BMI intervals (can be extended with more sophisticated change-point detection)
NIPT Recommendations: Generates specific timing recommendations for each BMI interval with safety margins
Comprehensive Evaluation: Calculates R², MAE, RMSE for model assessment
Rich Visualizations:
Y-concentration vs gestational age scatter plot
Model predictions for different BMI values
BMI vs predicted maturation time
Residual analysis
BMI distribution with intervals
Predicted vs actual values
Output Includes:
Fitted parameters with biological interpretation
Model performance metrics (R², MAE, RMSE)
BMI interval boundaries and characteristics
Final recommendation table with timing, safety margins, and quality metrics
Visualization suite for model validation and interpretation
The model is designed to be robust, interpretable, and clinically actionable, providing both the mathematical foundation and practical implementation for NIPT timing optimization based on maternal BMI.