File size: 13,684 Bytes
128403f f137b36 128403f f137b36 128403f f137b36 128403f 772c682 128403f f137b36 128403f f137b36 128403f f137b36 128403f 772c682 128403f f137b36 128403f f137b36 128403f 772c682 128403f d6b88c2 128403f 772c682 128403f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
"""
Gradio user interface for AIM-CU
Disclaimer:
This software and documentation was developed at the Food and Drug Administration (FDA) by employees of the Federal Government in the course of their official duties. Pursuant to Title 17, Section 105 of the United States Code, this work is not subject to copyright protection and is in the public domain. Permission is hereby granted, free of charge, to any person obtaining a copy of the Software, to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, or sell copies of the Software or derivatives, and to permit persons to whom the Software is furnished to do so. FDA assumes no responsibility whatsoever for use by other parties of the Software, its source code, documentation or compiled executables, and makes no guarantees, expressed or implied, about its quality, reliability, or any other characteristic. Further, use of this code in no way implies endorsement by the FDA or confers any advantage in regulatory decisions. Although this software can be redistributed and/or modified freely, we ask that any derivative works bear some notice that they are derived from it, and any modified versions bear some notice that they have been modified.
"""
import os
import sys
import pandas as pd
import gradio as gr
import tomli
from cusum import CUSUM
from ARLTheoretical import get_ref_value, get_ref_value_k, get_ARL_1, get_ARL_1_h_mu1_k
from utils import (
populate_summary_table_ARL0_k,
populate_summary_table_ARL1_k,
)
import great_tables as gt
import plotly.graph_objects as go
def set_init_days(
file_csv_metric: gr.File, init_days: str
) -> tuple[float, float, go.Figure]:
"""
Set number of baseline observations and get in-control mean and standard deviation.
Args:
file_csv_metric (gr.File): CSV file with metric data
init_days (str): Number of baseline observations to calculate in-control mean and standard deviation
Returns:
tuple[float, float, go.Figure]: In-control mean and standard deviation, and observation data plot.
"""
init_days = int(init_days)
data_csv_metric = pd.read_csv(file_csv_metric.name)
obj_cusum.set_df_metric_csv(data_csv_metric)
obj_cusum.set_init_stats(init_days=init_days)
return (
"{:.2f}".format(obj_cusum.in_mu),
"{:.2f}".format(obj_cusum.in_std),
obj_cusum.plot_input_metric_plotly_raw(),
)
def populate_table(h: str) -> tuple[gt.GT, gt.GT]:
"""
Populate tables for ARL0 and ARL1 given the value of h
Args:
h (str): Normalized threshold.
Returns:
tuple[gt.GT, gt.GT]: Table for ARL0 and k in HTML format; table for ARL1 and k in HTML format.
"""
h = float(h)
summary_table_df_ARL0_k, dict_ARL0_k = get_ref_value(
h=h,
list_ARL_0=config["params_cusum"]["list_ARL_0"],
)
summary_table_df_ARL0_k = summary_table_df_ARL0_k.applymap(
lambda x: "{:.2f}".format(x) if isinstance(x, (float)) else x
)
summary_table_df_ARL1_k = get_ARL_1(
h=h,
shift_in_mean=config["params_cusum"]["shift_in_mean"],
dict_ARL0_k=dict_ARL0_k,
)
summary_table_df_ARL1_k = summary_table_df_ARL1_k.applymap(
lambda x: "{:.2f}".format(x) if isinstance(x, (float)) else x
)
return populate_summary_table_ARL0_k(
summary_table_df_ARL0_k, h
), populate_summary_table_ARL1_k(summary_table_df_ARL1_k, dict_ARL0_k, h)
def calculate_reference_value_k(h: str, arl_0: str) -> float:
"""
Gets the reference value for given h and ARL_0.
Args:
h (str): Normalized threshold.
arl_0 (str): ARL0 value.
Returns:
float: Normalized reference value k.
"""
h = float(h)
arl_0 = float(arl_0)
k = get_ref_value_k(h=h, ARL_0=arl_0)
k = "{:.2f}".format(k)
return k, k, k
def calculate_arl1_h_k_mu1(h: str, k: str, mu1: str) -> float:
"""
Get the ARL_1 with given Shift in Mean (mu1) and k.
Args:
h (str): Normalized threshold.
k (str): Normalized reference value.
mu1 (str): Intended shift in mean.
Returns:
float: Detection delay (ARL1).
"""
h = float(h)
k = float(k)
mu1 = float(mu1)
arl_1 = get_ARL_1_h_mu1_k(h=h, k=k, mu1=mu1)
arl_1 = "{:.2f}".format(arl_1)
return arl_1
def populate_cusum_plots(
ref_value: str, normalized_threshold: str
) -> tuple[go.Figure, go.Figure]:
"""
Populate CUSUM plots
Args:
ref_value (str): Normalized reference value for detecting a unit standard deviation change in mean of the process.
normalized_threshold (str): Normalized threshold.
Returns:
tuple[go.Figure, go.Figure]: Scatter plot as Plotly graph object; CUSUM plot using Plotly graph object.
"""
ref_value = float(ref_value)
normalized_threshold = float(normalized_threshold)
obj_cusum.change_detection(
normalized_ref_value=ref_value,
normalized_threshold=normalized_threshold,
)
return (obj_cusum.plot_input_metric_plotly(), obj_cusum.plot_cusum_plotly())
with gr.Blocks(
theme=gr.themes.Base(
neutral_hue=gr.themes.Color(
c50="#e5f1f8",
c100="#e5f1f8",
c200="#cce4f1",
c300="#b2d7ea",
c400="#7fbddc",
c500="#4ca3ce",
c600="#007cba",
c700="#006394",
c800="#004a6f",
c900="#00314a",
c950="#001825",
),
)
) as demo:
gr.Markdown(f"""
# AIM-CU
## AIM-CU: A statistical tool for AI monitoring using cumulative sum (AIM-CU).
""") # noqa: F541
gr.Markdown(f"""
### AIM-CU Input:
AI output (e.g. metrics such as Accuracy, F1-score, Sensitivity etc.)
""") # noqa: F541
with gr.Row():
with gr.Column():
gr.Markdown(f"""
### Initialization:
""") # noqa: F541
gr.Markdown(f"""
### Upload the AI output.
""") # noqa: F541
# load the CSV file with specifities across days
csv_file_metric = gr.File(
label="Upload the AI output (CSV file)",
)
with gr.Row():
with gr.Column():
init_days = gr.Textbox(label="Number of baseline observations", placeholder="30")
with gr.Column():
button_calculate_incontrol_params = gr.Button(
"Calculate parameters"
)
with gr.Row():
with gr.Column():
in_control_mean = gr.Textbox(
label="In-control mean", interactive=False
)
with gr.Column():
in_control_std = gr.Textbox(
label="In-control standard deviation", interactive=False
)
plot_observation_data = gr.Plot(label="AI output", visible=False)
gr.Markdown(f"""
Parameter choices for detecting change and detection delay estimates (theoretical calculations).
""") # noqa: F541
gr.Markdown(f"""
### Enter h value:
""") # noqa: F541
h_phase1 = gr.Textbox(
label="h value =",
placeholder="h = normalized threshold, default = 4. Range: between 4 and 5 ([4, 5])",
value="3",
autofocus=True,
)
dataframe_gt_ref_value = gr.HTML(
label="Reference Values for an intended ARL0 with normalized threshold h",
show_label=True,
visible=False,
)
gr.Markdown(f"""
### Calculate reference value k for a specific value for ARL<sub>0</sub>:
""") # noqa: F541
with gr.Row():
arl_0 = gr.Textbox(
label="ARL_0 value =", placeholder="ARL_0", value="100"
)
button_calculate_k = gr.Button("Calculate k")
output_k = gr.Textbox(label="Calculated k =", visible=False)
dataframe_gt_ARL0 = gr.HTML(
label="Estimate of steady state ARL (ARL_1 based on the computed reference values and intended zero-state ARL (ARL_0) with normalized threshold h)",
show_label=True,
visible=False,
)
gr.Markdown(f"""
### Calculate ARL<sub>1</sub> for reference value h, value k and shift in mean:
""") # noqa: F541
with gr.Row():
k_phase1 = gr.Textbox(
label="k value =", placeholder="k", value="0.2996"
)
mu1 = gr.Textbox(
label="Shift in mean value =",
placeholder="Shift in mean value",
value="1.2",
)
button_calculate_ARL_1 = gr.Button("Calculate ARL_1")
output_ARL_1 = gr.Textbox(label="Calculated ARL_1 =", visible=False)
button_populate_table = gr.Button(
"Populate Reference Values and ARL_1 tables for the given h value"
)
gr.Markdown(f"""
### Workflow:
Phase I:
- Upload the AI output (CSV file).
- Enter number of baseline observations.
- Calculate parameters.
- Check parameter choices in Phase 1, for Phase 2. (optional)
Phase II:
- Enter h and k values.
- Get CUSUM plots.
""") # noqa: F541
table_param_description = gr.Dataframe(
value=pd.read_csv("../../assets/params.csv")
)
with gr.Column():
gr.Markdown(f"""
### Monitoring:
Performance drift detection plots, pre- and post-change distribution with respect to the performance drift detected.
""") # noqa: F541
gr.Markdown(f"""
### Enter required values:
""") # noqa: F541
with gr.Row():
h_phase2 = gr.Textbox(
label="h value =",
placeholder="normalized threshold, default = 4. Range: between 4 and 5 ([4, 5])",
value="3",
)
k_phase2 = gr.Textbox(
label="k value =",
placeholder="normalized reference value, default = 0.5",
value="0.5",
)
button_csv_metric = gr.Button("Show CUSUM plots")
plot_avg_metric = gr.Plot(
label="AI model performance",
visible=False,
)
plot_cusum_chart = gr.Plot(label="CUSUM Chart", visible=False)
button_calculate_incontrol_params.click(
fn=set_init_days,
inputs=[csv_file_metric, init_days],
outputs=[in_control_mean, in_control_std, plot_observation_data],
)
button_calculate_incontrol_params.click(
fn=lambda: gr.update(visible=True), inputs=[], outputs=plot_observation_data
)
# Get the CSV file and populate tables
button_populate_table.click(
fn=populate_table,
inputs=[h_phase1],
outputs=[dataframe_gt_ref_value, dataframe_gt_ARL0],
)
button_populate_table.click(
fn=lambda: gr.update(visible=True), inputs=[], outputs=dataframe_gt_ref_value
)
button_populate_table.click(
fn=lambda: gr.update(visible=True), inputs=[], outputs=dataframe_gt_ARL0
)
# Calculate specific k for ARL_0
button_calculate_k.click(
fn=calculate_reference_value_k, inputs=[h_phase1, arl_0], outputs=[output_k, k_phase1, k_phase2]
)
button_calculate_k.click(
fn=lambda: gr.update(visible=True), inputs=[], outputs=output_k
)
# Calculate specific ARL_1 for value h, value k and shift in mean
button_calculate_ARL_1.click(
fn=calculate_arl1_h_k_mu1,
inputs=[h_phase1, k_phase1, mu1],
outputs=[output_ARL_1],
)
button_calculate_ARL_1.click(
fn=lambda: gr.update(visible=True), inputs=[], outputs=output_ARL_1
)
# Get the CSV file and populate plots
button_csv_metric.click(
fn=populate_cusum_plots,
inputs=[k_phase2, h_phase2],
outputs=[plot_avg_metric, plot_cusum_chart],
)
button_csv_metric.click(
fn=lambda: gr.update(visible=True), inputs=[], outputs=plot_avg_metric
)
button_csv_metric.click(
fn=lambda: gr.update(visible=True), inputs=[], outputs=plot_cusum_chart
)
try:
path_file_config = os.path.abspath("../../config/config.toml")
with open(path_file_config, "rb") as file_config:
config = tomli.load(file_config)
except FileNotFoundError:
print("Error: config.toml not found at", path_file_config)
sys.exit(1)
if config["control"]["save_figure"] == "true":
path_check = os.path.abspath(
os.path.join("../../", config["path_output"]["path_figure"])
)
if not os.path.exists(path_check):
os.mkdir(path_check)
print("Created", path_check)
obj_cusum = CUSUM()
obj_cusum.initialize()
demo.launch(server_name="0.0.0.0", server_port=7860)
|