python Copy code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.impute import SimpleImputer
from sklearn.metrics import roc_auc_score, mean_absolute_error, mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler
from sklearn.calibration import calibration_curve
from scipy.optimize import minimize_scalar
from scipy import stats
from sklearn.cluster import KMeans
import statsmodels.api as sm
import statsmodels.formula.api as smf
import warnings
warnings.filterwarnings('ignore')
# ---------------------------------------------------
# 1. Load + preprocess
# ---------------------------------------------------
def convert_ga(ga_str):
if isinstance(ga_str, str) and '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
try:
return float(ga_str)
except:
return np.nan
def preprocess_data(path):
df = pd.read_csv(path)
df['GA'] = df['检测孕周'].apply(convert_ga)
df.rename(columns={'孕妇BMI':'BMI','年龄':'Age','身高':'Height','体重':'Weight',
'原始读段数':'RawReads','GC含量':'GC'}, inplace=True)
df['IVF'] = (df['IVF妊娠']!='自然受孕').astype(int)
df['Fault'] = df['染色体的非整倍体'].apply(lambda x: 1 if pd.notna(x) and str(x).strip()!='' else 0)
# Keep analyzable data
df = df.dropna(subset=['GA','BMI','Age','Y染色体浓度'])
# Filter validity
df = df[(df['Y染色体浓度']>0)&(df['Y染色体浓度']<1)]
return df
# Example: df = preprocess_data("your_data.csv")
# ---------------------------------------------------
# 2. Fit model (logit GLM surrogate of Beta regression)
# ---------------------------------------------------
def fit_glm(df):
# scale continuous
scaler = StandardScaler()
scale_cols = ['GA','BMI','Age','Height','Weight','GC','RawReads']
for col in scale_cols:
if col in df.columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
df[scale_cols] = scaler.fit_transform(df[scale_cols].fillna(df[scale_cols].median()))
formula = 'Y染色体浓度 ~ GA + BMI + Age + Height + Weight + GC + RawReads + IVF + Fault'
model = smf.glm(formula, data=df,
family=sm.families.Binomial(link=sm.families.links.logit())).fit()
return model, scaler
# ---------------------------------------------------
# 3. Risk function + optimization
# ---------------------------------------------------
def prob_mature(model, row, ga, threshold=0.04):
row = row.copy()
row['GA'] = ga
mean = model.predict(row)[0]
# approximate distributional uncertainty with phi=100
alpha, beta = mean*100, (1-mean)*100
return stats.beta.sf(threshold, alpha, beta)
def risk_function(ga, model, row, weights=(1,0.2,5)):
p = prob_mature(model,row,ga)
r_failure = 1-p
r_delay=np.log(ga+1e-6)
if ga<12: r_urg = 0
elif ga<28: r_urg=1
else: r_urg=5
return weights[0]*r_failure+weights[1]*r_delay+weights[2]*r_urg
def optimal_nipt_time(model,row,nipt_window=(10,25),target=0.95):
obj=lambda ga:risk_function(ga,model,row)
result=minimize_scalar(obj,bounds=nipt_window,method='bounded')
ga_opt=result.x
# ensure passes probability threshold
gagrid=np.arange(nipt_window[0],nipt_window[1]+0.1,0.1)
try_ga=nipt_window[0]
for g in gagrid:
if prob_mature(model,row,g)>=target:
try_ga=g;break
return max(ga_opt,try_ga)
# ---------------------------------------------------
# 4. Group into BMI intervals (cluster BMI & GAtime)
# ---------------------------------------------------
def cluster_intervals(df,model,n_clusters=3):
profiles = df.groupby('孕妇代码').median().reset_index()
times=[]; bmis=[]
for i,row in profiles.iterrows():
opt=optimal_nipt_time(model,[row])
times.append(opt); bmis.append(row['BMI'])
X=np.vstack([bmis,times]).T
labels=KMeans(n_clusters=n_clusters,random_state=0,n_init=10).fit_predict(X)
profiles['OptGA']=times; profiles['cluster']=labels
recs=[]
for c,grp in profiles.groupby('cluster'):
bmi_lo,bmi_hi=grp['BMI'].min(),grp['BMI'].max()
recGA=grp['OptGA'].max()+0.5
p=prob_mature(model,[grp.iloc[0]],recGA)
recs.append(dict(Cluster=c, BMIInterval=f"[{bmi_lo:.1f},{bmi_hi:.1f}]",
RecommendedGA=recGA, Pmature=p))
return pd.DataFrame(recs),profiles
# ---------------------------------------------------
# 5. Evaluate
# ---------------------------------------------------
def evaluate(df,model):
df=df.copy()
pred=model.predict(df)
gnd=df['Y染色体浓度'].values
mae=mean_absolute_error(gnd,pred)
rmse=np.sqrt(mean_squared_error(gnd,pred))
r2=r2_score(gnd,pred)
return dict(R2=r2, MAE=mae, RMSE=rmse)
# ---------------------------------------------------
# 6. Visualization
# ---------------------------------------------------
def visualize(recs,profiles,metrics):
fig,ax=plt.subplots(1,2,figsize=(12,5))
sns.scatterplot(data=profiles,x="BMI",y="OptGA",hue="cluster",ax=ax[0])
ax[0].set_title("Optimal GA vs BMI (clusters)")
sns.barplot(data=recs,x="BMIInterval",y="RecommendedGA",ax=ax[1])
ax[1].set_title("Final Recommendation per BMI Interval")
plt.show()
print("Performance metrics:",metrics)