Learn R Programming

⚠️There's a newer version (1.0.0) of this package.Take me there.

Installation

Available from CRAN with the following R script, which installs the released version of BayesianFROC .


              install.packages("BayesianFROC")
              
              
#     Pleaes execute it from the R console or the R studio console.

Shiny Based GUIs

A single reader and a single modaity case


                           library(BayesianFROC)
                           BayesianFROC::fit_GUI_Shiny()

Multiple Readers and Mutiple Modalities Case


                           library(BayesianFROC)
                           BayesianFROC::fit_GUI_Shiny_MRMC()

For details

  • See vignettes (For package size restriction (< 5Mb), it is omitted.)

  • A pre-print of the author: Bayesian Models for Free-response Receiver Operating Characteristic Analysis

Goal of this package BayesianFROC

Comparison of modality. In some context, modality is imaging methods: MRI, CT, PET,…etc, and the another context, if images are taken for treatment (case) group and untreatment (or another treatment) (control) group, then modality means efficacy of treatment.

  • Fitting: data is the following two type
    • Single Reader and Single Modality case.
    • Multiple Reader and Multiple modality case (MRMC)
  • Comparison of the modalities by AUC (the area under the AFROC curve).

Example

  • Build Data
    • Convert from Jafroc data
    • make a dataset
  • Fit
    • draw FROC curves using a fitted model object
    • Calculates AUCs
  • Validation
    • goodness of fit
    • posterior predictive p value (PPP)
    • SBC
    • comparison of truth by replicating datasets from true model

This is an example dataset;

Confidence LevelNumber of HitsNumber of False alarms
3 = definitely present971
2 = equivocal3214
1 = questionable3174

where hit means True Positive: TP and false alarm means False Positive: FP.


#0) To avoid the following error in Readme file,
#I have to attach the Rcpp. 
#I do not know why such error occur withou Rcpp. 
#This error occurs only when I run the following R scripts from readme.

#Error
#in do.call(rbind,sampler_params) :second argument must be a list Calles:<Anonymous>...get_divergent_iterations ->sampler_param_vector =. do.call Execution halted

 library(Rcpp)  # This code can remove the above unknown error, if someone know why the error occur, please tell me.




 library(BayesianFROC)


#1) Build  data for singler reader and single modality  case.




  dataList <- list(c=c(3,2,1),     # c is ignored, can omit.
              h=c(97,32,31),
              f=c(1,14,74),
              NL=259,
              NI=57,
              C=3)





#  where,
#        c denotes confidence level, each components indicates that 
#                3 = Definitely lesion,
#                2 = subtle,  
#                1 = very subtle
#        h denotes number of hits 
#          (True Positives: TP) for each confidence level,
#        f denotes number of false alarms
#          (False Positives: FP) for each confidence level,
#        NL denotes number of lesions (signal),
#        NI denotes number of images,


  
  
  
  
  
  
  
  
  
  
  
  
  
#2) Fit the FROC model.


 
   fit <- BayesianFROC::fit_Bayesian_FROC(
     
            # data to which we fit a model                 
                dataList = dataList,
                                        
            # The number of MCMC chains                         
                     cha = 4,
            
            # The number of MCMC samples for each chains                         
                    ite  = 11111,
                    
            # The number of warming up of MCMC simulation for each chains           
                     war = 1111,
            
            # Show verbose summary and MCMC process
                 summary = TRUE
                                                         )

                  
                  
                  
                  
                  
                  

#  validation of fit via alculation of p -value of the chi square goodness of fit, which is 
#  calculated by integrating with  predictive posterior measure.
                  
                  
            BayesianFROC::ppp(
              fit
              )
                   
                   # The auhor thinks it is not correctly programmed, so it needs validaton of programing

                                     
                  

Jafroc (a software)

In order to apply this package to a dataset formulated for Jafroc, use the following code;

     dataList <- convertFromJafroc(
                                  No.of.Modalities =5,
                                  No.of.readers    =4,
                                  No.of.confidence.levels = 5
                                    )

where it requires to specify the number of modalities, readers, confidence levels.

The FROC curve

