import pandas as pd
import rpy2.robjects as ro
from rpy2.robjects.packages import importr
import os
current_directory = os.getcwd()
print('单阶段/Simon's 2 阶段 Phase II 样本量计算 - Python程序 \nby Lokyshin\n')
# 请注意,该程序是python调用R的clinfun实现。
# reference: https://cran.r-project.org/web/packages/clinfun
# 载入需要的R包
clinfun = importr('clinfun')
# 定义变量
pu = 0.58 #unacceptable response rate
pa = 0.8 #response rate that is desirable
alpha = 0.05
power = 0.85
beta = 1 - power
png_filepath = os.path.join(current_directory, "simon2stage.png")
# 执行R代码
ro.r(f'''
png("{png_filepath}", res = 150, 800, 800)
n_stage_one = ph2single({pu}, {pa}, {alpha}, {beta})
n_stage_simon_two =ph2simon({pu}, {pa}, {alpha}, {beta})
plot(n_stage_simon_two)
dev.off()
''')
result_single_stage = ''
print(f'\n基于您期望的率从 {pu} 提高到 {pa},alpha = {alpha} 和Power = {power},样本量计算如下 \n')
# 一阶段的计算
n_stage_1_table_rdf = ro.r('n_stage_one')# 获取R的data.frame
result_single_stage += '\n 单阶段的样本量计算\n\n'
n_stage_1_table_df = pd.DataFrame(ro.conversion.rpy2py(n_stage_1_table_rdf)).T
n_stage_1_table_df.columns = ['n', 'r', 'Type I error', 'Type II error']
n_stage_1_table_df['Type II error']= 1 - n_stage_1_table_df['Type II error']
n_stage_1_table_df.columns = ['n', 'r', 'alpha', 'Power']
result_single_stage += f" Exact single stage Phase II design\n\n"
result_single_stage += f"Unacceptable response rate: {pu}\n"
result_single_stage += f"Desirable response rate: {pa}\n"
result_single_stage += f"Error rates: alpha = {alpha} ; beta = {beta:.2f}\n\n"
result_single_stage += n_stage_1_table_df.to_string()
# Simon两阶段的计算
result_simon = ''
n_stage_2_table = ro.r('n_stage_simon_two')# 获取R的数据
result_simon += '\n\n Simon II 阶段样本量计算\n'
result_simon += str(n_stage_2_table)
print(result_single_stage)
print(result_simon)
print('\n感谢您使用本程序进行统计分析,再见。\n')