# R Socket 서버 - PBPK 시뮬레이션 # Python으로부터 약물 데이터를 받아 PBPK 시뮬레이션 수행 # 필요한 라이브러리 if (!require("jsonlite", quietly = TRUE)) { we install.packages("jsonlite", repos = "http://cran.r-project.org") } library(jsonlite) # 작업 디렉토리 설정 #setwd("/workspace/bio_kmelloddy_all") setwd("C:/Users/hjung/OneDrive/바탕 화면/연합학습/K-Melloddy-master") # PhysioSIm_run_webdemo.R의 run_pbpk_simulation 함수 사용 # 파일 내부의 setwd() 호출을 무시하기 위해 환경 변수 설정 Sys.setenv(PBPK_WORKING_DIR = "/workspace/bio_kmelloddy_all/pbpk_ft") source("pbpk_ft/PhysioSIm_run_webdemo.R") # 전역 변수 초기화 (getPBPKParam, NCA_result_PBPK 등의 함수가 참조) cat("전역 변수 초기화 중...\n") species_select <- "Human" param_organs <- select_param_organs(species_select) param_ACAT <- select_param_ACAT(species_select) param_general <- select_param_general(species_select) param_diss <- select_param_diss(species_select) cat("전역 변수 초기화 완료.\n\n") start_pbpk_server <- function(host = "127.0.0.1", port = 7000, pid_file = ".pbpk_server.pid") { #' PBPK 시뮬레이션 서버 시작 cat("==========================================\n") cat("PBPK 서버 시작\n") cat("==========================================\n") cat("포트:", port, "\n") cat("호스트:", host, "\n") cat("상태: 클라이언트 연결 대기 중...\n") cat("==========================================\n") # PID 파일 저장 pid <- Sys.getpid() writeLines(as.character(pid), pid_file) # 서버 종료 플래그 should_shutdown <- FALSE tryCatch({ # 계속해서 새로운 연결 대기 while (!should_shutdown) { # 각 요청마다 새로운 소켓 연결 생성 server_socket <- tryCatch({ socketConnection( host = host, port = port, server = TRUE, blocking = TRUE, open = "r+b", timeout = 600 # PBPK 시뮬레이션은 시간이 걸릴 수 있음 ) }, error = function(e) { NULL }) if (is.null(server_socket)) { Sys.sleep(1) next } # 클라이언트 요청 처리 tryCatch({ raw_data <- readLines(server_socket, n = 1, warn = FALSE) if (length(raw_data) > 0) { data <- fromJSON(raw_data) # 종료 명령 확인 if (!is.null(data$command) && data$command == "shutdown") { response <- list(status = "success", message = "PBPK server shutting down") writeLines(toJSON(response, auto_unbox = TRUE), server_socket) flush(server_socket) should_shutdown <- TRUE } # PBPK 시뮬레이션 요청 처리 else if (!is.null(data$data)) { drug_data <- data$data cat("클라이언트 연결됨. 약물 데이터 수신:", drug_data$Drug.Name, "\n") cat("PBPK 시뮬레이션 시작...\n") # PBPK 시뮬레이션 실행 pbpk_result <- tryCatch({ run_pbpk_simulation(drug_data_input = drug_data) }, error = function(e) { cat("PBPK 시뮬레이션 오류:", e$message, "\n") list(error = TRUE, message = paste("PBPK error:", e$message)) }) if (!is.null(pbpk_result) && is.null(pbpk_result$error)) { # 성공 응답 - 간단하게 cat("PBPK 시뮬레이션 완료:", drug_data$Drug.Name, "\n") response <- list(status = "success", message = "PBPK prediction completed") } else { # 에러 응답 cat("PBPK 시뮬레이션 실패:", drug_data$Drug.Name, "\n") response <- list( status = "error", message = ifelse(!is.null(pbpk_result$message), pbpk_result$message, "PBPK simulation failed") ) } writeLines(toJSON(response, auto_unbox = TRUE), server_socket) flush(server_socket) } else { # 잘못된 요청 response <- list(status = "error", message = "Invalid request format") writeLines(toJSON(response, auto_unbox = TRUE), server_socket) flush(server_socket) } } }, error = function(e) { # 개별 요청 에러는 무시하고 계속 진행 }) # 연결 종료 close(server_socket) } }, error = function(e) { # 전체 서버 에러 }, finally = { # PID 파일 삭제 if (file.exists(pid_file)) { file.remove(pid_file) } }) } # 서버 시작 if (!interactive()) { cat("PBPK Simulation Server Starting...\n") cat("Port: 7000\n") cat("Working Directory:", getwd(), "\n\n") start_pbpk_server(host = "127.0.0.1", port = 7000, pid_file = "pbpk_ft/.pbpk_server.pid") }