Using the fitted model object fit of class stanfitExtended, we can draw the FROC curve (or AFROC curve) as follows;

# new.imaging.device = FALSE  is used to include the output image 
# in this README file, so I recommand new.imaging.device = TRUE
BayesianFROC::DrawCurves(fit,
                         new.imaging.device = FALSE)

If you want to draw the curve in white background, then use the followings

# new.imaging.device = FALSE  is used to include the output image 
# in this README file, so I recommand new.imaging.device = TRUE.

BayesianFROC::DrawCurves(fit,
                         Colour = FALSE,
                         new.imaging.device = FALSE)

Excuting the above code, an imaging device will appears in which there are circles indicating the so-called False Positive Fractions (FPFs) and True Positive Fractions (TPFs). In addition, an FROC curve is plotted. FROC curve thorough exactly the expected points of FPFs and TPFs. Thus we can intuitively confirm the goodness of fit by comparing the circles and the curve. Ha,… someone reads this boring vignettes? My right arm ache bothering me for 20 months. Ha,… I want to die. I developed theory and package, but this research cannot make me happy, cannot change anything about my poor life… ha.

Latent Distributions

Hit rates are determined the areas of signal Gaussian between thresholds,

and false alarm rate are defined by the areas of differential logarithmic cumulative Gaussian between thresholds.

False rate

# new.imaging.device = FALSE  is used to include the output image 
# in this README file, so I recommand new.imaging.device = TRUE

BayesianFROC::draw_bi_normal_version_UP(
    fit,new.imaging.device = F,
    dark_theme = T,
    hit.rate = F,
    false.alarm.rate = T,
    both.hit.and.false.rate = F)

Hit rate

# new.imaging.device = FALSE  is used to include the output image 
# in this README file, so I recommand new.imaging.device = TRUE

BayesianFROC::draw_bi_normal_version_UP(
    fit,new.imaging.device = F,
    dark_theme = T,
    hit.rate = T,
    false.alarm.rate = F,
    both.hit.and.false.rate = F)

One will see that the bi normal assumption is wrong in the FROC context, and instead of bi normal assumption, we use two latent distributions, one is Gaussian for signal and another is the differential logarithmic Gaussian introduced first by the author of this package. For details, see vignettes of this package.

Modality Comparison

By fitting hierarchical Bayesian model, we can get the characteristics such as AUCs for each imaging modality (MRI,PET,CT,etc) to compare modalities.

Using the data object named BayesianFROC::dataList.Chakra.Web representing multiple modality data, we will fit the model to data by the following R script. For letting the running time be short, we take small MCMC iteration, that is, ite =222 which is too small to obtain reliable estimates. I think it should be ite =33333 for actual data analysis or compatible result with Jafroc.

The author try to remove eval=FALSE, but it cause stopping of knitr, so I can not include the following code. The following code sometimes crash R session, so,… it is heavy for README file??



#0) To avoid the following error I have to attach the Rcpp. I do not know why such error occur withou Rcpp.
#Error in do.call(rbind,sampler_params) :second argument must be a list Calles:<Anonymous>...get_divergent_iterations ->sampler_param_vector =. do.call Execution halted

library(Rcpp)  # This code can remove the above unknown error, if someone know why the error occur, please tell me.


library(BayesianFROC)



dataList <- dataList.Chakra.Web

fitt <- BayesianFROC::fit_Bayesian_FROC(
  
  # data of multiple reader and multiple case (modalities)
 dataList =   dataList,
  
  # iteration of MCMC
  ite = 1111 # Should be ite = 33333
 )

Now, we obtain the fitted model object named fit which is an S4 object of class stanfitExtended inherited from stanfit of the rstan package..

Transform of S4 Class to apply other packages

To apply the functions of other package such as rstan or ggmcmc, …, etc in which there are functions for object of class stanfit, e.g., rstan::stan_trace(), rstan::stan_dens(),rstan::check_hmc_diagnostics(),…etc, we have to change the class of the fitted model object by the following manner:

 fit.stan <- methods::as(fit, "stanfit")

Then the above object fit.stan is an object of the class stanfit and thus we can apply the function of rstan package as rstan::stan_dens(fit.stan).

Prepare pipe operator (redundant)

# First, get pipe operator
`%>%` <- utils::getFromNamespace("%>%", "magrittr")

Change the class to stanfit

# Change the class from stanfitExtended to stanfit
fit.stan <- methods::as(fit,"stanfit")

trace plot for object of class stanfit


# Change the class from stanfitExtended to stanfit
#fit.stan <- methods::as(fit,"stanfit")


# Plot about MCMC samples of paremeter name "A", reperesenting AUC
ggmcmc::ggs(fit.stan) %>% ggmcmc::ggs_traceplot(family  = "A")

posterior density of parameter A stored in an object of class stanfit

The following plot indicates that maximal posterior estimator (MAP) is very unstable in each chain in this iteration. By drawing more samples, it become stable?


# Change the class from stanfitExtended to stanfit
#fit.stan <- methods::as(fit,"stanfit"
                        
                        
ggmcmc::ggs(fit.stan) %>% ggmcmc::ggs_density(family    = "A")

Auto correlation for an object of class stanfit



# Change the class from stanfitExtended to stanfit
# fit.stan <- methods::as(fit,"stanfit")


ggmcmc::ggs(fit.stan) %>% ggmcmc::ggs_autocorrelation(family    = "A")

How ggmcmc painted using these colors was amazing!

package shinystan

For fitted model object fit.stan of class stanfit, there is a GUI viewer


# Change the class from stanfitExtended to stanfit
fit.stan <- methods::as(fit,"stanfit")


shinystan::launch_shinystan(fit.stan)

Goodness of fit via posterior predictive p value

Evaluates a p value of chi square goodness of fit. In addition, the scatter plot are drawn which shows the replicated datasets from the posterior predictive p value of the data which is used to create a fitted model object fit.

BayesianFROC::ppp(fit)

In previous release, my program for ppp was wrong, so in the current version I fixed.

SBC

Validation of model via Simulation Based Calibration (SBC)

Talts, S., Betancourt, M., Simpson, D., Vehtari, A., and Gelman, A. (2018). Validating Bayesian Inference Algorithms with Simulation-Based Calibration. arXiv preprint arXiv:1804.06788

BayesianFROC::Simulation_Based_Calibration_single_reader_single_modality_via_rstan_sbc()

Errors of estimates decrease monotonically with respect to sample size.

The author investigate the sample size for reliable estimates. Accracy of estimates are depend on the sample size. Large sample size leads us to small error. However, in practical perspective, the number of images or lesions has limitation. The author thinks it is better to obtain 100 images or lesions. And 100 images or lesions gives us the error 0.01 in AUC.

X axis is sample size and Y axis is error of estimates.

BayesianFROC::error_srsc_error_visualization(a)

X axis is sample size and Y axis is variance of estimates.

BayesianFROC::error_srsc_variance_visualization(a)

Copy Link

Version

Install

install.packages('BayesianFROC')

Monthly Downloads

110

Version

0.2.1

License

MIT + file LICENSE

Maintainer

Issei Tsunoda

Last Published

January 19th, 2020

Functions in BayesianFROC (0.2.1)

AFROC

AFROC curve
Author_vs_classic_for_AUC

validation of AUC calculation
Close_all_graphic_devices

Close the Graphic Device
Confirm_hit_rates_are_correctly_made_in_case_of_MRMC

Check hit rate is defined correctly
Credible_Interval_for_curve

Draw FROC curves which means credible interval.
ConfirmConvergence

Check R hat criterion
DrawCurves

Draw the FROC curves
Chi_square_goodness_of_fit_in_case_of_MRMC_Posterior_Mean

Chi square statistic (goodness of fit) in the case of MRMC at the pair of given data and each MCMC sample
BayesianFROC

Theory of FROC Analysis via Bayesian Approaches
AFROC_curve

FROC curve as an embedding map
DrawCurves_MRMC_pairwise_BlackWhite

Draw the FROC curves without colour
Simulation_Based_Calibration_single_reader_single_modality_via_rstan_sbc

Simulation Based Calibration (SBC) for a single reader and a single modality case
Draw_an_area_of_AUC_for_srsc

Draw a Region of the area under the AFROC curve
Draw_a_simulated_data_set_and_Draw_posterior_samples

Draw a dataset and MCMC samples
Simulation_Based_Calibration_histogram

Draw a histogram of the rank statistics
DrawCurves_MRMC

Draw the FROC curves for all modalities and readers
Phi_inv

Inverse function of the Cumulative distribution function \(\Phi(x)\) of the Standard Gaussian. where \(x\) is a real number.
DrawCurves_srsc

Draw the FROC curves
Draw_AUC

draw AUC of AFROC
Phi

The Cumulative distribution function \(\Phi(x)\) of the Standard Gaussian, namely, mean = 0 and variance =1.
DrawCurves_MRMC_pairwise

Draw the FROC curves with Colour
DrawCurves_MRMC_pairwise_col

Draw the FROC curves with Colour
check_hit_is_less_than_NL

Chech total hit is less than NL for each reader and each modality
array_of_hit_and_false_alarms_from_vector

Array of hits and false alarms; 2019 Jun 18
Empirical_FROC_via_ggplot

Empirical FROC curve via ggplot2
Draw_a_prior_sample

Draw One Sample from Prior
Stan_code_validation

stan code
Simulation_Based_Calibration_via_rstan_sbc_MRMC

Simiulation Based Calibration (SBC) for a single reader and a single modality case
FROC_curve

FROC curve as an embedding map
chi_square_goodness_of_fit_from_input_all_param

Not vetor: The Goodness of Fit (Chi Square) Calculator
chi_square_goodness_of_fit

Chi square goodness of fit statistics at each MCMC sample w.r.t. a given dataset.
dark_theme

Dark Theme
check_rhat

Diagnosis of MCMC sampling
data.MultiReaderMultiModality

Multiple reader and Multiple modality data
Draw_a_simulated_data_set

Draw a simulated dataset from model distributions with specified parameters from priors
StatisticForANOVA

Statistic for ANOVA
data.SingleReaderSingleModality

Data: A Single Reader and A Single Modality
Test_Null_Hypothesis_that_all_modalities_are_same

Test the Null hypothesis that all modalities are same
dataList.High

Data: Single reader and Single modality
dataList.divergent.transition.in.case.of.srsc

Divergent transitions Data: Single reader and Single modality
dataList.Low

Data: Single reader and Single modality
dataList.Chakra.Web.orderd

Multiple reader and Multiple modality data
TRUE.Counter.in.vector

Count TRUE in a Vector whose components are all Logical R objects
comparison

model comparison
clearWorkspace

Clear Work Space
compare

model comparison
dataList.Chakra.1

Data: A Single Reader and A Single Modality
chi_square_goodness_of_fit_from_input_all_param_MRMC

Chi square in the case of MRMC at a given dataset and a given parameter.
dataList.Chakra.1.with.explantation

Data: A Single Reader and A Single Modality
dataList.low.ability

Data: A Single Reader and A Single Modality
dataList.high.ability

Data: A Single Reader and A Single Modality
chi_square_at_replicated_data_and_MCMC_samples_MRMC

chi square at replicated data drawn (only one time) from model with each MCMC samples.
convertFromJafroc

Convert .xlsx File of Jafroc into R Object
demo_Bayesian_FROC

demonstration
ddddddd

Multiple reader and 2 modalities data such that all modalities have same AUC.
data.bad.fit

Data: Single reader and Single modality
dataList.Chakra.Web

Multiple Reader and Multiple Modality Data
dataList.Chakra.4

Data: A Single Reader and A Single Modality
dataList.one.modality

Multiple reader and one modality data for fit_MRMC_versionTWO
dataList.Chakra.2

Data: A Single Reader and A Single Modality
dataList.Chakra.3

Data: A Single Reader and A Single Modality
create_dataList_MRMC

Creates a Single Dataset in Case of MRMC
data_of_36_readers_and_a_single_modality

36 readers and a sinle modality data
draw_latent_noise_distribution

Visualization of the Latent Gaussian for Hit rates
draw_latent_signal_distribution

Visualization of Latent Gaussians ( Signal Distribution)
explanation_for_what_curves_are_drawn

Print out about what curves are drawn
ddddd

MRMC; Model did not converge both null model
array_easy_example

Example array
extractAUC

Extract AUC
error_srsc

Validation via replicated datasets from a model at a given model parameter
d

Data: A Single Reader and A Single Modality
extract_estimates_MRMC

MRMC: Extract All Posterior Mean Estimates from stanfitExtended object
error_srsc_error_visualization

Visualization Of Error Analysis
draw.CFP.CTP.from.dataList

Plot the pairs of CFPs and CTPs
extract_data_frame_from_dataList_MRMC

Extract sub data frame from list of FROC data
create_dataset

Create a dataset
demo_Bayesian_FROC_without_pause

demonstration without pause
dataset_creator_by_specifying_only_M_Q

Creates dataset
data.hier.ficitious

Multiple reader and Multiple modality data
fit_GUI_dashboard

Fit with GUI via Shiny (Simple version)
data.nonconverge.srsc

Non-Convergent Data: Single reader and Single modality
extract_parameters_from_replicated_models

Extract Estimates From Replicated MRMC Model
error_srsc_variance_visualization

Visualization Of variance Analysis
dddddd

Multiple reader and one modality data
false_and_its_rate_creator

False Alarm Creator for both cases of MRMC and srsc
explanation_about_package_BayesianFROC

Explanation of this package
fit_GUI_simple_from_apppp_file

Fit with GUI via Shiny
fit_Bayesian_FROC

Fit a model to data
fit_GUI_MRMC

Fit with GUI via Shiny in case of MRMC
ggplotFROC.EAP

Draw FROC curves by two parameters a and b
dataset_creator_for_many_Readers

create data for MRMC
data_2modaities_2readers_3confidence

data: 2 readers, 2 modalities and 3 confideneces
foo

without double quote
hits_rate_creator

MRMC Hit Rates Creator from Thresholds, Mean and S.D.
foo_of_a_List_of_Arrays

Variance of a List of Arrays
fit_GUI

Fit with GUI via Shiny
initial_values_specification_for_stan_in_case_of_MRMC

Initial values for HMC (Hamiltonian Moncte Carlo Markov Chains)
fit_Null_hypothesis_model_to_

Fit the null model
fit_GUI_MRMC_new

Fit an MRMC model to data with Shiny GUI
fit_srsc

fit a model to data in the case of A Single reader and A Single modality (srsc).
give_name_srsc_CFP_CTP_vector

Give a Name For CTP CFP vector
dataset_creator_new_version

Create a Dataset (version 2) Interactively
mu_truth

Mean of signal: parameter of an MRMC model
ddd

Multiple reader and Multiple modality data
hits_false_alarms_creator_from_thresholds

Hits and False Alarms Creator
hits_from_thresholds

MRMC Hit Creator from thresholds, mean and S.D.
ggplotFROC

Draw FROC curves by two parameters a and b
give_name_srsc_data

Give a name for srsc data list component
dd.orderd

Multiple Reader and Multiple Modality Data
dd

Multiple Reader and Multiple Modality Data
error_message

Error Message for Data Format
mu_truth_creator_for_many_readers_MRMC_data

mu of MRMC model paramter
plot_curve_and_hit_rate_and_false_rate_simultaneously

Curve and signal distribution and noise d log Phi() for a single reader and a single modality
metadata_srsc_per_image

Create metadata for MRMC data.
prior_predictor

Predict some estimates of parameter
summarize_MRMC

Summarize the estimates for MRMC case
plot_test

# Definition of a method for the inherited class stanfitExtended from stanfit
prior_print_MRMC

Print What Prior Are Used
error_message_on_imaging_device_rhat_values

Error message on a plot plane(imaging device)
p

Hit Rate: parameter of an MRMC model
z_from_dz

Thresholds from its difference
validation.draw_srsc

Draw Curves for validation dataset
z_truth

Threshold : parameter of an MRMC model
viewdata

Build a table of FROC data
summary_AUC_comparison_MRMC

Print summary for AUC comparisons for MRMC
metadata_to_DrawCurve_MRMC

Create metadata for MRMC data
p_truth

Hit Rate: parameter of an MRMC model
extract_EAP_CI

MRMC: Extract Estimates of a vector from stanfitExtended object
dddd

One reader and Multiple modality data
plotFROC

Draw FROC curves by two parameters a and b
plot_FPF_and_TPF_from_a_dataset

Plot FPF and TPF from MRMC data
false_and_its_rate_creator_MRMC

MRMC: False Alarm Creator For each Modality and each Reader.
dz

Threshold: parameter of an MRMC model
error_MRMC

Comparison of Estimates and Truth in case of MRMC
fffaaabbb

Package Development tools and memo.
snippet_for_BayesianFROC

Edit Snippet
replicate_model_MRMC

Replicate Models
small_margin

Margin
replicate_MRMC_dataList

MRMC: Replicates Datasets From Threshold, Mean and S.D.
validation.dataset_srsc

Error between a give parameter and estimates for the parameters
v_truth_creator_for_many_readers_MRMC_data

v of MRMC model paramter
fit_MRMC

Fit and Draw the FROC models (curves)
z

Threshold: parameter of an MRMC model
waic

WAIC calculator
extract_EAP_by_array

Extract Etimates Preserving Array Format.
fit_GUI_Shiny

Fit with GUI via Shiny (Simple version)
fooo

taboo or
from_array_to_vector

Transform from an array to a vector
fit_GUI_Shiny_MRMC

Fit with GUI via Shiny (in case of MRMC case)
install_imports

Installer.
get_posterior_variance

(UNDER CONSTRUCTION) Alternative of rstan::get_posterior_mean()
fit_MRMC_versionTWO

Fit and Draw the FROC models (curves) version2.
m_q_c_vector_from_M_Q_C

Creats vectors: m,q,c from integers: M,Q,C
get_samples_from_Posterior_Predictive_distribution

Get Samples from the Predictive Posterior Distribution (PPD).
pause

Pause for Demo
make_TeX

Make a TeX file for summary
hits_creator_from_rate

MRMC Dataset Creator From Hit Rate.
make_true_parameter_MRMC

Make a true model parameter and include it in this package
%>>%

Fit a model
pairs_plot_if_divergent_transition_occurred

Pairs plot for divergent transition
metadata_to_fit_MRMC

Create metadata for MRMC data
mu

Mean of signal: parameter of an MRMC model
ppp_MRMC

MRMC: Posterior Predictive P value (PPP) for MRMC,
p_value_of_the_Bayesian_sense_for_chi_square_goodness_of_fit

P value for goodness of fit : No longer used in 2019 Oct
ppp_srsc

Calculates PPP for Models of a single reader and a single modality (Calculation is correct! :'-D)
summary_AUC_comparison_MRMC_with_crayon

Print summary for AUC comparisons for MRMC hier with color
summary_AUC_comparison_MRMC_without_crayon

Print summary for AUC comparisons for MRMC without color
viewdata_srsc

Build a table of data in the case of A Single reader and A Single modality (srsc)
viewdata_MRMC

View MRMC data
plot-methods

A generic function plot()
print

print_stanfitExtended

Definition of a method for the inherited class stanfitExtended from stanfit
showGM

Show the Graphical Model for a single reader and a single modality
pnorm_or_qnorm

pnorm or qnorm
size_of_return_value

Size of R object
v

Standard Deviation: parameter of an MRMC model
v_truth

Standard Deviation: parameter of an MRMC model
prior_print_srsc

Print What Prior Are Used
rank_statistics_with_two_parameters

Rank Statistics
ppp

MRMC or srsc: Posterior Predictive P value (PPP) for MRMC or srsc.
sortAUC

Make a Ranking for AUCs for MRMC Data
summary_EAP_CI_srsc

Summary
stanfitExtended

the_row_number_of_logical_vector

Extract the row number from a logical vector