licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
15783
## %PREDICTMD_GENERATED_BY% using PredictMDExtra PredictMDExtra.import_all() using PredictMD PredictMD.import_all() using CSVFiles using CategoricalArrays using DataFrames using DecisionTree using Distributions using FileIO using GLM using IterTools using Knet using LIBSVM using LinearAlgebra using PredictMD using PredictMDAPI using PredictMDExtra using RDatasets using Random using StatsModels using Test using Unitful const Schema = StatsModels.Schema # PREDICTMD IF INCLUDE TEST STATEMENTS logger = Base.CoreLogging.current_logger_for_env(Base.CoreLogging.Debug, Symbol(splitext(basename(something(@__FILE__, "nothing")))[1]), something(@__MODULE__, "nothing")) if isnothing(logger) logger_stream = devnull else logger_stream = logger.stream end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ### Begin project-specific settings DIRECTORY_CONTAINING_THIS_FILE = @__DIR__ PROJECT_DIRECTORY = dirname( joinpath(splitpath(DIRECTORY_CONTAINING_THIS_FILE)...) ) PROJECT_OUTPUT_DIRECTORY = joinpath( PROJECT_DIRECTORY, "output", ) mkpath(PROJECT_OUTPUT_DIRECTORY) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "data")) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "models")) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "plots")) # PREDICTMD IF INCLUDE TEST STATEMENTS @debug("PROJECT_OUTPUT_DIRECTORY: ", PROJECT_OUTPUT_DIRECTORY,) if PredictMD.is_travis_ci() PredictMD.cache_to_path!( ; from = ["cpu_examples", "breast_cancer_biopsy", "output",], to = [PROJECT_OUTPUT_DIRECTORY], ) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ### End project-specific settings ### Begin model comparison code Kernel = LIBSVM.Kernel Random.seed!(999) trainingandtuning_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "trainingandtuning_features_df.csv", ) trainingandtuning_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "trainingandtuning_labels_df.csv", ) testing_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "testing_features_df.csv", ) testing_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "testing_labels_df.csv", ) training_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "training_features_df.csv", ) training_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "training_labels_df.csv", ) tuning_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "tuning_features_df.csv", ) tuning_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "tuning_labels_df.csv", ) trainingandtuning_features_df = DataFrames.DataFrame( FileIO.load( trainingandtuning_features_df_filename; type_detect_rows = 100, ) ) trainingandtuning_labels_df = DataFrames.DataFrame( FileIO.load( trainingandtuning_labels_df_filename; type_detect_rows = 100, ) ) testing_features_df = DataFrames.DataFrame( FileIO.load( testing_features_df_filename; type_detect_rows = 100, ) ) testing_labels_df = DataFrames.DataFrame( FileIO.load( testing_labels_df_filename; type_detect_rows = 100, ) ) training_features_df = DataFrames.DataFrame( FileIO.load( training_features_df_filename; type_detect_rows = 100, ) ) training_labels_df = DataFrames.DataFrame( FileIO.load( training_labels_df_filename; type_detect_rows = 100, ) ) tuning_features_df = DataFrames.DataFrame( FileIO.load( tuning_features_df_filename; type_detect_rows = 100, ) ) tuning_labels_df = DataFrames.DataFrame( FileIO.load( tuning_labels_df_filename; type_detect_rows = 100, ) ) smoted_training_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "smoted_training_features_df.csv", ) smoted_training_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "smoted_training_labels_df.csv", ) smoted_training_features_df = DataFrames.DataFrame( FileIO.load( smoted_training_features_df_filename; type_detect_rows = 100, ) ) smoted_training_labels_df = DataFrames.DataFrame( FileIO.load( smoted_training_labels_df_filename; type_detect_rows = 100, ) ) logistic_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "logistic_classifier.jld2", ) random_forest_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "random_forest_classifier.jld2", ) c_svc_svm_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "c_svc_svm_classifier.jld2", ) nu_svc_svm_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "nu_svc_svm_classifier.jld2", ) knet_mlp_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "knet_mlp_classifier.jld2", ) # PREDICTMD IF INCLUDE TEST STATEMENTS logistic_classifier = nothing Test.@test isnothing(logistic_classifier) random_forest_classifier = nothing Test.@test isnothing(random_forest_classifier) c_svc_svm_classifier = nothing Test.@test isnothing(c_svc_svm_classifier) nu_svc_svm_classifier = nothing Test.@test isnothing(nu_svc_svm_classifier) knet_mlp_classifier = nothing Test.@test isnothing(knet_mlp_classifier) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS logistic_classifier = PredictMD.load_model(logistic_classifier_filename) random_forest_classifier = PredictMD.load_model(random_forest_classifier_filename) c_svc_svm_classifier = PredictMD.load_model(c_svc_svm_classifier_filename) nu_svc_svm_classifier = PredictMD.load_model(nu_svc_svm_classifier_filename) knet_mlp_classifier = PredictMD.load_model(knet_mlp_classifier_filename) PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) # PREDICTMD IF INCLUDE TEST STATEMENTS PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS all_models = PredictMD.AbstractFittable[ logistic_classifier, random_forest_classifier, c_svc_svm_classifier, nu_svc_svm_classifier, knet_mlp_classifier, ] single_label_name = :Class negative_class = "benign" positive_class = "malignant" single_label_levels = [negative_class, positive_class] categorical_label_names = Symbol[single_label_name] continuous_label_names = Symbol[] label_names = vcat(categorical_label_names, continuous_label_names) println( logger_stream, string( "Single label binary classification metrics, training set, ", "fix sensitivity", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, training_features_df, training_labels_df, single_label_name, positive_class; sensitivity = 0.95, ); allrows = true, allcols = true, splitcols = false, ) println( logger_stream, string( "Single label binary classification metrics, training set, ", "fix specificity", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, training_features_df, training_labels_df, single_label_name, positive_class; specificity = 0.95, ); allrows = true, allcols = true, splitcols = false, ) println( logger_stream, string( "Single label binary classification metrics, training set, ", "maximize F1 score", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, training_features_df, training_labels_df, single_label_name, positive_class; maximize = :f1score, ); allrows = true, allcols = true, splitcols = false, ) println( logger_stream, string( "Single label binary classification metrics, training set, ", "maximize Cohen's kappa", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, training_features_df, training_labels_df, single_label_name, positive_class; maximize = :cohen_kappa, ); allrows = true, allcols = true, splitcols = false, ) println( logger_stream, string( "Single label binary classification metrics, testing set, ", "fix sensitivity", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, testing_features_df, testing_labels_df, single_label_name, positive_class; sensitivity = 0.95, ); allrows = true, allcols = true, splitcols = false, ) # PREDICTMD IF INCLUDE TEST STATEMENTS metrics = PredictMD.singlelabelbinaryclassificationmetrics(all_models, testing_features_df, testing_labels_df, single_label_name, positive_class; sensitivity = 0.95) auprc_row = first( findall( strip.(metrics[:metric]) .== "AUPRC" ) ) Test.@test( strip(metrics[auprc_row, :metric]) == "AUPRC" ) Test.@test( metrics[auprc_row, Symbol("Logistic regression")] > 0.910 ) Test.@test( metrics[auprc_row, Symbol("Random forest")] > 0.910 ) Test.@test( metrics[auprc_row, Symbol("SVM (C-SVC)")] > 0.910 ) Test.@test( metrics[auprc_row, Symbol("SVM (nu-SVC)")] > 0.910 ) Test.@test( metrics[auprc_row, Symbol("Knet MLP")] > 0.910 ) aurocc_row = first( findall( strip.(metrics[:metric]) .== "AUROCC" ) ) Test.@test( metrics[aurocc_row, :metric] == "AUROCC" ) Test.@test( metrics[aurocc_row, Symbol("Logistic regression")] > 0.910 ) Test.@test( metrics[aurocc_row, Symbol("Random forest")] > 0.910 ) Test.@test( metrics[aurocc_row, Symbol("SVM (C-SVC)")] > 0.910 ) Test.@test( metrics[aurocc_row, Symbol("SVM (nu-SVC)")] > 0.910 ) Test.@test( metrics[aurocc_row, Symbol("Knet MLP")] > 0.910 ) avg_precision_row = first( findall( strip.(metrics[:metric]) .== "Average precision" ) ) Test.@test( strip(metrics[avg_precision_row, :metric]) == "Average precision" ) Test.@test( metrics[avg_precision_row, Symbol("Logistic regression")] > 0.910 ) Test.@test( metrics[avg_precision_row, Symbol("Random forest")] > 0.910 ) Test.@test( metrics[avg_precision_row, Symbol("SVM (C-SVC)")] > 0.910 ) Test.@test( metrics[avg_precision_row, Symbol("SVM (nu-SVC)")] > 0.910 ) Test.@test( metrics[avg_precision_row, Symbol("Knet MLP")] > 0.910 ) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS println( logger_stream, string( "Single label binary classification metrics, testing set, ", "fix specificity", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, testing_features_df, testing_labels_df, single_label_name, positive_class; specificity = 0.95, ); allrows = true, allcols = true, splitcols = false, ) println( logger_stream, string( "Single label binary classification metrics, testing set, ", "maximize F1 score", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, testing_features_df, testing_labels_df, single_label_name, positive_class; maximize = :f1score, ); allrows = true, allcols = true, splitcols = false, ) println( logger_stream, string( "Single label binary classification metrics, testing set, ", "maximize Cohen's kappa", ) ) show( logger_stream, PredictMD.singlelabelbinaryclassificationmetrics( all_models, testing_features_df, testing_labels_df, single_label_name, positive_class; maximize = :cohen_kappa, ); allrows = true, allcols = true, splitcols = false, ) rocplottesting = PredictMD.plotroccurve( all_models, testing_features_df, testing_labels_df, single_label_name, positive_class, ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "rocplottesting", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, rocplottesting) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(rocplottesting) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "rocplottesting.pdf", ), rocplottesting, ) prplottesting = PredictMD.plotprcurve( all_models, testing_features_df, testing_labels_df, single_label_name, positive_class, ); # PREDICTMD IF INCLUDE TEST STATEMENTS filename = string( tempname(), "_", "prplottesting", ".pdf", ) rm(filename; force = true, recursive = true,) @debug("Attempting to test that the file does not exist...", filename,) Test.@test(!isfile(filename)) @debug("The file does not exist.", filename, isfile(filename),) PredictMD.save_plot(filename, prplottesting) if PredictMD.is_force_test_plots() @debug("Attempting to test that the file exists...", filename,) Test.@test(isfile(filename)) @debug("The file does exist.", filename, isfile(filename),) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS display(prplottesting) PredictMD.save_plot( joinpath( PROJECT_OUTPUT_DIRECTORY, "plots", "prplottesting.pdf", ), prplottesting, ) ### End model comparison code # PREDICTMD IF INCLUDE TEST STATEMENTS if PredictMD.is_travis_ci() PredictMD.path_to_cache!( ; to = ["cpu_examples", "breast_cancer_biopsy", "output",], from = [PROJECT_OUTPUT_DIRECTORY], ) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ## %PREDICTMD_GENERATED_BY%
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
10858
## %PREDICTMD_GENERATED_BY% using PredictMDExtra PredictMDExtra.import_all() using PredictMD PredictMD.import_all() using CSVFiles using CategoricalArrays using DataFrames using DecisionTree using Distributions using FileIO using GLM using IterTools using Knet using LIBSVM using LinearAlgebra using PredictMD using PredictMDAPI using PredictMDExtra using RDatasets using Random using StatsModels using Test using Unitful const Schema = StatsModels.Schema # PREDICTMD IF INCLUDE TEST STATEMENTS logger = Base.CoreLogging.current_logger_for_env(Base.CoreLogging.Debug, Symbol(splitext(basename(something(@__FILE__, "nothing")))[1]), something(@__MODULE__, "nothing")) if isnothing(logger) logger_stream = devnull else logger_stream = logger.stream end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ### Begin project-specific settings DIRECTORY_CONTAINING_THIS_FILE = @__DIR__ PROJECT_DIRECTORY = dirname( joinpath(splitpath(DIRECTORY_CONTAINING_THIS_FILE)...) ) PROJECT_OUTPUT_DIRECTORY = joinpath( PROJECT_DIRECTORY, "output", ) mkpath(PROJECT_OUTPUT_DIRECTORY) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "data")) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "models")) mkpath(joinpath(PROJECT_OUTPUT_DIRECTORY, "plots")) # PREDICTMD IF INCLUDE TEST STATEMENTS if PredictMD.is_travis_ci() PredictMD.cache_to_path!( ; from = ["cpu_examples", "breast_cancer_biopsy", "output",], to = [PROJECT_OUTPUT_DIRECTORY], ) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS # PREDICTMD IF INCLUDE TEST STATEMENTS @debug("PROJECT_OUTPUT_DIRECTORY: ", PROJECT_OUTPUT_DIRECTORY,) if PredictMD.is_travis_ci() PredictMD.cache_to_path!( ; from = ["cpu_examples", "breast_cancer_biopsy", "output",], to = [PROJECT_OUTPUT_DIRECTORY], ) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ### End project-specific settings ### Begin model output code Kernel = LIBSVM.Kernel Random.seed!(999) trainingandtuning_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "trainingandtuning_features_df.csv", ) trainingandtuning_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "trainingandtuning_labels_df.csv", ) testing_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "testing_features_df.csv", ) testing_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "testing_labels_df.csv", ) training_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "training_features_df.csv", ) training_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "training_labels_df.csv", ) tuning_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "tuning_features_df.csv", ) tuning_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "tuning_labels_df.csv", ) trainingandtuning_features_df = DataFrames.DataFrame( FileIO.load( trainingandtuning_features_df_filename; type_detect_rows = 100, ) ) trainingandtuning_labels_df = DataFrames.DataFrame( FileIO.load( trainingandtuning_labels_df_filename; type_detect_rows = 100, ) ) testing_features_df = DataFrames.DataFrame( FileIO.load( testing_features_df_filename; type_detect_rows = 100, ) ) testing_labels_df = DataFrames.DataFrame( FileIO.load( testing_labels_df_filename; type_detect_rows = 100, ) ) training_features_df = DataFrames.DataFrame( FileIO.load( training_features_df_filename; type_detect_rows = 100, ) ) training_labels_df = DataFrames.DataFrame( FileIO.load( training_labels_df_filename; type_detect_rows = 100, ) ) tuning_features_df = DataFrames.DataFrame( FileIO.load( tuning_features_df_filename; type_detect_rows = 100, ) ) tuning_labels_df = DataFrames.DataFrame( FileIO.load( tuning_labels_df_filename; type_detect_rows = 100, ) ) smoted_training_features_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "smoted_training_features_df.csv", ) smoted_training_labels_df_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "data", "smoted_training_labels_df.csv", ) smoted_training_features_df = DataFrames.DataFrame( FileIO.load( smoted_training_features_df_filename; type_detect_rows = 100, ) ) smoted_training_labels_df = DataFrames.DataFrame( FileIO.load( smoted_training_labels_df_filename; type_detect_rows = 100, ) ) logistic_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "logistic_classifier.jld2", ) random_forest_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "random_forest_classifier.jld2", ) c_svc_svm_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "c_svc_svm_classifier.jld2", ) nu_svc_svm_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "nu_svc_svm_classifier.jld2", ) knet_mlp_classifier_filename = joinpath( PROJECT_OUTPUT_DIRECTORY, "models", "knet_mlp_classifier.jld2", ) # PREDICTMD IF INCLUDE TEST STATEMENTS logistic_classifier = nothing Test.@test isnothing(logistic_classifier) random_forest_classifier = nothing Test.@test isnothing(random_forest_classifier) c_svc_svm_classifier = nothing Test.@test isnothing(c_svc_svm_classifier) nu_svc_svm_classifier = nothing Test.@test isnothing(nu_svc_svm_classifier) knet_mlp_classifier = nothing Test.@test isnothing(knet_mlp_classifier) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS logistic_classifier = PredictMD.load_model(logistic_classifier_filename) random_forest_classifier = PredictMD.load_model(random_forest_classifier_filename) c_svc_svm_classifier = PredictMD.load_model(c_svc_svm_classifier_filename) nu_svc_svm_classifier = PredictMD.load_model(nu_svc_svm_classifier_filename) knet_mlp_classifier = PredictMD.load_model(knet_mlp_classifier_filename) PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) # PREDICTMD IF INCLUDE TEST STATEMENTS PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS PredictMD.predict_proba(logistic_classifier, smoted_training_features_df) PredictMD.predict_proba(random_forest_classifier, smoted_training_features_df) PredictMD.predict_proba(c_svc_svm_classifier, smoted_training_features_df) PredictMD.predict_proba(nu_svc_svm_classifier, smoted_training_features_df) PredictMD.predict_proba(knet_mlp_classifier, smoted_training_features_df) PredictMD.predict_proba(logistic_classifier,testing_features_df) PredictMD.predict_proba(random_forest_classifier,testing_features_df) PredictMD.predict_proba(c_svc_svm_classifier,testing_features_df) PredictMD.predict_proba(nu_svc_svm_classifier,testing_features_df) PredictMD.predict_proba(knet_mlp_classifier,testing_features_df) PredictMD.predict(logistic_classifier,smoted_training_features_df) PredictMD.predict(random_forest_classifier,smoted_training_features_df) PredictMD.predict(c_svc_svm_classifier,smoted_training_features_df) PredictMD.predict(nu_svc_svm_classifier,smoted_training_features_df) PredictMD.predict(knet_mlp_classifier,smoted_training_features_df) PredictMD.predict(logistic_classifier,testing_features_df) PredictMD.predict(random_forest_classifier,testing_features_df) PredictMD.predict(c_svc_svm_classifier,testing_features_df) PredictMD.predict(nu_svc_svm_classifier,testing_features_df) PredictMD.predict(knet_mlp_classifier,testing_features_df) single_label_name = :Class negative_class = "benign" positive_class = "malignant" PredictMD.predict(logistic_classifier,smoted_training_features_df, positive_class, 0.3) PredictMD.predict(random_forest_classifier,smoted_training_features_df, positive_class, 0.3) PredictMD.predict(c_svc_svm_classifier,smoted_training_features_df, positive_class, 0.3) PredictMD.predict(nu_svc_svm_classifier,smoted_training_features_df, positive_class, 0.3) PredictMD.predict(knet_mlp_classifier,smoted_training_features_df, positive_class, 0.3) PredictMD.predict(logistic_classifier,testing_features_df, positive_class, 0.3) PredictMD.predict(random_forest_classifier,testing_features_df, positive_class, 0.3) PredictMD.predict(c_svc_svm_classifier,testing_features_df, positive_class, 0.3) PredictMD.predict(nu_svc_svm_classifier,testing_features_df, positive_class, 0.3) PredictMD.predict(knet_mlp_classifier,testing_features_df, positive_class, 0.3) ### End model output code # PREDICTMD IF INCLUDE TEST STATEMENTS PredictMD.get_underlying(logistic_classifier) PredictMD.get_underlying(random_forest_classifier) PredictMD.get_underlying(c_svc_svm_classifier) PredictMD.get_underlying(nu_svc_svm_classifier) PredictMD.get_underlying(knet_mlp_classifier) PredictMD.get_history(logistic_classifier) PredictMD.get_history(random_forest_classifier) PredictMD.get_history(c_svc_svm_classifier) PredictMD.get_history(nu_svc_svm_classifier) PredictMD.get_history(knet_mlp_classifier) PredictMD.parse_functions!(logistic_classifier) PredictMD.parse_functions!(random_forest_classifier) PredictMD.parse_functions!(c_svc_svm_classifier) PredictMD.parse_functions!(nu_svc_svm_classifier) PredictMD.parse_functions!(knet_mlp_classifier) # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS # PREDICTMD IF INCLUDE TEST STATEMENTS if PredictMD.is_travis_ci() PredictMD.path_to_cache!( ; to = ["cpu_examples", "breast_cancer_biopsy", "output",], from = [PROJECT_OUTPUT_DIRECTORY], ) end # PREDICTMD ELSE # PREDICTMD ENDIF INCLUDE TEST STATEMENTS ## %PREDICTMD_GENERATED_BY%
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
6773
import InteractiveUtils # stdlib import Pkg # stdlib import Test # stdlib import Random Random.seed!(999) @debug(string("Julia depot paths: "), Base.DEPOT_PATH) @debug(string("Julia load paths: "), Base.LOAD_PATH) InteractiveUtils.versioninfo(verbose=true) @debug(string("Attempting to import PredictMD...",)) import PredictMD @debug(string("Successfully imported PredictMD.",)) @debug(string("PredictMD version: "),PredictMD.version(),) @debug( string("PredictMD package directory: "), PredictMD.package_directory(), ) @debug(string("Attempting to import PredictMDExtra...",)) import PredictMDExtra @debug(string("Successfully imported PredictMDExtra.",)) @debug(string("PredictMDExtra version: "),PredictMDExtra.version(),) @debug( string("PredictMDExtra package directory: "), PredictMDExtra.package_directory(), ) @debug(string("Julia depot paths: "), Base.DEPOT_PATH) @debug(string("Julia load paths: "), Base.LOAD_PATH) if group_includes_block(TEST_GROUP, TestBlockUnitTests()) Test.@testset "Unit tests" begin if false else unit_test_interval_string = "[,)" end @debug( "unit_test_interval_string: ", unit_test_interval_string, ) if !is_interval(unit_test_interval_string) throw( ArgumentError( string( "$(unit_test_interval_string) ", "is not a valid interval", ) ) ) end unit_test_interval = construct_interval( unit_test_interval_string ) @debug( "unit_test_interval: ", unit_test_interval, ) testmodulea_filename = joinpath("PredictMDTestModuleA","PredictMDTestModuleA.jl",) testmoduleb_filename = joinpath( "PredictMDTestModuleB", "directory1", "directory2", "directory3", "directory4", "directory5", "PredictMDTestModuleB.jl", ) testmodulec_filename = joinpath( PredictMD.maketempdir(), "PredictMDTestModuleC.jl", ) rm(testmodulec_filename; force = true, recursive = true) open(testmodulec_filename, "w") do io write(io, "module PredictMDTestModuleC end") end include(testmodulea_filename) include(testmoduleb_filename) include(testmodulec_filename) test_directory = dirname(@__FILE__) unit_test_directory = joinpath(test_directory, "unit") include("unit-tests-type-definitions.jl") for (root, dirs, files) in walkdir(unit_test_directory) Test.@testset "$(root)" begin for file in files if endswith(lowercase(strip(file)), ".jl") file_path = joinpath(root, file) if interval_contains_x(unit_test_interval, strip(file)) Test.@testset "$(file_path)" begin @debug("Running $(file_path)") include(file_path) end end end end end end end end temp_generate_examples_dir = joinpath( PredictMD.maketempdir(), "generate_examples", "PredictMDTEMP", "examples", ) rm( temp_generate_examples_dir; force = true, recursive = true, ) Test.@testset "Integration tests" begin Test.@testset "Generate examples " begin Test.@test( temp_generate_examples_dir == PredictMD.generate_examples( temp_generate_examples_dir; scripts = true, include_test_statements = true, markdown = false, notebooks = false, execute_notebooks = false, ) ) end Test.@testset "Boston housing regression example (CPU) " begin @debug("Testing Boston housing regression example (CPU)") boston_housing_tests = [ "01_preprocess_data.jl" => TestBlockIntegration1(), "02_linear_regression.jl" => TestBlockIntegration1(), "03_random_forest_regression.jl" => TestBlockIntegration2(), "04_knet_mlp_regression.jl" => TestBlockIntegration2(), "05_compare_models.jl" => TestBlockIntegration3(), "06_get_model_output.jl" => TestBlockIntegration3(), ] for test_pair in boston_housing_tests test_file = test_pair[1] test_block = test_pair[2] if group_includes_block(TEST_GROUP, test_block) Test.@testset "cpu_examples/bostonhousing/src/$(test_file)" begin include( joinpath( temp_generate_examples_dir, "cpu_examples", "boston_housing", "src", test_file, ) ) end end end end Test.@testset "Breast cancer biopsy classification (CPU)" begin @debug("Testing breast cancer biopsy classification example (CPU)") breast_cancer_tests = [ "01_preprocess_data.jl" => TestBlockIntegration4(), "02_smote.jl" => TestBlockIntegration4(), "03_logistic_classifier.jl" => TestBlockIntegration4(), "04_random_forest_classifier.jl" => TestBlockIntegration5(), "05_c_svc_svm_classifier.jl" => TestBlockIntegration5(), "06_nu_svc_svm_classifier.jl" => TestBlockIntegration5(), "07_knet_mlp_classifier.jl" => TestBlockIntegration6(), "08_compare_models.jl" => TestBlockIntegration7(), "09_get_model_output.jl" => TestBlockIntegration7(), ] for test_pair in breast_cancer_tests test_file = test_pair[1] test_block = test_pair[2] if group_includes_block(TEST_GROUP, test_block) Test.@testset "cpu_examples/breastcancer/src/$(test_file)" begin include( joinpath( temp_generate_examples_dir, "cpu_examples", "breast_cancer_biopsy", "src", test_file, ) ) end end end end end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
7291
abstract type AbstractTestBlock end struct TestBlockUnitTests <: AbstractTestBlock end struct TestBlockIntegration1 <: AbstractTestBlock end struct TestBlockIntegration2 <: AbstractTestBlock end struct TestBlockIntegration3 <: AbstractTestBlock end struct TestBlockIntegration4 <: AbstractTestBlock end struct TestBlockIntegration5 <: AbstractTestBlock end struct TestBlockIntegration6 <: AbstractTestBlock end struct TestBlockIntegration7 <: AbstractTestBlock end group_includes_block(::AbstractTestGroup, ::AbstractTestBlock) = true group_includes_block(::TestGroupDefault, ::AbstractTestBlock) = true group_includes_block(::TestGroupAll, ::AbstractTestBlock) = true group_includes_block(::TestGroupTestPlots, ::AbstractTestBlock) = true group_includes_block(::TestGroupImportOnly, ::AbstractTestBlock) = false group_includes_block(::TestGroupTravis1, ::TestBlockUnitTests) = true group_includes_block(::TestGroupTravis1, ::TestBlockIntegration1) = true group_includes_block(::TestGroupTravis1, ::TestBlockIntegration2) = false group_includes_block(::TestGroupTravis1, ::TestBlockIntegration3) = false group_includes_block(::TestGroupTravis1, ::TestBlockIntegration4) = false group_includes_block(::TestGroupTravis1, ::TestBlockIntegration5) = false group_includes_block(::TestGroupTravis1, ::TestBlockIntegration6) = false group_includes_block(::TestGroupTravis1, ::TestBlockIntegration7) = false group_includes_block(::TestGroupTravis2, ::TestBlockUnitTests) = false group_includes_block(::TestGroupTravis2, ::TestBlockIntegration1) = false group_includes_block(::TestGroupTravis2, ::TestBlockIntegration2) = true group_includes_block(::TestGroupTravis2, ::TestBlockIntegration3) = false group_includes_block(::TestGroupTravis2, ::TestBlockIntegration4) = false group_includes_block(::TestGroupTravis2, ::TestBlockIntegration5) = false group_includes_block(::TestGroupTravis2, ::TestBlockIntegration6) = false group_includes_block(::TestGroupTravis2, ::TestBlockIntegration7) = false group_includes_block(::TestGroupTravis3, ::TestBlockUnitTests) = false group_includes_block(::TestGroupTravis3, ::TestBlockIntegration1) = false group_includes_block(::TestGroupTravis3, ::TestBlockIntegration2) = false group_includes_block(::TestGroupTravis3, ::TestBlockIntegration3) = true group_includes_block(::TestGroupTravis3, ::TestBlockIntegration4) = false group_includes_block(::TestGroupTravis3, ::TestBlockIntegration5) = false group_includes_block(::TestGroupTravis3, ::TestBlockIntegration6) = false group_includes_block(::TestGroupTravis3, ::TestBlockIntegration7) = false group_includes_block(::TestGroupTravis4, ::TestBlockUnitTests) = false group_includes_block(::TestGroupTravis4, ::TestBlockIntegration1) = false group_includes_block(::TestGroupTravis4, ::TestBlockIntegration2) = false group_includes_block(::TestGroupTravis4, ::TestBlockIntegration3) = false group_includes_block(::TestGroupTravis4, ::TestBlockIntegration4) = true group_includes_block(::TestGroupTravis4, ::TestBlockIntegration5) = false group_includes_block(::TestGroupTravis4, ::TestBlockIntegration6) = false group_includes_block(::TestGroupTravis4, ::TestBlockIntegration7) = false group_includes_block(::TestGroupTravis5, ::TestBlockUnitTests) = false group_includes_block(::TestGroupTravis5, ::TestBlockIntegration1) = false group_includes_block(::TestGroupTravis5, ::TestBlockIntegration2) = false group_includes_block(::TestGroupTravis5, ::TestBlockIntegration3) = false group_includes_block(::TestGroupTravis5, ::TestBlockIntegration4) = false group_includes_block(::TestGroupTravis5, ::TestBlockIntegration5) = true group_includes_block(::TestGroupTravis5, ::TestBlockIntegration6) = false group_includes_block(::TestGroupTravis5, ::TestBlockIntegration7) = false group_includes_block(::TestGroupTravis6, ::TestBlockUnitTests) = false group_includes_block(::TestGroupTravis6, ::TestBlockIntegration1) = false group_includes_block(::TestGroupTravis6, ::TestBlockIntegration2) = false group_includes_block(::TestGroupTravis6, ::TestBlockIntegration3) = false group_includes_block(::TestGroupTravis6, ::TestBlockIntegration4) = false group_includes_block(::TestGroupTravis6, ::TestBlockIntegration5) = false group_includes_block(::TestGroupTravis6, ::TestBlockIntegration6) = true group_includes_block(::TestGroupTravis6, ::TestBlockIntegration7) = false group_includes_block(::TestGroupTravis7, ::TestBlockUnitTests) = false group_includes_block(::TestGroupTravis7, ::TestBlockIntegration1) = false group_includes_block(::TestGroupTravis7, ::TestBlockIntegration2) = false group_includes_block(::TestGroupTravis7, ::TestBlockIntegration3) = false group_includes_block(::TestGroupTravis7, ::TestBlockIntegration4) = false group_includes_block(::TestGroupTravis7, ::TestBlockIntegration5) = false group_includes_block(::TestGroupTravis7, ::TestBlockIntegration6) = false group_includes_block(::TestGroupTravis7, ::TestBlockIntegration7) = true group_includes_block(::TestGroupDocker1, ::TestBlockUnitTests) = true group_includes_block(::TestGroupDocker1, ::TestBlockIntegration1) = false group_includes_block(::TestGroupDocker1, ::TestBlockIntegration2) = false group_includes_block(::TestGroupDocker1, ::TestBlockIntegration3) = false group_includes_block(::TestGroupDocker1, ::TestBlockIntegration4) = false group_includes_block(::TestGroupDocker1, ::TestBlockIntegration5) = false group_includes_block(::TestGroupDocker1, ::TestBlockIntegration6) = false group_includes_block(::TestGroupDocker1, ::TestBlockIntegration7) = false group_includes_block(::TestGroupDocker2, ::TestBlockUnitTests) = false group_includes_block(::TestGroupDocker2, ::TestBlockIntegration1) = true group_includes_block(::TestGroupDocker2, ::TestBlockIntegration2) = true group_includes_block(::TestGroupDocker2, ::TestBlockIntegration3) = true group_includes_block(::TestGroupDocker2, ::TestBlockIntegration4) = false group_includes_block(::TestGroupDocker2, ::TestBlockIntegration5) = false group_includes_block(::TestGroupDocker2, ::TestBlockIntegration6) = false group_includes_block(::TestGroupDocker2, ::TestBlockIntegration7) = false group_includes_block(::TestGroupDocker3, ::TestBlockUnitTests) = false group_includes_block(::TestGroupDocker3, ::TestBlockIntegration1) = false group_includes_block(::TestGroupDocker3, ::TestBlockIntegration2) = false group_includes_block(::TestGroupDocker3, ::TestBlockIntegration3) = false group_includes_block(::TestGroupDocker3, ::TestBlockIntegration4) = true group_includes_block(::TestGroupDocker3, ::TestBlockIntegration5) = true group_includes_block(::TestGroupDocker3, ::TestBlockIntegration6) = true group_includes_block(::TestGroupDocker3, ::TestBlockIntegration7) = true group_includes_block(::TestGroupDocker4, ::TestBlockUnitTests) = false group_includes_block(::TestGroupDocker4, ::TestBlockIntegration1) = false group_includes_block(::TestGroupDocker4, ::TestBlockIntegration2) = false group_includes_block(::TestGroupDocker4, ::TestBlockIntegration3) = false group_includes_block(::TestGroupDocker4, ::TestBlockIntegration4) = false group_includes_block(::TestGroupDocker4, ::TestBlockIntegration5) = false group_includes_block(::TestGroupDocker4, ::TestBlockIntegration6) = false group_includes_block(::TestGroupDocker4, ::TestBlockIntegration7) = false
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
1578
import PredictMD abstract type AbstractTestGroup end struct TestGroupDefault <: AbstractTestGroup end struct TestGroupAll <: AbstractTestGroup end struct TestGroupTestPlots <: AbstractTestGroup end struct TestGroupImportOnly <: AbstractTestGroup end struct TestGroupTravis1 <: AbstractTestGroup end struct TestGroupTravis2 <: AbstractTestGroup end struct TestGroupTravis3 <: AbstractTestGroup end struct TestGroupTravis4 <: AbstractTestGroup end struct TestGroupTravis5 <: AbstractTestGroup end struct TestGroupTravis6 <: AbstractTestGroup end struct TestGroupTravis7 <: AbstractTestGroup end struct TestGroupDocker1 <: AbstractTestGroup end struct TestGroupDocker2 <: AbstractTestGroup end struct TestGroupDocker3 <: AbstractTestGroup end struct TestGroupDocker4 <: AbstractTestGroup end const TEST_GROUP_STRING_TO_INSTANCE = Dict{String, AbstractTestGroup}( # "default" => TestGroupDefault(), # "all" => TestGroupAll(), # "test-plots" => TestGroupTestPlots(), # "import-only" => TestGroupImportOnly(), # "travis-1" => TestGroupTravis1(), "travis-2" => TestGroupTravis2(), "travis-3" => TestGroupTravis3(), "travis-4" => TestGroupTravis4(), "travis-5" => TestGroupTravis5(), "travis-6" => TestGroupTravis6(), "travis-7" => TestGroupTravis7(), # "docker-1" => TestGroupDocker1(), "docker-2" => TestGroupDocker2(), "docker-3" => TestGroupDocker3(), "docker-4" => TestGroupDocker4(), ) const TEST_GROUP_INSTANCE_TO_STRING = PredictMD.inverse( TEST_GROUP_STRING_TO_INSTANCE )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
1454
import PredictMD if get(ENV, "PKGEVAL", "") == "true" ENV["PREDICTMD_TEST_GROUP"] = "all" end if PredictMD.is_travis_ci() && !haskey(ENV, "PREDICTMD_TEST_GROUP") ENV["PREDICTMD_TEST_GROUP"] = lowercase( strip( get( ENV, "GROUP", "", ) ) ) end const _test_group_environment_variable = lowercase( strip( get( ENV, "PREDICTMD_TEST_GROUP", "" ) ) ) if length(_test_group_environment_variable) == 0 const _test_group_value = "default" else const _test_group_value = _test_group_environment_variable end if haskey(TEST_GROUP_STRING_TO_INSTANCE, _test_group_value) const TEST_GROUP = TEST_GROUP_STRING_TO_INSTANCE[_test_group_value] @info( string( "PREDICTMD_TEST_GROUP: \"", TEST_GROUP_INSTANCE_TO_STRING[TEST_GROUP], "\"", ) ) else const _valid_test_group_values = string( "\"", join( sort(collect(keys(TEST_GROUP_STRING_TO_INSTANCE))), "\", \"", ), "\"", ) error( string( "\"", _test_group_value, "\" is not a valid value for PREDICTMD_TEST_GROUP. ", "Valid values are: ", _valid_test_group_values, ".", ) ) end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
851
import InteractiveUtils import Pkg import Test @debug(string("Julia depot paths: "), Base.DEPOT_PATH) @debug(string("Julia load paths: "), Base.LOAD_PATH) logger = Base.CoreLogging.current_logger_for_env(Base.CoreLogging.Debug, Symbol(splitext(basename(something(@__FILE__, "nothing")))[1]), something(@__MODULE__, "nothing")) @debug(string("Julia version info: ",)) if !isnothing(logger) InteractiveUtils.versioninfo(logger.stream; verbose=true) end @debug(string("Attempting to import PredictMD...",)) import PredictMD @debug(string("Successfully imported PredictMD.",)) @debug(string("PredictMD version: "),PredictMD.version(),) @debug(string("PredictMD package directory: "),PredictMD.package_directory(),) @debug(string("Julia depot paths: "), Base.DEPOT_PATH) @debug(string("Julia load paths: "), Base.LOAD_PATH) PredictMD.import_all()
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
5351
abstract type AbstractInterval end struct NoBoundsInterval <: AbstractInterval end struct LowerAndUpperBoundInterval <: AbstractInterval left::String right::String function LowerAndUpperBoundInterval( left::String, right::String, )::LowerAndUpperBoundInterval correct_left = strip(left) correct_right = strip(right) result::LowerAndUpperBoundInterval = new( correct_left, correct_right, ) return result end end struct LowerBoundOnlyInterval <: AbstractInterval left::String function LowerBoundOnlyInterval( left::String, )::LowerBoundOnlyInterval correct_left = strip(left) result::LowerBoundOnlyInterval = new( correct_left, ) return result end end struct UpperBoundOnlyInterval <: AbstractInterval right::String function UpperBoundOnlyInterval( right::String, )::UpperBoundOnlyInterval correct_right = strip(right) result::UpperBoundOnlyInterval = new( correct_right, ) return result end end function is_interval(x::String)::Bool if is_no_bounds_interval(x) return true elseif is_lower_bound_only_interval(x) return true elseif is_upper_bound_only_interval(x) return true elseif is_lower_and_upper_bound_interval(x) return true else return false end end function get_lower_and_upper_bound_interval_regex()::Regex lower_and_upper_bound_interval_regex::Regex = r"\[(\w\w*?)\,(\w\w*?)\)" return lower_and_upper_bound_interval_regex end function get_lower_bound_only_interval_regex()::Regex lower_bound_only_interval_regex::Regex = r"\[(\w\w*?)\,\)" return lower_bound_only_interval_regex end function get_upper_bound_only_interval_regex()::Regex upper_bound_only_interval_regex::Regex = r"\[\,(\w\w*?)\)" return upper_bound_only_interval_regex end function get_no_bounds_interval_regex()::Regex no_bounds_interval_regex::Regex = r"\[\,\)" return no_bounds_interval_regex end function is_no_bounds_interval(x::String)::Bool result::Bool = occursin( get_no_bounds_interval_regex(), x, ) return result end function is_lower_and_upper_bound_interval(x::String)::Bool result::Bool = occursin( get_lower_and_upper_bound_interval_regex(), x, ) return result end function is_lower_bound_only_interval(x::String)::Bool result::Bool = occursin( get_lower_bound_only_interval_regex(), x, ) return result end function is_upper_bound_only_interval(x::String)::Bool result::Bool = occursin( get_upper_bound_only_interval_regex(), x, ) return result end function construct_interval(x::String)::AbstractInterval if is_no_bounds_interval(x) result = NoBoundsInterval() elseif is_lower_bound_only_interval(x) loweronly_regexmatch::RegexMatch = match( get_lower_bound_only_interval_regex(), x, ) loweronly_left::String = strip( convert(String, loweronly_regexmatch[1]) ) result = LowerBoundOnlyInterval(loweronly_left) elseif is_upper_bound_only_interval(x) upperonly_regexmatch::RegexMatch = match( get_upper_bound_only_interval_regex(), x, ) upperonly_right::String = strip( convert(String, upperonly_regexmatch[1]) ) result = UpperBoundOnlyInterval(upperonly_right) elseif is_lower_and_upper_bound_interval(x) lowerandupper_regexmatch::RegexMatch = match( get_lower_and_upper_bound_interval_regex(), x, ) lowerandupper_left::String = strip( convert(String, lowerandupper_regexmatch[1]) ) lowerandupper_right::String = strip( convert(String, lowerandupper_regexmatch[2]) ) result = LowerAndUpperBoundInterval( lowerandupper_left, lowerandupper_right, ) else error("argument is not a valid interval") end return result end function interval_contains_x( interval::NoBoundsInterval, x::AbstractString, )::Bool result::Bool = true return result end function interval_contains_x( interval::LowerAndUpperBoundInterval, x::AbstractString, )::Bool x_stripped::String = strip(convert(String, x)) left::String = strip(interval.left) right::String = strip(interval.right) result::Bool = (left <= x_stripped) && (x_stripped < right) return result end function interval_contains_x( interval::LowerBoundOnlyInterval, x::AbstractString, )::Bool x_stripped::String = strip(convert(String, x)) left::String = strip(interval.left) result::Bool = left <= x_stripped return result end function interval_contains_x( interval::UpperBoundOnlyInterval, x::AbstractString, ) x_stripped::String = strip(convert(String, x)) right::String = strip(interval.right) result::Bool = x_stripped < right return result end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
574
import Test ENV["PREDICTMD_IS_RUNTESTS"] = "true" Test.@testset "PredictMD.jl" begin ENV["PREDICTMD_IS_RUNTESTS"] = "true" import PredictMDExtra PredictMDExtra.import_all() include("intervals.jl") include("import-predictmd.jl") include("define-test-groups.jl") include("define-test-blocks.jl") include("get-test-group.jl") include("set-predictmd-test-plots.jl") include("set-predictmd-open-plots-during-tests.jl") include("all-testsets.jl") ENV["PREDICTMD_IS_RUNTESTS"] = "false" end ENV["PREDICTMD_IS_RUNTESTS"] = "false"
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
312
if length( lowercase(strip(get(ENV, "PREDICTMD_OPEN_PLOTS_DURING_TESTS", ""))) ) == 0 ENV["PREDICTMD_OPEN_PLOTS_DURING_TESTS"] = "false" end @debug( string( "PREDICTMD_OPEN_PLOTS_DURING_TESTS: \"", ENV["PREDICTMD_OPEN_PLOTS_DURING_TESTS"], "\"", ) )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
1226
if length(lowercase(strip(get(ENV, "PREDICTMD_TEST_PLOTS", "")))) == 0 ENV["PREDICTMD_TEST_PLOTS"] = "false" end if isa(TEST_GROUP, TestGroupAll) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupTestPlots) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupTravis1) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupTravis2) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupTravis3) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupTravis4) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupTravis5) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupTravis6) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupDocker1) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupDocker2) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupDocker3) ENV["PREDICTMD_TEST_PLOTS"] = "true" end if isa(TEST_GROUP, TestGroupDocker4) ENV["PREDICTMD_TEST_PLOTS"] = "true" end @info( string( "PREDICTMD_TEST_PLOTS: \"", ENV["PREDICTMD_TEST_PLOTS"], "\"", ) )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
693
import PredictMD import Test Test.@test( isdir(PredictMD.package_directory()) ) Test.@test( isdir(PredictMD.package_directory("ci")) ) Test.@test( isdir(PredictMD.package_directory("ci", "travis")) ) Test.@test( isdir(PredictMD.package_directory(PredictMDTestModuleA)) ) Test.@test( isdir(PredictMD.package_directory(PredictMDTestModuleB)) ) Test.@test( isdir( PredictMD.package_directory( PredictMDTestModuleB, "directory2", ) ) ) Test.@test( isdir( PredictMD.package_directory( PredictMDTestModuleB, "directory2", "directory3", ) ) ) Test.@test_throws( ErrorException, PredictMD.package_directory(PredictMDTestModuleC), )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
157
import PredictMD import Test # Test.@test(typeof(PredictMD.registry_url_list()) <: Vector{String}) # Test.@test(length(PredictMD.registry_url_list()) > 0)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
789
import PredictMD import Test Test.@test( Base.VERSION >= VersionNumber("1.0") ) Test.@test( PredictMD.version() > VersionNumber(0) ) Test.@test( PredictMD.version() == PredictMD.version(PredictMD) ) Test.@test( PredictMD.version() == PredictMD.version(first(methods(PredictMD.eval))) ) Test.@test( PredictMD.version() == PredictMD.version(PredictMD.eval) ) Test.@test( PredictMD.version() == PredictMD.version(PredictMD.eval, (Any,)) ) Test.@test( PredictMD.version(PredictMDTestModuleA) == VersionNumber("1.2.3") ) Test.@test( PredictMD.version(PredictMDTestModuleB) == VersionNumber("4.5.6") ) Test.@test_throws( ErrorException, PredictMD.TomlFile(joinpath(PredictMD.maketempdir(),"1","2","3","4")), )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
232
import PredictMDAPI struct Foo_Fittable{T} <: PredictMDAPI.AbstractFittable x::T end struct Bar_Fittable{T} <: PredictMDAPI.AbstractFittable x::T end struct Baz_Fittable{T} <: PredictMDAPI.AbstractFittable x::T end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
33
module PredictMDTestModuleA end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
33
module PredictMDTestModuleB end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
83
import PredictMD import Test Test.@test length(PredictMD.registry_url_list()) > 0
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
299
import Test import PredictMD a = PredictMD.version() Test.@test( typeof(a) == VersionNumber ) Test.@test( typeof(a) === VersionNumber ) Test.@test( a != VersionNumber(0) ) Test.@test( a > VersionNumber(0) ) Test.@test( a > VersionNumber("0.1.0") ) Test.@test( a < VersionNumber("123456789.0.0") )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
753
import Test import PredictMD a = PredictMD.package_directory() Test.@test( isdir(a) ) b = PredictMD.package_directory( "assets", ) Test.@test( isdir(b) ) Test.@test( dirname(b) == a ) c = PredictMD.package_directory( "assets", "icd", ) Test.@test( isdir(c) ) Test.@test( dirname(c) == b ) d = PredictMD.package_directory( "assets", "icd", "icd9", ) Test.@test( isdir(d) ) Test.@test( dirname(d) == c ) e = PredictMD.package_directory( "assets", "icd", "icd9", "ccs" ) Test.@test( isdir(e) ) Test.@test( dirname(e) == d ) f = PredictMD.package_directory( "assets", "icd", "icd9", "ccs", "AppendixASingleDX.txt" ) Test.@test( dirname(f) == e ) Test.@test( isfile(f) )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
377
import PredictMD import PredictMD.Cleaning Test.@test( PredictMD.Cleaning.x_contains_y("abc", ["xyz", "abc", "123",]) ) Test.@test( !PredictMD.Cleaning.x_contains_y("abc", ["xyz", "opqrst", "123",]) ) Test.@test( PredictMD.Cleaning.symbol_begins_with(:abcdefg, "abc") ) Test.@test( !PredictMD.Cleaning.symbol_begins_with(:abcdefg, "xyz") )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
68
import PredictMD PredictMD.import_all() PredictMD.import_all(Main)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
200
import PredictMD import Test if PredictMD.is_travis_ci_on_linux() Test.@test( PredictMD.is_filesystem_root("/") ) Test.@test_throws(ErrorException, PredictMD.find_package_directory("/")) end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
186
import PredictMD import Test if PredictMD.is_travis_ci() Test.@testset "Testing print_list_of_package_imports()" begin PredictMD.print_list_of_package_imports() end end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
169
import PredictMD import Test tmpdir = PredictMD.maketempdir() tmpfile = joinpath(tmpdir, "Project.toml") Test.@test_throws(ErrorException, PredictMD.TomlFile(tmpfile))
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
186
import PredictMD import Test Test.@test_throws ErrorException PredictMD.simple_linear_regression([1, 2], []) Test.@test_throws ErrorException PredictMD.simple_linear_regression([], [])
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
3680
import DataFrames import PredictMD import Test Test.@test_throws( ErrorException, PredictMD.calculate_smote_pct_under(;pct_over=-111,minority_to_majority_ratio=0.5), ) Test.@test_throws( ErrorException, PredictMD.calculate_smote_pct_under(;pct_over=100,minority_to_majority_ratio=-1.5), ) features_df_0rows = DataFrames.DataFrame() labels_df_0rows = DataFrames.DataFrame() labels_df_3rows = DataFrames.DataFrame() labels_df_3rows[:y] = [1,2,3] Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "", minorityclass = "", ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "", ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_3rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", minority_to_majority_ratio = 1, ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", minority_to_majority_ratio = 1, ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_0rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", minority_to_majority_ratio = 1, ), ) Test.@test_throws( ErrorException, PredictMD.smote(features_df_0rows, labels_df_3rows, Symbol[], :y; majorityclass = "majorityclass", minorityclass = "minorityclass", minority_to_majority_ratio = 1, ), )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
188
Test.@test_throws ErrorException PredictMD.generate_examples(PredictMD.maketempdir()) Test.@test_throws ErrorException PredictMD.generate_examples(PredictMD.maketempdir(); scripts = true)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
620
import Test import PredictMD y_true = [3, -0.5, 2, 7,] y_pred = [2.5, 0.0, 2, 8,] Test.@test( isapprox( PredictMD.r2_score(y_true, y_pred,), 0.948; atol = 0.001, ) ) y_true = [1,2,3,] y_pred = [1,2,3,] Test.@test( isapprox( PredictMD.r2_score(y_true, y_pred,), 1.0; ) ) y_true = [1,2,3,] y_pred = [2,2,2,] Test.@test( isapprox( PredictMD.r2_score(y_true, y_pred,), 0.0; ) ) y_true = [1,2,3,] y_pred = [3,2,1,] Test.@test( isapprox( PredictMD.r2_score(y_true, y_pred,), -3.0; ) )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
477
import Test import PredictMD table1 = [20 5; 10 15] Test.@test( isapprox(PredictMD.cohen_kappa(table1), 0.4; atol = 0.00000000001) ) table2 = [45 15; 25 15] Test.@test( isapprox(PredictMD.cohen_kappa(table2), 0.1304; atol = 0.0001) ) table3 = [25 35; 5 35] Test.@test( isapprox(PredictMD.cohen_kappa(table3), 0.2593; atol = 0.0001) ) table4 = [9 3 1; 4 8 2 ; 2 1 6] Test.@test( isapprox(PredictMD.cohen_kappa(table4), 0.45; atol = 0.001) )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
26037
import PredictMD import StatsBase import Test Test.@test_throws(ArgumentError, PredictMD.get_number_in_each_fold(1, 2)) Test.@test_throws(DimensionMismatch, PredictMD.get_top_level_num_folds(PredictMD.CrossValidation{Int}(PredictMD.CrossValidation{Int}[PredictMD.CrossValidation{Int}(; all_indices = [1,2,3,4,5,6,7,8,9,10], num_folds_per_level = (2,2,2))], Vector{Int}[]))) Test.@test(PredictMD.get_top_level_num_folds(PredictMD.CrossValidation{Int}(PredictMD.CrossValidation{Int}[], Vector{Int}[])) == 0) Test.@testset "CrossValidation" begin Test.@testset "get_number_in_each_fold" begin @debug("get_number_in_each_fold") Test.@test( sum(PredictMD.get_number_in_each_fold(100, 1)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 1) == [100] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 2)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 2) == [50, 50] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 3)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 3) == [34, 33, 33] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 4)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 4) == [25, 25, 25, 25] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 5)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 5) == [20, 20, 20, 20, 20] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 6)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 6) == [17, 17, 17, 17, 16, 16] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 7)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 7) == [15, 15, 14, 14, 14, 14, 14] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 8)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 8) == [13, 13, 13, 13, 12, 12, 12, 12] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 9)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 9) == [12, 11, 11, 11, 11, 11, 11, 11, 11] ) Test.@test( sum(PredictMD.get_number_in_each_fold(100, 10)) == 100 ) Test.@test( PredictMD.get_number_in_each_fold(100, 10) == [10, 10, 10, 10, 10, 10, 10, 10, 10, 10] ) end Test.@testset "get_indices_in_each_fold" begin @debug("get_indices_in_each_fold") Test.@test( PredictMD.get_indices_in_each_fold([1,2,3,4,5,6,7,8,9,10], 3) == [[1,2,3,4], [5,6,7], [8,9,10]] ) Test.@test( PredictMD.get_indices_in_each_fold([5,6,7,8,9,10], 3) == [[5,6], [7,8], [9,10]] ) Test.@test( PredictMD.get_indices_in_each_fold([1,2,3,4,8,9,10], 3) == [[1,2,3], [4,8], [9,10]] ) Test.@test( PredictMD.get_indices_in_each_fold([1,2,3,4,5,6,7], 3) == [[1,2,3], [4,5], [6,7]] ) end Test.@testset "get_leavein_indices on vector of integers" begin @debug("get_leavein_indices") Test.@test( PredictMD.get_leavein_indices([1,2,3,4,5,6,7,8,9,10], 3, 1) == [5,6,7,8,9,10] ) Test.@test( PredictMD.get_leavein_indices([1,2,3,4,5,6,7,8,9,10], 3, 2) == [1,2,3,4,8,9,10] ) Test.@test( PredictMD.get_leavein_indices([1,2,3,4,5,6,7,8,9,10], 3, 3) == [1,2,3,4,5,6,7] ) end Test.@testset "get_leaveout_indices on vector of integers" begin @debug("get_leaveout_indices") Test.@test( PredictMD.get_leaveout_indices([1,2,3,4,5,6,7,8,9,10], 3, 1) == [1,2,3,4] ) Test.@test( PredictMD.get_leaveout_indices([1,2,3,4,5,6,7,8,9,10], 3, 2) == [5,6,7] ) Test.@test( PredictMD.get_leaveout_indices([1,2,3,4,5,6,7,8,9,10], 3, 3) == [8,9,10] ) end Test.@testset "nested cross validation, integer indices, small" begin @debug("nested cross validation, integer indices, small") cv = PredictMD.CrossValidation{Int}(; all_indices = [1,2,3,4,5,6,7,8,9,10], num_folds_per_level = (2,2,2)) Test.@test( isa(cv, PredictMD.CrossValidation{Int}) ) Test.@test( !PredictMD.isleaf(cv) ) Test.@test( PredictMD.get_top_level_num_folds(cv) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv, 1) == [1,2,3,4,5] ) Test.@test( PredictMD.get_leaveout_indices(cv, 2) == [6,7,8,9,10] ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv) ) cv_1 = PredictMD.get_leavein_cv(cv, 1) Test.@test( !PredictMD.isleaf(cv_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_1, 1) == [6,7,8] ) Test.@test( PredictMD.get_leaveout_indices(cv_1, 2) == [9,10] ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_1) ) cv_2 = PredictMD.get_leavein_cv(cv, 2) Test.@test( !PredictMD.isleaf(cv_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_2, 1) == [1,2,3]) Test.@test( PredictMD.get_leaveout_indices(cv_2, 2) == [4,5]) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_2) ) cv_1_1 = PredictMD.get_leavein_cv(cv_1, 1) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_1_1) ) Test.@test( !PredictMD.isleaf(cv_1_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_1) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_1_1, 1) == [9] ) Test.@test( PredictMD.get_leaveout_indices(cv_1_1, 2) == [10] ) cv_1_2 = PredictMD.get_leavein_cv(cv_1, 2) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_1_2) ) Test.@test( !PredictMD.isleaf(cv_1_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_2) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_1_2, 1) == [6, 7] ) Test.@test( PredictMD.get_leaveout_indices(cv_1_2, 2) == [8] ) cv_2_1 = PredictMD.get_leavein_cv(cv_2, 1) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_2_1) ) Test.@test( !PredictMD.isleaf(cv_2_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_1) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_2_1, 1) == [4] ) Test.@test( PredictMD.get_leaveout_indices(cv_2_1, 2) == [5] ) cv_2_2 = PredictMD.get_leavein_cv(cv_2, 2) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_2_2) ) Test.@test( !PredictMD.isleaf(cv_2_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_2) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_2_2, 1) == [1,2] ) Test.@test( PredictMD.get_leaveout_indices(cv_2_2, 2) == [3] ) cv_1_1_1 = PredictMD.get_leavein_cv(cv_1_1, 1) Test.@test( PredictMD.isleaf(cv_1_1_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_1_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_1_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_1_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_1_1) == [10] ) cv_1_1_2 = PredictMD.get_leavein_cv(cv_1_1, 2) Test.@test( PredictMD.isleaf(cv_1_1_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_1_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_1_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_1_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_1_2) == [9] ) cv_1_2_1 = PredictMD.get_leavein_cv(cv_1_2, 1) Test.@test( PredictMD.isleaf(cv_1_2_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_2_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_2_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_2_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_2_1) == [8] ) cv_1_2_2 = PredictMD.get_leavein_cv(cv_1_2, 2) Test.@test( PredictMD.isleaf(cv_1_2_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_2_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_2_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_2_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_2_2) == [6,7] ) cv_2_1_1 = PredictMD.get_leavein_cv(cv_2_1, 1) Test.@test( PredictMD.isleaf(cv_2_1_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_1_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_1_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_1_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_1_1) == [5] ) cv_2_1_2 = PredictMD.get_leavein_cv(cv_2_1, 2) Test.@test( PredictMD.isleaf(cv_2_1_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_1_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_1_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_1_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_1_2) == [4] ) cv_2_2_1 = PredictMD.get_leavein_cv(cv_2_2, 1) Test.@test( PredictMD.isleaf(cv_2_2_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_2_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_2_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_2_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_2_1) == [3] ) cv_2_2_2 = PredictMD.get_leavein_cv(cv_2_2, 2) Test.@test( PredictMD.isleaf(cv_2_2_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_2_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_2_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_2_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_2_2) == [1,2] ) end Test.@testset "nested cross validation, range indices, small" begin @debug("nested cross validation, range indices, small") cv_integers = PredictMD.CrossValidation{Int}(; all_indices = [1,2,3,4,5,6,7,8,9,10], num_folds_per_level = (2,2,2)) Test.@test( isa(cv_integers, PredictMD.CrossValidation{Int}) ) cv_ranges = PredictMD.CrossValidation{UnitRange{Int}}(cv_integers) Test.@test( isa(cv_ranges, PredictMD.CrossValidation{UnitRange{Int}}) ) Test.@test( !PredictMD.isleaf(cv_ranges) ) Test.@test( PredictMD.get_top_level_num_folds(cv_ranges) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_ranges, 1) == [1:5] ) Test.@test( PredictMD.get_leaveout_indices(cv_ranges, 2) == [6:10] ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_ranges) ) cv_1 = PredictMD.get_leavein_cv(cv_ranges, 1) Test.@test( !PredictMD.isleaf(cv_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_1, 1) == [6:8] ) Test.@test( PredictMD.get_leaveout_indices(cv_1, 2) == [9:10] ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_1) ) cv_2 = PredictMD.get_leavein_cv(cv_ranges, 2) Test.@test( !PredictMD.isleaf(cv_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_2, 1) == [1:3]) Test.@test( PredictMD.get_leaveout_indices(cv_2, 2) == [4:5]) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_2) ) cv_1_1 = PredictMD.get_leavein_cv(cv_1, 1) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_1_1) ) Test.@test( !PredictMD.isleaf(cv_1_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_1) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_1_1, 1) == [9:9] ) Test.@test( PredictMD.get_leaveout_indices(cv_1_1, 2) == [10:10] ) cv_1_2 = PredictMD.get_leavein_cv(cv_1, 2) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_1_2) ) Test.@test( !PredictMD.isleaf(cv_1_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_2) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_1_2, 1) == [6:7] ) Test.@test( PredictMD.get_leaveout_indices(cv_1_2, 2) == [8:8] ) cv_2_1 = PredictMD.get_leavein_cv(cv_2, 1) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_2_1) ) Test.@test( !PredictMD.isleaf(cv_2_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_1) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_2_1, 1) == [4:4] ) Test.@test( PredictMD.get_leaveout_indices(cv_2_1, 2) == [5:5] ) cv_2_2 = PredictMD.get_leavein_cv(cv_2, 2) Test.@test_throws( ArgumentError, PredictMD.get_leavein_indices(cv_2_2) ) Test.@test( !PredictMD.isleaf(cv_2_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_2) == 2 ) Test.@test( PredictMD.get_leaveout_indices(cv_2_2, 1) == [1:2] ) Test.@test( PredictMD.get_leaveout_indices(cv_2_2, 2) == [3:3] ) cv_1_1_1 = PredictMD.get_leavein_cv(cv_1_1, 1) Test.@test( PredictMD.isleaf(cv_1_1_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_1_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_1_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_1_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_1_1) == [10:10] ) cv_1_1_2 = PredictMD.get_leavein_cv(cv_1_1, 2) Test.@test( PredictMD.isleaf(cv_1_1_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_1_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_1_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_1_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_1_2) == [9:9] ) cv_1_2_1 = PredictMD.get_leavein_cv(cv_1_2, 1) Test.@test( PredictMD.isleaf(cv_1_2_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_2_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_2_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_2_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_2_1) == [8:8] ) cv_1_2_2 = PredictMD.get_leavein_cv(cv_1_2, 2) Test.@test( PredictMD.isleaf(cv_1_2_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_1_2_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_1_2_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_1_2_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_1_2_2) == [6:7] ) cv_2_1_1 = PredictMD.get_leavein_cv(cv_2_1, 1) Test.@test( PredictMD.isleaf(cv_2_1_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_1_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_1_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_1_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_1_1) == [5:5] ) cv_2_1_2 = PredictMD.get_leavein_cv(cv_2_1, 2) Test.@test( PredictMD.isleaf(cv_2_1_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_1_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_1_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_1_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_1_2) == [4:4] ) cv_2_2_1 = PredictMD.get_leavein_cv(cv_2_2, 1) Test.@test( PredictMD.isleaf(cv_2_2_1) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_2_1) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_2_1, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_2_1, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_2_1) == [3:3] ) cv_2_2_2 = PredictMD.get_leavein_cv(cv_2_2, 2) Test.@test( PredictMD.isleaf(cv_2_2_2) ) Test.@test( PredictMD.get_top_level_num_folds(cv_2_2_2) == 0 ) Test.@test_throws( ArgumentError, PredictMD.get_leaveout_indices(cv_2_2_2, 1) ) Test.@test_throws( ArgumentError, PredictMD.get_leavein_cv(cv_2_2_2, 1) ) Test.@test( PredictMD.get_leavein_indices(cv_2_2_2) == [1:2] ) end Test.@testset "nested cross validation, integer indices, large" begin @debug("nested cross validation, integer indices, large") num_samples = 1_000 master_cv = PredictMD.CrossValidation{Int}(; all_indices = collect(1:num_samples), num_folds_per_level = (3,5,7)) Test.@test( isa(master_cv, PredictMD.CrossValidation{Int}) ) Test.@test( PredictMD.get_all_indices(master_cv) == 1:num_samples) Test.@test( !PredictMD.isleaf(master_cv) ) Test.@test( PredictMD.get_top_level_num_folds(master_cv) == 3 ) for i = 1:3 @debug("i = $(i)") testing_indices = PredictMD.get_leaveout_indices(master_cv, i) supertuning_tuning_training_cv = PredictMD.get_leavein_cv(master_cv, i) Test.@test( length(intersect(testing_indices, PredictMD.get_all_indices(supertuning_tuning_training_cv))) == 0 ) Test.@test( sort(unique(union(testing_indices, PredictMD.get_all_indices(supertuning_tuning_training_cv)))) == 1:num_samples ) Test.@test( !PredictMD.isleaf(supertuning_tuning_training_cv) ) Test.@test( PredictMD.get_top_level_num_folds(supertuning_tuning_training_cv) == 5 ) for j = 1:5 @debug("j = $(j)") supertuning_indices = PredictMD.get_leaveout_indices(supertuning_tuning_training_cv, j) tuning_training_cv = PredictMD.get_leavein_cv(supertuning_tuning_training_cv, j) Test.@test( !PredictMD.isleaf(tuning_training_cv) ) Test.@test( PredictMD.get_top_level_num_folds(tuning_training_cv) == 7 ) for k = 1:7 @debug("k = $(k)") tuning_indices = PredictMD.get_leaveout_indices(tuning_training_cv, k) training_cv = PredictMD.get_leavein_cv(tuning_training_cv, k) Test.@test( PredictMD.isleaf(training_cv) ) Test.@test( PredictMD.get_top_level_num_folds(training_cv) == 0 ) training_indices = PredictMD.get_leavein_indices(training_cv) Test.@test( length(intersect(testing_indices, supertuning_indices)) == 0 ) Test.@test( length(intersect(testing_indices, tuning_indices)) == 0 ) Test.@test( length(intersect(testing_indices, training_indices)) == 0 ) Test.@test( length(intersect(supertuning_indices, tuning_indices)) == 0 ) Test.@test( length(intersect(supertuning_indices, training_indices)) == 0 ) Test.@test( length(intersect(tuning_indices, training_indices)) == 0 ) end end end end Test.@testset "nested cross validation, range indices, large" begin @debug("nested cross validation, range indices, large") num_samples = 1_000 master_cv_integers = PredictMD.CrossValidation{Int}(; all_indices = collect(1:num_samples), num_folds_per_level = (3,5,7)) Test.@test( isa(master_cv_integers, PredictMD.CrossValidation{Int}) ) master_cv_ranges = PredictMD.CrossValidation{UnitRange{Int}}(master_cv_integers) Test.@test( isa(master_cv_ranges, PredictMD.CrossValidation{UnitRange{Int}}) ) Test.@test( !PredictMD.isleaf(master_cv_ranges) ) Test.@test( PredictMD.get_top_level_num_folds(master_cv_ranges) == 3 ) for i = 1:3 @debug("i = $(i)") testing_indices = PredictMD.get_leaveout_indices(master_cv_ranges, i) supertuning_tuning_training_cv = PredictMD.get_leavein_cv(master_cv_ranges, i) Test.@test( !PredictMD.isleaf(supertuning_tuning_training_cv) ) Test.@test( PredictMD.get_top_level_num_folds(supertuning_tuning_training_cv) == 5 ) for j = 1:5 @debug("j = $(j)") supertuning_indices = PredictMD.get_leaveout_indices(supertuning_tuning_training_cv, j) tuning_training_cv = PredictMD.get_leavein_cv(supertuning_tuning_training_cv, j) Test.@test( !PredictMD.isleaf(tuning_training_cv) ) Test.@test( PredictMD.get_top_level_num_folds(tuning_training_cv) == 7 ) for k = 1:7 @debug("k = $(k)") tuning_indices = PredictMD.get_leaveout_indices(tuning_training_cv, k) training_cv = PredictMD.get_leavein_cv(tuning_training_cv, k) Test.@test( PredictMD.isleaf(training_cv) ) Test.@test( PredictMD.get_top_level_num_folds(training_cv) == 0 ) training_indices = PredictMD.get_leavein_indices(training_cv) Test.@test( length(intersect(testing_indices, supertuning_indices)) == 0 ) Test.@test( length(intersect(testing_indices, tuning_indices)) == 0 ) Test.@test( length(intersect(testing_indices, training_indices)) == 0 ) Test.@test( length(intersect(supertuning_indices, tuning_indices)) == 0 ) Test.@test( length(intersect(supertuning_indices, training_indices)) == 0 ) Test.@test( length(intersect(tuning_indices, training_indices)) == 0 ) end end end end Test.@testset "roundtrip CV integer indices <-> CV range indices" begin @debug("roundtrip CV integer indices <-> CV range indices") num_samples = 1_000 cv_integer_1 = PredictMD.CrossValidation{Int}(; all_indices = collect(1:num_samples), num_folds_per_level = (3,5,7)) cv_ranges_2 = PredictMD.CrossValidation{UnitRange{Int}}(cv_integer_1) cv_integer_3 = PredictMD.CrossValidation{Int}(cv_ranges_2) cv_ranges_4 = PredictMD.CrossValidation{UnitRange{Int}}(cv_integer_3) cv_integer_5 = PredictMD.CrossValidation{Int}(cv_ranges_4) cv_ranges_6 = PredictMD.CrossValidation{UnitRange{Int}}(cv_integer_5) cv_integer_7 = PredictMD.CrossValidation{Int}(cv_ranges_6) cv_ranges_8 = PredictMD.CrossValidation{UnitRange{Int}}(cv_integer_7) cv_integer_9 = PredictMD.CrossValidation{Int}(cv_ranges_8) Test.@test( isa(cv_integer_1, PredictMD.CrossValidation{Int}) ) Test.@test( isa(cv_integer_3, PredictMD.CrossValidation{Int}) ) Test.@test( isa(cv_integer_5, PredictMD.CrossValidation{Int}) ) Test.@test( isa(cv_integer_7, PredictMD.CrossValidation{Int}) ) Test.@test( isa(cv_integer_9, PredictMD.CrossValidation{Int}) ) Test.@test( isa(cv_ranges_2, PredictMD.CrossValidation{UnitRange{Int}}) ) Test.@test( isa(cv_ranges_4, PredictMD.CrossValidation{UnitRange{Int}}) ) Test.@test( isa(cv_ranges_6, PredictMD.CrossValidation{UnitRange{Int}}) ) Test.@test( isa(cv_ranges_8, PredictMD.CrossValidation{UnitRange{Int}}) ) Test.@test( cv_integer_1 == cv_integer_3 == cv_integer_5 == cv_integer_7 == cv_integer_9) Test.@test( cv_ranges_2 == cv_ranges_4 == cv_ranges_6 == cv_ranges_8) end Test.@testset "vectors_to_ranges" begin @debug("vectors_to_ranges") x = Int[ 12, 28, 27, 24, 21, 30, 6, 10, 4, 18, 16, 36, 35, 29, 15, 9, 19, 34, 17, 5, 23, 3, 26, 37, 20, 11, 7, ] y = UnitRange{Int}[ 3:7, 9:12, 15:21, 23:24, 26:30, 34:37, ] Test.@test y == PredictMD.vector_to_ranges(x) vector_1 = StatsBase.sample(1:100_000_000, 100_000) unique!(vector_1) sort!(vector_1) ranges_2 = PredictMD.vector_to_ranges(vector_1) vector_3 = PredictMD.ranges_to_vector(ranges_2) ranges_4 = PredictMD.vector_to_ranges(vector_3) vector_5 = PredictMD.ranges_to_vector(ranges_4) ranges_6 = PredictMD.vector_to_ranges(vector_5) vector_7 = PredictMD.ranges_to_vector(ranges_6) ranges_8 = PredictMD.vector_to_ranges(vector_7) vector_9 = PredictMD.ranges_to_vector(ranges_8) Test.@test vector_1 == vector_3 == vector_5 == vector_7 == vector_9 Test.@test ranges_2 == ranges_4 == ranges_6 == ranges_8 end Test.@testset "ranges_to_vectors" begin @debug("ranges_to_vectors") x = Int[ 12, 28, 27, 24, 21, 30, 6, 10, 4, 18, 16, 36, 35, 29, 15, 9, 19, 34, 17, 5, 23, 3, 26, 37, 20, 11, 7, ] y = UnitRange{Int}[ 3:7, 9:12, 15:21, 23:24, 26:30, 34:37, ] Test.@test sort(x) == PredictMD.ranges_to_vector(y) ranges_1 = Vector{UnitRange{Int}}(undef, 0) for i = 1:100 a = StatsBase.sample((i)*(1_000_000):(i+1)*(1_000_000)) b = StatsBase.sample((i)*(1_000_000):(i+1)*(1_000_000)) push!(ranges_1, min(a,b):max(a,b)) end unique!(ranges_1) sort!(ranges_1) vector_2 = PredictMD.ranges_to_vector(ranges_1) ranges_3 = PredictMD.vector_to_ranges(vector_2) vector_4 = PredictMD.ranges_to_vector(ranges_3) ranges_5 = PredictMD.vector_to_ranges(vector_4) vector_6 = PredictMD.ranges_to_vector(ranges_5) ranges_7 = PredictMD.vector_to_ranges(vector_6) vector_8 = PredictMD.ranges_to_vector(ranges_7) ranges_9 = PredictMD.vector_to_ranges(vector_8) Test.@test ranges_1 == ranges_3 == ranges_5 == ranges_7 == ranges_9 Test.@test vector_2 == vector_4 == vector_6 == vector_8 end end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
492
features_df = DataFrames.DataFrame() labels_df = DataFrames.DataFrame() labels_df[:y] = [1,2,3] Test.@test_throws(ErrorException, PredictMD.split_data(features_df, labels_df, 2.0)) Test.@test_throws(ErrorException, PredictMD.split_data(features_df, labels_df, 0.5))
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
709
Test.@test( PredictMD.remove_all_full_stops(".1.2.3.4.") == "1234" ) Test.@test( PredictMD.remove_all_full_stops("1234") == "1234" ) PredictMD.parse_icd_icd9_ccs_appendixasingledx_file!() PredictMD.parse_icd_icd9_ccs_appendixasingledx_file!() PredictMD.parse_icd_icd9_ccs_appendixasingledx_file!() Test.@test(PredictMD.single_level_dx_ccs_number_to_name(1) == "Tuberculosis") Test.@test(PredictMD.single_level_dx_ccs_number_to_name(2) == "Septicemia (except in labor)") Test.@test( all(sort(unique( PredictMD.single_level_dx_ccs_to_list_of_icd9_codes(107))) .== sort(unique(["42741", "42742", "4275"]))) ) Test.@test(PredictMD.icd9_code_to_single_level_dx_ccs("42741") == 107)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
28675
import PredictMD import Test Test.@test Base.IteratorEltype(PredictMD.SimplePipeline{String, Vector}) == Base.HasEltype() Test.@test Base.IteratorSize(PredictMD.SimplePipeline{String, Vector}) == Base.HasShape{1}() Test.@test Base.IndexStyle(PredictMD.SimplePipeline{String, Vector}) == Base.IndexLinear() a = PredictMD.SimplePipeline("name", PredictMD.AbstractFittable[]) Test.@test PredictMD.ispipeline(a) Test.@test PredictMD.isflat(a) Test.@test a isa PredictMD.SimplePipeline Test.@test isempty(a) Test.@test length(a) == 0 Test.@test ndims(a) == 1 Test.@test length(size(a)) == 1 Test.@test size(a) == (0,) Test.@test size(a)[1] == 0 PredictMD.get_underlying(a) PredictMD.get_history(a) empty!(a) Test.@test !PredictMD.ispipeline(Foo_Fittable(0)) b = Foo_Fittable(11) |> Bar_Fittable(22) c = Foo_Fittable(11) |> Bar_Fittable(22) |> Baz_Fittable(30) d = Foo_Fittable(11) |> Bar_Fittable(22) |> Baz_Fittable(30) |> Foo_Fittable(40) |> Bar_Fittable(50) |> Baz_Fittable(60) e = PredictMD.SimplePipeline("name", PredictMD.AbstractFittable[Baz_Fittable(11)]) Test.@test PredictMD.ispipeline(b) Test.@test PredictMD.ispipeline(c) Test.@test PredictMD.ispipeline(d) Test.@test PredictMD.ispipeline(e) Test.@test PredictMD.isflat(b) Test.@test PredictMD.isflat(c) Test.@test PredictMD.isflat(d) Test.@test PredictMD.isflat(e) Test.@test b isa PredictMD.SimplePipeline Test.@test c isa PredictMD.SimplePipeline Test.@test d isa PredictMD.SimplePipeline Test.@test e isa PredictMD.SimplePipeline Test.@test !isempty(b) Test.@test !isempty(c) Test.@test !isempty(d) Test.@test !isempty(e) Test.@test length(b) == 2 Test.@test ndims(b) == 1 Test.@test length(size(b)) == 1 Test.@test size(b) == (2,) Test.@test size(b)[1] == 2 Test.@test length(c) == 3 Test.@test ndims(c) == 1 Test.@test length(size(c)) == 1 Test.@test size(c) == (3,) Test.@test size(c)[1] == 3 Test.@test length(d) == 6 Test.@test ndims(d) == 1 Test.@test length(size(d)) == 1 Test.@test size(d) == (6,) Test.@test size(d)[1] == 6 Test.@test length(e) == 1 Test.@test ndims(e) == 1 Test.@test length(size(e)) == 1 Test.@test size(e) == (1,) Test.@test size(e)[1] == 1 Test.@test b[1] == Foo_Fittable(11) Test.@test b[2] == Bar_Fittable(22) Test.@test c[1] == Foo_Fittable(11) Test.@test c[2] == Bar_Fittable(22) Test.@test c[3] == Baz_Fittable(30) Test.@test c[1:3] == [Foo_Fittable(11), Bar_Fittable(22), Baz_Fittable(30)] Test.@test view(c, 2:3)[1] == Bar_Fittable(22) Test.@test view(c, 2:3)[2] == Baz_Fittable(30) for x in c Test.@test x isa PredictMD.AbstractFittable end c[2] = Foo_Fittable(22) Test.@test c[1] == Foo_Fittable(11) Test.@test c[2] == Foo_Fittable(22) Test.@test c[3] == Baz_Fittable(30) Test.@test e[1] == Baz_Fittable(11) for x in e Test.@test x == Baz_Fittable(11) end Test.@test isassigned(e, 1) Test.@test isa(Foo_Fittable(11) |> Bar_Fittable(22), PredictMD.SimplePipeline) Test.@test isa(PredictMD.SimplePipeline("", [Foo_Fittable(11)]) |> Bar_Fittable(22), PredictMD.SimplePipeline) Test.@test isa(Foo_Fittable(11) |> PredictMD.SimplePipeline("", [Bar_Fittable(22)]), PredictMD.SimplePipeline) Test.@test isa(PredictMD.SimplePipeline("", [Foo_Fittable(11)]) |> PredictMD.SimplePipeline("", [Bar_Fittable(22)]), PredictMD.SimplePipeline) f = Foo_Fittable(1) |> Foo_Fittable(2) |> Foo_Fittable(3) |> Foo_Fittable(4) |> Foo_Fittable(5) |> Foo_Fittable(6) |> Foo_Fittable(7) Test.@test PredictMD.ispipeline(f) Test.@test PredictMD.isflat(f) for x in f Test.@test x isa Foo_Fittable end for i = 1:length(f) Test.@test f[i] isa Foo_Fittable Test.@test f[i] == Foo_Fittable(i) Test.@test f[i].x == i end for i = 1:size(f,1) Test.@test f[i] isa Foo_Fittable Test.@test f[i] == Foo_Fittable(i) Test.@test f[i].x == i end for i = 1:size(f)[1] Test.@test f[i] isa Foo_Fittable Test.@test f[i] == Foo_Fittable(i) Test.@test f[i].x == i end Test.@test ndims(f) == 1 Test.@test length(f) == 7 Test.@test size(f) == (7,) Test.@test size(f)[1] == 7 Test.@test length(size(f)) == 1 g = Foo_Fittable(1) |> Bar_Fittable(2) |> Baz_Fittable(3) |> Foo_Fittable(4) |> Bar_Fittable(5) |> Baz_Fittable(6) |> Foo_Fittable(7) Test.@test PredictMD.ispipeline(g) Test.@test PredictMD.isflat(g) for x in g Test.@test x isa PredictMD.AbstractFittable end for i = 1:length(g) Test.@test g[i] isa PredictMD.AbstractFittable Test.@test g[i].x == i end for i = 1:size(g,1) Test.@test g[i] isa PredictMD.AbstractFittable Test.@test g[i].x == i end for i = 1:size(g)[1] Test.@test g[i] isa PredictMD.AbstractFittable Test.@test g[i].x == i end Test.@test ndims(g) == 1 Test.@test length(g) == 7 Test.@test size(g) ==(7,) Test.@test size(g)[1] == 7 Test.@test length(size(g)) == 1 h = Foo_Fittable(11) |> Bar_Fittable(22) i = PredictMD.SimplePipeline([Foo_Fittable(11)]) |> Bar_Fittable(22) j = Foo_Fittable(11) |> PredictMD.SimplePipeline([Bar_Fittable(22)]) k = PredictMD.SimplePipeline([Foo_Fittable(11)]) |> PredictMD.SimplePipeline([Bar_Fittable(22)]) Test.@test PredictMD.ispipeline(h) Test.@test PredictMD.ispipeline(i) Test.@test PredictMD.ispipeline(j) Test.@test PredictMD.ispipeline(k) Test.@test PredictMD.isflat(h) Test.@test PredictMD.isflat(i) Test.@test PredictMD.isflat(j) Test.@test PredictMD.isflat(k) Test.@test h[1] == Foo_Fittable(11) Test.@test i[1] == Foo_Fittable(11) Test.@test j[1] == Foo_Fittable(11) Test.@test k[1] == Foo_Fittable(11) Test.@test h[2] == Bar_Fittable(22) Test.@test i[2] == Bar_Fittable(22) Test.@test j[2] == Bar_Fittable(22) Test.@test k[2] == Bar_Fittable(22) Test.@test h[1].x == 11 Test.@test i[1].x == 11 Test.@test j[1].x == 11 Test.@test k[1].x == 11 Test.@test h[2].x == 22 Test.@test i[2].x == 22 Test.@test j[2].x == 22 Test.@test k[2].x == 22 aa = PredictMD.SimplePipeline([Foo_Fittable(10), Foo_Fittable(20), Foo_Fittable(30)]; name = "aa") bb = PredictMD.SimplePipeline([Foo_Fittable(40), Foo_Fittable(50), Foo_Fittable(60)]; name = "bb") cc = PredictMD.SimplePipeline([Foo_Fittable(70), Foo_Fittable(80), Foo_Fittable(90)]; name = "cc") Test.@test PredictMD.ispipeline(aa) Test.@test PredictMD.ispipeline(bb) Test.@test PredictMD.ispipeline(cc) Test.@test PredictMD.isflat(aa) Test.@test PredictMD.isflat(bb) Test.@test PredictMD.isflat(cc) dd = PredictMD.SimplePipeline([Foo_Fittable(100), Foo_Fittable(110), Foo_Fittable(120)]; name = "dd") ee = PredictMD.SimplePipeline([Foo_Fittable(130), Foo_Fittable(140), Foo_Fittable(150)]; name = "ee") Test.@test PredictMD.ispipeline(dd) Test.@test PredictMD.ispipeline(ee) Test.@test PredictMD.isflat(dd) Test.@test PredictMD.isflat(ee) ff = PredictMD.SimplePipeline([Foo_Fittable(160), Foo_Fittable(170), Foo_Fittable(180)]; name = "ff") gg = PredictMD.SimplePipeline([Foo_Fittable(190), Foo_Fittable(200), Foo_Fittable(210)]; name = "gg") Test.@test PredictMD.ispipeline(ff) Test.@test PredictMD.ispipeline(gg) Test.@test PredictMD.isflat(ff) Test.@test PredictMD.isflat(gg) hh = PredictMD.SimplePipeline([aa, bb, cc]) ii = PredictMD.SimplePipeline([dd, ee]) jj = PredictMD.SimplePipeline([ff, gg]) Test.@test PredictMD.ispipeline(hh) Test.@test PredictMD.ispipeline(ii) Test.@test PredictMD.ispipeline(jj) Test.@test !PredictMD.isflat(hh) Test.@test !PredictMD.isflat(ii) Test.@test !PredictMD.isflat(jj) kk = PredictMD.SimplePipeline([hh]) ll = PredictMD.SimplePipeline([ii, jj]) |> Foo_Fittable(220) Test.@test PredictMD.ispipeline(kk) Test.@test PredictMD.ispipeline(ll) Test.@test !PredictMD.ispipeline(Foo_Fittable(220)) Test.@test !PredictMD.isflat(kk) Test.@test !PredictMD.isflat(ll) mm = PredictMD.SimplePipeline([kk, ll]) Test.@test PredictMD.ispipeline(mm) Test.@test !PredictMD.isflat(mm) mm_flattened = PredictMD.flatten(mm) Test.@test PredictMD.ispipeline(mm_flattened) Test.@test PredictMD.isflat(mm_flattened) Test.@test mm_flattened isa PredictMD.SimplePipeline for x in mm_flattened Test.@test x isa Foo_Fittable end for i = 1:length(mm_flattened) Test.@test mm_flattened[i] isa Foo_Fittable Test.@test mm_flattened[i] == Foo_Fittable(i*10) Test.@test mm_flattened[i].x == i*10 end for i = 1:size(mm_flattened,1) Test.@test mm_flattened[i] isa Foo_Fittable Test.@test mm_flattened[i] == Foo_Fittable(i*10) Test.@test mm_flattened[i].x == i*10 end for i = 1:size(mm_flattened)[1] Test.@test mm_flattened[i] isa Foo_Fittable Test.@test mm_flattened[i] == Foo_Fittable(i*10) Test.@test mm_flattened[i].x == i*10 end Test.@test length(mm_flattened) == 22 Test.@test ndims(mm_flattened) == 1 Test.@test length(size(mm_flattened)) == 1 Test.@test size(mm_flattened) == (22,) Test.@test size(mm_flattened)[1] == 22 Test.@test mm_flattened[1] == Foo_Fittable(10) Test.@test mm_flattened[2] == Foo_Fittable(20) Test.@test mm_flattened[3] == Foo_Fittable(30) Test.@test mm_flattened[4] == Foo_Fittable(40) Test.@test mm_flattened[5] == Foo_Fittable(50) Test.@test mm_flattened[6] == Foo_Fittable(60) Test.@test mm_flattened[7] == Foo_Fittable(70) Test.@test mm_flattened[8] == Foo_Fittable(80) Test.@test mm_flattened[9] == Foo_Fittable(90) Test.@test mm_flattened[10] == Foo_Fittable(100) Test.@test mm_flattened[11] == Foo_Fittable(110) Test.@test mm_flattened[12] == Foo_Fittable(120) Test.@test mm_flattened[13] == Foo_Fittable(130) Test.@test mm_flattened[14] == Foo_Fittable(140) Test.@test mm_flattened[15] == Foo_Fittable(150) Test.@test mm_flattened[16] == Foo_Fittable(160) Test.@test mm_flattened[17] == Foo_Fittable(170) Test.@test mm_flattened[18] == Foo_Fittable(180) Test.@test mm_flattened[19] == Foo_Fittable(190) Test.@test mm_flattened[20] == Foo_Fittable(200) Test.@test mm_flattened[21] == Foo_Fittable(210) Test.@test mm_flattened[22] == Foo_Fittable(220) mm_flat_on_creation_in_one_step_from_some_primitives = aa |> bb |> cc |> dd |> ee |> ff |> gg |> Foo_Fittable(220) Test.@test PredictMD.ispipeline(mm_flat_on_creation_in_one_step_from_some_primitives) Test.@test PredictMD.isflat(mm_flat_on_creation_in_one_step_from_some_primitives) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives isa PredictMD.SimplePipeline for x in mm_flat_on_creation_in_one_step_from_some_primitives Test.@test x isa Foo_Fittable end for i = 1:length(mm_flat_on_creation_in_one_step_from_some_primitives) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_one_step_from_some_primitives,1) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_one_step_from_some_primitives)[1] Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[i].x == i*10 end Test.@test length(mm_flat_on_creation_in_one_step_from_some_primitives) == 22 Test.@test ndims(mm_flat_on_creation_in_one_step_from_some_primitives) == 1 Test.@test length(size(mm_flat_on_creation_in_one_step_from_some_primitives)) == 1 Test.@test size(mm_flat_on_creation_in_one_step_from_some_primitives) == (22,) Test.@test size(mm_flat_on_creation_in_one_step_from_some_primitives)[1] == 22 Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[1] == Foo_Fittable(10) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[2] == Foo_Fittable(20) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[3] == Foo_Fittable(30) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[4] == Foo_Fittable(40) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[5] == Foo_Fittable(50) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[6] == Foo_Fittable(60) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[7] == Foo_Fittable(70) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[8] == Foo_Fittable(80) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[9] == Foo_Fittable(90) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[10] == Foo_Fittable(100) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[11] == Foo_Fittable(110) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[12] == Foo_Fittable(120) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[13] == Foo_Fittable(130) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[14] == Foo_Fittable(140) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[15] == Foo_Fittable(150) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[16] == Foo_Fittable(160) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[17] == Foo_Fittable(170) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[18] == Foo_Fittable(180) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[19] == Foo_Fittable(190) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[20] == Foo_Fittable(200) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[21] == Foo_Fittable(210) Test.@test mm_flat_on_creation_in_one_step_from_some_primitives[22] == Foo_Fittable(220) mm_flat_on_creation_in_one_step_from_all_primitives = Foo_Fittable(10) |> Foo_Fittable(20) |> Foo_Fittable(30) |> Foo_Fittable(40) |> Foo_Fittable(50) |> Foo_Fittable(60) |> Foo_Fittable(70) |> Foo_Fittable(80) |> Foo_Fittable(90) |> Foo_Fittable(100) |> Foo_Fittable(110) |> Foo_Fittable(120) |> Foo_Fittable(130) |> Foo_Fittable(140) |> Foo_Fittable(150) |> Foo_Fittable(160) |> Foo_Fittable(170) |> Foo_Fittable(180) |> Foo_Fittable(190) |> Foo_Fittable(200) |> Foo_Fittable(210) |> Foo_Fittable(220) Test.@test PredictMD.ispipeline(mm_flat_on_creation_in_one_step_from_all_primitives) Test.@test PredictMD.isflat(mm_flat_on_creation_in_one_step_from_all_primitives) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives isa PredictMD.SimplePipeline for x in mm_flat_on_creation_in_one_step_from_all_primitives Test.@test x isa Foo_Fittable end for i = 1:length(mm_flat_on_creation_in_one_step_from_all_primitives) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_one_step_from_all_primitives,1) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_one_step_from_all_primitives)[1] Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[i].x == i*10 end Test.@test length(mm_flat_on_creation_in_one_step_from_all_primitives) == 22 Test.@test ndims(mm_flat_on_creation_in_one_step_from_all_primitives) == 1 Test.@test length(size(mm_flat_on_creation_in_one_step_from_all_primitives)) == 1 Test.@test size(mm_flat_on_creation_in_one_step_from_all_primitives) == (22,) Test.@test size(mm_flat_on_creation_in_one_step_from_all_primitives)[1] == 22 Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[1] == Foo_Fittable(10) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[2] == Foo_Fittable(20) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[3] == Foo_Fittable(30) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[4] == Foo_Fittable(40) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[5] == Foo_Fittable(50) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[6] == Foo_Fittable(60) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[7] == Foo_Fittable(70) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[8] == Foo_Fittable(80) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[9] == Foo_Fittable(90) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[10] == Foo_Fittable(100) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[11] == Foo_Fittable(110) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[12] == Foo_Fittable(120) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[13] == Foo_Fittable(130) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[14] == Foo_Fittable(140) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[15] == Foo_Fittable(150) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[16] == Foo_Fittable(160) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[17] == Foo_Fittable(170) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[18] == Foo_Fittable(180) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[19] == Foo_Fittable(190) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[20] == Foo_Fittable(200) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[21] == Foo_Fittable(210) Test.@test mm_flat_on_creation_in_one_step_from_all_primitives[22] == Foo_Fittable(220) hh_flat = aa |> bb |> cc ii_flat = dd |> ee jj_flat = ff |> gg kk_flat = hh_flat ll_flat = ii_flat |> jj_flat |> Foo_Fittable(220) mm_flat_on_creation_in_multiple_steps_from_some_primitives = kk_flat |> ll_flat Test.@test !PredictMD.ispipeline(Foo_Fittable(220)) Test.@test PredictMD.ispipeline(aa) Test.@test PredictMD.ispipeline(bb) Test.@test PredictMD.ispipeline(cc) Test.@test PredictMD.ispipeline(dd) Test.@test PredictMD.ispipeline(ee) Test.@test PredictMD.ispipeline(ff) Test.@test PredictMD.ispipeline(gg) Test.@test PredictMD.ispipeline(hh_flat) Test.@test PredictMD.ispipeline(ii_flat) Test.@test PredictMD.ispipeline(jj_flat) Test.@test PredictMD.ispipeline(kk_flat) Test.@test PredictMD.ispipeline(ll_flat) Test.@test PredictMD.ispipeline(mm_flat_on_creation_in_multiple_steps_from_some_primitives) Test.@test PredictMD.isflat(aa) Test.@test PredictMD.isflat(bb) Test.@test PredictMD.isflat(cc) Test.@test PredictMD.isflat(dd) Test.@test PredictMD.isflat(ee) Test.@test PredictMD.isflat(ff) Test.@test PredictMD.isflat(gg) Test.@test PredictMD.isflat(hh_flat) Test.@test PredictMD.isflat(ii_flat) Test.@test PredictMD.isflat(jj_flat) Test.@test PredictMD.isflat(kk_flat) Test.@test PredictMD.isflat(ll_flat) Test.@test PredictMD.isflat(mm_flat_on_creation_in_multiple_steps_from_some_primitives) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives isa PredictMD.SimplePipeline for x in mm_flat_on_creation_in_multiple_steps_from_some_primitives Test.@test x isa Foo_Fittable end for i = 1:length(mm_flat_on_creation_in_multiple_steps_from_some_primitives) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_multiple_steps_from_some_primitives,1) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_multiple_steps_from_some_primitives)[1] Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[i].x == i*10 end Test.@test length(mm_flat_on_creation_in_multiple_steps_from_some_primitives) == 22 Test.@test ndims(mm_flat_on_creation_in_multiple_steps_from_some_primitives) == 1 Test.@test length(size(mm_flat_on_creation_in_multiple_steps_from_some_primitives)) == 1 Test.@test size(mm_flat_on_creation_in_multiple_steps_from_some_primitives) == (22,) Test.@test size(mm_flat_on_creation_in_multiple_steps_from_some_primitives)[1] == 22 Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[1] == Foo_Fittable(10) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[2] == Foo_Fittable(20) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[3] == Foo_Fittable(30) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[4] == Foo_Fittable(40) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[5] == Foo_Fittable(50) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[6] == Foo_Fittable(60) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[7] == Foo_Fittable(70) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[8] == Foo_Fittable(80) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[9] == Foo_Fittable(90) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[10] == Foo_Fittable(100) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[11] == Foo_Fittable(110) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[12] == Foo_Fittable(120) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[13] == Foo_Fittable(130) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[14] == Foo_Fittable(140) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[15] == Foo_Fittable(150) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[16] == Foo_Fittable(160) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[17] == Foo_Fittable(170) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[18] == Foo_Fittable(180) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[19] == Foo_Fittable(190) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[20] == Foo_Fittable(200) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[21] == Foo_Fittable(210) Test.@test mm_flat_on_creation_in_multiple_steps_from_some_primitives[22] == Foo_Fittable(220) aa_frombasepipe = Foo_Fittable(10) |> Foo_Fittable(20) |> Foo_Fittable(30) bb_frombasepipe = Foo_Fittable(40) |> Foo_Fittable(50) |> Foo_Fittable(60) cc_frombasepipe = Foo_Fittable(70) |> Foo_Fittable(80) |> Foo_Fittable(90) dd_frombasepipe = Foo_Fittable(100) |> Foo_Fittable(110) |> Foo_Fittable(120) ee_frombasepipe = Foo_Fittable(130) |> Foo_Fittable(140) |> Foo_Fittable(150) ff_frombasepipe = Foo_Fittable(160) |> Foo_Fittable(170) |> Foo_Fittable(180) gg_frombasepipe = Foo_Fittable(190) |> Foo_Fittable(200) |> Foo_Fittable(210) hh_flat = aa_frombasepipe |> bb_frombasepipe |> cc_frombasepipe ii_flat = dd_frombasepipe |> ee_frombasepipe jj_flat = ff_frombasepipe |> gg_frombasepipe kk_flat = hh_flat ll_flat = ii_flat |> jj_flat |> Foo_Fittable(220) mm_flat_on_creation_in_multiple_steps_from_all_primitives = kk_flat |> ll_flat Test.@test !PredictMD.ispipeline(Foo_Fittable(220)) Test.@test PredictMD.ispipeline(aa_frombasepipe) Test.@test PredictMD.ispipeline(bb_frombasepipe) Test.@test PredictMD.ispipeline(cc_frombasepipe) Test.@test PredictMD.ispipeline(dd_frombasepipe) Test.@test PredictMD.ispipeline(ee_frombasepipe) Test.@test PredictMD.ispipeline(ff_frombasepipe) Test.@test PredictMD.ispipeline(gg_frombasepipe) Test.@test PredictMD.ispipeline(hh_flat) Test.@test PredictMD.ispipeline(ii_flat) Test.@test PredictMD.ispipeline(jj_flat) Test.@test PredictMD.ispipeline(kk_flat) Test.@test PredictMD.ispipeline(ll_flat) Test.@test PredictMD.ispipeline(mm_flat_on_creation_in_multiple_steps_from_all_primitives) Test.@test PredictMD.isflat(aa_frombasepipe) Test.@test PredictMD.isflat(bb_frombasepipe) Test.@test PredictMD.isflat(cc_frombasepipe) Test.@test PredictMD.isflat(dd_frombasepipe) Test.@test PredictMD.isflat(ee_frombasepipe) Test.@test PredictMD.isflat(ff_frombasepipe) Test.@test PredictMD.isflat(gg_frombasepipe) Test.@test PredictMD.isflat(hh_flat) Test.@test PredictMD.isflat(ii_flat) Test.@test PredictMD.isflat(jj_flat) Test.@test PredictMD.isflat(kk_flat) Test.@test PredictMD.isflat(ll_flat) Test.@test PredictMD.isflat(mm_flat_on_creation_in_multiple_steps_from_all_primitives) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives isa PredictMD.SimplePipeline for x in mm_flat_on_creation_in_multiple_steps_from_all_primitives Test.@test x isa Foo_Fittable end for i = 1:length(mm_flat_on_creation_in_multiple_steps_from_all_primitives) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_multiple_steps_from_all_primitives,1) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i].x == i*10 end for i = 1:size(mm_flat_on_creation_in_multiple_steps_from_all_primitives)[1] Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i] isa Foo_Fittable Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i] == Foo_Fittable(i*10) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[i].x == i*10 end Test.@test length(mm_flat_on_creation_in_multiple_steps_from_all_primitives) == 22 Test.@test ndims(mm_flat_on_creation_in_multiple_steps_from_all_primitives) == 1 Test.@test length(size(mm_flat_on_creation_in_multiple_steps_from_all_primitives)) == 1 Test.@test size(mm_flat_on_creation_in_multiple_steps_from_all_primitives) == (22,) Test.@test size(mm_flat_on_creation_in_multiple_steps_from_all_primitives)[1] == 22 Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[1] == Foo_Fittable(10) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[2] == Foo_Fittable(20) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[3] == Foo_Fittable(30) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[4] == Foo_Fittable(40) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[5] == Foo_Fittable(50) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[6] == Foo_Fittable(60) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[7] == Foo_Fittable(70) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[8] == Foo_Fittable(80) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[9] == Foo_Fittable(90) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[10] == Foo_Fittable(100) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[11] == Foo_Fittable(110) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[12] == Foo_Fittable(120) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[13] == Foo_Fittable(130) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[14] == Foo_Fittable(140) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[15] == Foo_Fittable(150) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[16] == Foo_Fittable(160) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[17] == Foo_Fittable(170) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[18] == Foo_Fittable(180) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[19] == Foo_Fittable(190) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[20] == Foo_Fittable(200) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[21] == Foo_Fittable(210) Test.@test mm_flat_on_creation_in_multiple_steps_from_all_primitives[22] == Foo_Fittable(220)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
126
import PredictMD PredictMD.probability_calibration_scores_and_fractions( [0, 0, 0], [0., 0., 0.]; window = -1, )
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
718
import DataFrames import PredictMD import Test a = DataFrames.DataFrame() a[:x] = ["foo", "foo", "foo", "bar", "bar", "bar"] contrasts = PredictMD.DataFrameFeatureContrasts(a, [:x]) transformer = PredictMD.MutableDataFrame2DecisionTreeTransformer([:x], :y) PredictMD.set_feature_contrasts!(transformer, contrasts) Test.@test length(PredictMD.transform(transformer, a)) == 6 b = DataFrames.DataFrame() b[:x] = ["bar", "foo"] Test.@test length(PredictMD.transform(transformer, b)) == 2 c = DataFrames.DataFrame() c[:x] = ["foo", "bar", "baz"] Test.@test_throws KeyError PredictMD.transform(transformer, c) d = DataFrames.DataFrame() Test.@test_throws ErrorException PredictMD.DataFrameFeatureContrasts(d, [:x, :x])
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
1055
import DataFrames import PredictMD import Test x = Union{Missing, String}["foo", "bar", "foo", missing, "bar"] Test.@test( length(PredictMD.get_unique_values(x; skip_missings = true)) == 2 ) Test.@test( length(PredictMD.get_unique_values(x; skip_missings = false)) == 3 ) Test.@test( length(PredictMD.get_unique_values_skip_missings(x)) == 2 ) Test.@test( length(PredictMD.get_unique_values_include_missings(x)) == 3 ) Test.@test( PredictMD.get_number_of_unique_values(x; skip_missings = true) == 2 ) Test.@test( PredictMD.get_number_of_unique_values(x; skip_missings = false) == 3 ) Test.@test( PredictMD.get_number_of_unique_values_skip_missings(x) == 2 ) Test.@test( PredictMD.get_number_of_unique_values_include_missings(x) == 3 ) df = DataFrames.DataFrame() df[:a] = [1,2,3,4,5,6,7] df[:b] = [1,1,1,1,1,1,1] df_constant_cols = PredictMD.find_constant_columns(df) Test.@test length(df_constant_cols) == 1 Test.@test df_constant_cols == [:b] Test.@test all(df_constant_cols .== [:b])
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
298
import PredictMD import Test a = Union{String, Missing}["foo", "bar", "foo"] b = PredictMD.disallowmissing(a) Test.@test isa(b, Vector{String}) Test.@test b == String["foo", "bar", "foo"] c = Union{String, Missing}["foo", "bar", missing] Test.@test_throws MethodError PredictMD.disallowmissing(c)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
168
import PredictMD import Test a = PredictMD.predictionsassoctodataframe(Dict(:x => [0.3], :y => [0.7]), Symbol[]) Test.@test a[1, :x] == 0.3 Test.@test a[1, :y] == 0.7
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
312
import PredictMD import Test Test.@test PredictMD.is_make_examples() isa Bool Test.@test PredictMD.is_make_docs() isa Bool Test.@test PredictMD.is_deploy_docs() isa Bool Test.@test PredictMD.is_docs_or_examples() == PredictMD.is_make_examples() || PredictMD.is_make_docs() || PredictMD.is_deploy_docs()
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
103
import PredictMD import Test Test.@test_throws ErrorException PredictMD.simple_moving_average([], -1)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
575
import Test import PredictMD dict_1 = Dict() Test.@test( PredictMD.is_one_to_one(dict_1) ) dict_1_inverted = PredictMD.inverse(dict_1) dict_2 = Dict() dict_2["hello"] = :hola dict_2["goodbye"] = :adios Test.@test( PredictMD.is_one_to_one(dict_2) ) dict_2_inverted = PredictMD.inverse(dict_2) Test.@test( dict_2_inverted[:hola] == "hello" ) Test.@test( dict_2_inverted[:adios] == "goodbye") dict_3 = Dict() dict_3[1] = "odd" dict_3[2] = "even" dict_3[3] = "odd" Test.@test( !PredictMD.is_one_to_one(dict_3) ) Test.@test_throws(ErrorException, PredictMD.inverse(dict_3))
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
30
import Test import PredictMD
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
6248
import Test import DataFrames import PredictMD my_vector = Vector{Any}(undef, 5) my_vector[1] = Float64(1.1) my_vector[2] = Float64(2.2) my_vector[3] = DataFrames.missing my_vector[4] = Float64(4.4) my_vector[5] = DataFrames.missing Test.@test(eltype(my_vector) == Any) my_vector_fixed = PredictMD.fix_type(my_vector) Test.@test(eltype(my_vector_fixed) == Union{Float64, DataFrames.Missing}) Test.@test( PredictMD.fix_type(nothing) == nothing ) Test.@test( PredictMD.fix_type(3.14) == 3.14 ) dict_1 = Dict() dict_1[Symbol(:x)] = Float64(1.1) dict_1[Symbol(:y)] = Float64(2.2) dict_1[Symbol(:z)] = Float64(3.3) Test.@test(typeof(dict_1) <: Dict{Any, Any}) Test.@test(length(dict_1) == 3) dict_2 = PredictMD.fix_type(dict_1) Test.@test(typeof(dict_2) <: Dict{Symbol, Float64}) Test.@test(length(dict_2) == 3) Test.@test(dict_1[:x] == 1.1) Test.@test(dict_1[:y] == 2.2) Test.@test(dict_1[:z] == 3.3) dict_3 = PredictMD.fix_type(dict_2) Test.@test(typeof(dict_3) <: Dict{Symbol, Float64}) Test.@test(length(dict_3) == 3) Test.@test(dict_1[:x] == 1.1) Test.@test(dict_1[:y] == 2.2) Test.@test(dict_1[:z] == 3.3) dict_4 = PredictMD.fix_type(dict_3) Test.@test(typeof(dict_4) <: Dict{Symbol, Float64}) Test.@test(length(dict_4) == 3) Test.@test(dict_1[:x] == 1.1) Test.@test(dict_1[:y] == 2.2) Test.@test(dict_1[:z] == 3.3) Test.@test( PredictMD.fix_type(nothing) == nothing ) Test.@test( PredictMD.fix_type(nothing) == nothing ) vector_1 = [] push!(vector_1, Float64(1.0)) push!(vector_1, Float64(2.0)) push!(vector_1, Float64(3.0)) Test.@test(typeof(vector_1) <: Vector{Any}) Test.@test(length(vector_1) == 3) Test.@test(size(vector_1) == (3,)) vector_2 = PredictMD.fix_type(vector_1) Test.@test(typeof(vector_2) <: Vector{Float64}) Test.@test(length(vector_2) == 3) Test.@test(size(vector_2) == (3,)) Test.@test(vector_1[1] == 1.0) Test.@test(vector_1[2] == 2.0) Test.@test(vector_1[3] == 3.0) vector_3 = PredictMD.fix_type(vector_2) Test.@test(typeof(vector_3) <: Vector{Float64}) Test.@test(length(vector_3) == 3) Test.@test(size(vector_3) == (3,)) Test.@test(vector_1[1] == 1.0) Test.@test(vector_1[2] == 2.0) Test.@test(vector_1[3] == 3.0) vector_4 = PredictMD.fix_type(vector_3) Test.@test(length(vector_4) == 3) Test.@test(size(vector_4) == (3,)) Test.@test(typeof(vector_4) <: Vector{Float64}) Test.@test(vector_1[1] == 1.0) Test.@test(vector_1[2] == 2.0) Test.@test(vector_1[3] == 3.0) ############################################################################## array_1 = Array{Any}(undef, 2,3,4) array_1[1,1,1] = Float64(10) array_1[1,1,2] = Float64(20) array_1[1,1,3] = Float64(30) array_1[1,1,4] = Float64(40) array_1[1,2,1] = Float64(50) array_1[1,2,2] = Float64(60) array_1[1,2,3] = Float64(70) array_1[1,2,4] = Float64(80) array_1[1,3,1] = Float64(90) array_1[1,3,2] = Float64(100) array_1[1,3,3] = Float64(110) array_1[1,3,4] = Float64(120) array_1[2,1,1] = Float64(130) array_1[2,1,2] = Float64(140) array_1[2,1,3] = Float64(150) array_1[2,1,4] = Float64(160) array_1[2,2,1] = Float64(170) array_1[2,2,2] = Float64(180) array_1[2,2,3] = Float64(190) array_1[2,2,4] = Float64(200) array_1[2,3,1] = Float64(210) array_1[2,3,2] = Float64(220) array_1[2,3,3] = Float64(230) array_1[2,3,4] = Float64(240) Test.@test(typeof(array_1) <: Array{Any, 3}) Test.@test(length(array_1) == 24) Test.@test(size(array_1) == (2,3,4,)) array_2 = PredictMD.fix_type(array_1) Test.@test(typeof(array_2) <: Array{Float64, 3}) Test.@test(length(array_2) == 24) Test.@test(size(array_2) == (2,3,4,)) Test.@test(array_2[1,1,1] == 10) Test.@test(array_2[1,1,2] == 20) Test.@test(array_2[1,1,3] == 30) Test.@test(array_2[1,1,4] == 40) Test.@test(array_2[1,2,1] == 50) Test.@test(array_2[1,2,2] == 60) Test.@test(array_2[1,2,3] == 70) Test.@test(array_2[1,2,4] == 80) Test.@test(array_2[1,3,1] == 90) Test.@test(array_2[1,3,2] == 100) Test.@test(array_2[1,3,3] == 110) Test.@test(array_2[1,3,4] == 120) Test.@test(array_2[2,1,1] == 130) Test.@test(array_2[2,1,2] == 140) Test.@test(array_2[2,1,3] == 150) Test.@test(array_2[2,1,4] == 160) Test.@test(array_2[2,2,1] == 170) Test.@test(array_2[2,2,2] == 180) Test.@test(array_2[2,2,3] == 190) Test.@test(array_2[2,2,4] == 200) Test.@test(array_2[2,3,1] == 210) Test.@test(array_2[2,3,2] == 220) Test.@test(array_2[2,3,3] == 230) Test.@test(array_2[2,3,4] == 240) array_3 = PredictMD.fix_type(array_2) Test.@test(typeof(array_3) <: Array{Float64, 3}) Test.@test(length(array_3) == 24) Test.@test(size(array_3) == (2,3,4,)) Test.@test(array_3[1,1,1] == 10) Test.@test(array_3[1,1,2] == 20) Test.@test(array_3[1,1,3] == 30) Test.@test(array_3[1,1,4] == 40) Test.@test(array_3[1,2,1] == 50) Test.@test(array_3[1,2,2] == 60) Test.@test(array_3[1,2,3] == 70) Test.@test(array_3[1,2,4] == 80) Test.@test(array_3[1,3,1] == 90) Test.@test(array_3[1,3,2] == 100) Test.@test(array_3[1,3,3] == 110) Test.@test(array_3[1,3,4] == 120) Test.@test(array_3[2,1,1] == 130) Test.@test(array_3[2,1,2] == 140) Test.@test(array_3[2,1,3] == 150) Test.@test(array_3[2,1,4] == 160) Test.@test(array_3[2,2,1] == 170) Test.@test(array_3[2,2,2] == 180) Test.@test(array_3[2,2,3] == 190) Test.@test(array_3[2,2,4] == 200) Test.@test(array_3[2,3,1] == 210) Test.@test(array_3[2,3,2] == 220) Test.@test(array_3[2,3,3] == 230) Test.@test(array_3[2,3,4] == 240) array_4 = PredictMD.fix_type(array_3) Test.@test(typeof(array_4) <: Array{Float64, 3}) Test.@test(length(array_4) == 24) Test.@test(size(array_4) == (2,3,4,)) Test.@test(array_4[1,1,1] == 10) Test.@test(array_4[1,1,2] == 20) Test.@test(array_4[1,1,3] == 30) Test.@test(array_4[1,1,4] == 40) Test.@test(array_4[1,2,1] == 50) Test.@test(array_4[1,2,2] == 60) Test.@test(array_4[1,2,3] == 70) Test.@test(array_4[1,2,4] == 80) Test.@test(array_4[1,3,1] == 90) Test.@test(array_4[1,3,2] == 100) Test.@test(array_4[1,3,3] == 110) Test.@test(array_4[1,3,4] == 120) Test.@test(array_4[2,1,1] == 130) Test.@test(array_4[2,1,2] == 140) Test.@test(array_4[2,1,3] == 150) Test.@test(array_4[2,1,4] == 160) Test.@test(array_4[2,2,1] == 170) Test.@test(array_4[2,2,2] == 180) Test.@test(array_4[2,2,3] == 190) Test.@test(array_4[2,2,4] == 200) Test.@test(array_4[2,3,1] == 210) Test.@test(array_4[2,3,2] == 220) Test.@test(array_4[2,3,3] == 230) Test.@test(array_4[2,3,4] == 240)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
3486
import DataFrames import PredictMD import Random import Test Test.@testset "linearly independent" begin num_rows = 1_000 x = randn(Random.MersenneTwister(1), num_rows) x1 = randn(Random.MersenneTwister(2), num_rows) x11 = randn(Random.MersenneTwister(3), num_rows) y = randn(Random.MersenneTwister(4), num_rows) y1 = randn(Random.MersenneTwister(5), num_rows) y11 = randn(Random.MersenneTwister(6), num_rows) z = randn(Random.MersenneTwister(7), num_rows) z1 = randn(Random.MersenneTwister(8), num_rows) z11 = randn(Random.MersenneTwister(9), num_rows) df = DataFrames.DataFrame( :x => x, :x1 => x1, :x11 => x11, :y => y, :y1 => y1, :y11 => y11, :z => z, :z1 => z1, :z11 => z11, ) Test.@test(PredictMD.columns_are_linearly_independent(df)) Test.@test( PredictMD.columns_are_linearly_independent( df, [:x, :x1, :x11, :y, :y1, :y11, :z, :z1, :z11], ) ) Test.@test(length(PredictMD.linearly_dependent_columns(df)) == 0) Test.@test( length( PredictMD.linearly_dependent_columns( df, [:x, :x1, :x11, :y, :y1, :y11, :z, :z1, :z11], ), ) == 0 ) end Test.@testset "linearly dependent" begin num_rows = 1_000 x = randn(Random.MersenneTwister(10), num_rows) x1 = randn(Random.MersenneTwister(11), num_rows) x11 = randn(Random.MersenneTwister(12), num_rows) y = randn(Random.MersenneTwister(13), num_rows) y1 = randn(Random.MersenneTwister(14), num_rows) y11 = randn(Random.MersenneTwister(15), num_rows) z = 2*x .+ 3*y z1 = randn(Random.MersenneTwister(17), num_rows) z11 = randn(Random.MersenneTwister(18), num_rows) df = DataFrames.DataFrame( :x => x, :x1 => x1, :x11 => x11, :y => y, :y1 => y1, :y11 => y11, :z => z, :z1 => z1, :z11 => z11, ) Test.@test(!PredictMD.columns_are_linearly_independent(df)) Test.@test( !PredictMD.columns_are_linearly_independent( df, [:x, :x1, :x11, :y, :y1, :y11, :z, :z1, :z11], ) ) Test.@test(length(PredictMD.linearly_dependent_columns(df)) == 1) Test.@test( length( PredictMD.linearly_dependent_columns( df, [:x, :x1, :x11, :y, :y1, :y11, :z, :z1, :z11], ) ) == 1 ) result1 = PredictMD.linearly_dependent_columns(df) result2 = PredictMD.linearly_dependent_columns( df, [:x, :x1, :x11, :y, :y1, :y11, :z, :z1, :z11], ) Test.@test( all(result1.==[:x]) || all(result1.==[:y]) || all(result1.==[:z]) ) Test.@test( all(result2.==[:x]) || all(result2.==[:y]) || all(result2.==[:z]) ) DataFrames.deletecols!(df, [:z]) Test.@test(PredictMD.columns_are_linearly_independent(df)) Test.@test( PredictMD.columns_are_linearly_independent( df, [:x, :x1, :x11, :y, :y1, :y11, :z1, :z11], ) ) Test.@test(length(PredictMD.linearly_dependent_columns(df)) == 0) Test.@test( length( PredictMD.linearly_dependent_columns( df, [:x, :x1, :x11, :y, :y1, :y11, :z1, :z11], ) ) == 0 ) end
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
code
525
import PredictMD import Test Test.@test_throws ErrorException PredictMD.trapz([1, 2, 3], []) Test.@test_throws ErrorException PredictMD.trapz([], []) Test.@test_throws ErrorException PredictMD.trapz([1, 2, 1], [4, 5, 4]) x_1 = collect(0:0.00001:1) f_1(t) = t^2 y_1 = f_1.(x_1) I_1 = PredictMD.trapz(x_1, y_1) Test.@test isapprox(I_1, 1/3; atol=0.00000001) x_2 = collect(0:0.00001:1) f_2(t) = (t^2) * (tanh(t)) y_2 = f_2.(x_2) I_2 = PredictMD.trapz(x_2, y_2) Test.@test isapprox(I_2, 0.207068855098706896; atol=0.00000001)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
3346
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
5947
# PredictMD - Uniform interface for machine learning in Julia [![Zenodo][zenodo-img]][zenodo-url] [![Documentation (stable)][docs-stable-img]][docs-stable-url] [![Documentation (development)][docs-development-img]][docs-development-url] [![PkgEval][pkgeval-img]][pkgeval-url] [![Continuous integration (CI)][ghactions-ci-img]][ghactions-ci-url] [![Code coverage][codecov-img]][codecov-url] [zenodo-img]: https://zenodo.org/badge/109460252.svg [zenodo-url]: https://doi.org/10.5281/zenodo.1291209 [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://predictmd.net/stable [docs-development-img]: https://img.shields.io/badge/docs-development-blue.svg [docs-development-url]: https://predictmd.net/development [pkgeval-img]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/P/PredictMD.named.svg [pkgeval-url]: https://juliaci.github.io/NanosoldierReports/pkgeval_badges/P/PredictMD.html [ghactions-ci-img]: https://github.com/bcbi/PredictMD.jl/workflows/CI/badge.svg?branch=master [ghactions-ci-url]: https://github.com/bcbi/PredictMD.jl/actions?query=workflow%3ACI+branch%3Amaster [codecov-img]: https://codecov.io/gh/bcbi/PredictMD.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/bcbi/PredictMD.jl/branch/master [PredictMD](https://predictmd.net) is a free and open-source Julia package that provides a uniform interface for machine learning. PredictMD makes it easy to automate machine learning workflows and create reproducible machine learning pipelines. It is the official machine learning framework of the [Brown Center for Biomedical Informatics](https://github.com/bcbi). | Table of Contents | | ----------------- | | [1. Installation](#installation) | | [2. Run the test suite after installing](#run-the-test-suite-after-installing) | | [3. Citing](#citing) | | [4. Docker image](#docker-image) | | [5. Documentation](#documentation) | | [6. Related Repositories](#related-repositories) | | [7. Contributing](#contributing) | ## Installation PredictMD is registered in the Julia General registry. Therefore, to install PredictMD, simply open Julia and run the following four lines: ```julia import Pkg Pkg.activate("PredictMDEnvironment"; shared = true) Pkg.add("PredictMDFull") import PredictMDFull ``` ## Run the test suite after installing After you install PredictMD, you should run the test suite to make sure that everything is working. You can run the test suite by running the following five lines in Julia: ```julia import Pkg Pkg.activate("PredictMDEnvironment"; shared = true) Pkg.test("PredictMDExtra") Pkg.test("PredictMDFull") Pkg.test("PredictMD") ``` ## Citing If you use PredictMD in research, please cite the software using the following DOI: <a href="https://doi.org/10.5281/zenodo.1291209"> <img src="https://zenodo.org/badge/109460252.svg"/> </a> ## Docker image Alternatively, you can use the PredictMD Docker image for easy installation. Download and start the container by running the following line: ```bash docker run --name predictmd -it dilumaluthge/predictmd /bin/bash ``` Once you are inside the container, you can start Julia by running the following line: ```bash julia ``` In Julia, run the following line to load PredictMD: ```julia import PredictMDFull ``` You can run the test suite by running the following four lines in Julia: ```julia import Pkg Pkg.test("PredictMDExtra") Pkg.test("PredictMDFull") Pkg.test("PredictMD") ``` After you have exited the container, you can return to it by running the following line: ```bash docker start -ai predictmd ``` To delete your container, run the following line: ```bash docker container rm -f predictmd ``` To also delete the downloaded image, run the following line: ```bash docker image rm -f dilumaluthge/predictmd ``` ## Documentation The [PredictMD documentation](https://predictmd.net/stable) contains useful information, including instructions for use, example code, and a description of PredictMD's internals. ## Related Repositories - [BCBIRegistry](https://github.com/bcbi/BCBIRegistry) - Julia package registry for the Brown Center for Biomedical Informatics (BCBI) - [ClassImbalance.jl](https://github.com/bcbi/ClassImbalance.jl) - Sampling-based methods for correcting for class imbalance in two-category classification problems - [OfflineRegistry](https://github.com/DilumAluthge/OfflineRegistry) - Generate a custom Julia package registry, mirror, and depot for use on workstations without internet access - [PredictMD-docker](https://github.com/DilumAluthge/PredictMD-docker) - Docker and Singularity images for PredictMD - [PredictMD-roadmap](https://github.com/bcbi/PredictMD-roadmap) - Roadmap for the PredictMD machine learning pipeline - [PredictMD.jl](https://github.com/bcbi/PredictMD.jl) - Uniform interface for machine learning in Julia - [PredictMDAPI.jl](https://github.com/bcbi/PredictMDAPI.jl) - Provides the abstract types and generic functions that define the PredictMD application programming interface (API) - [PredictMDExtra.jl](https://github.com/bcbi/PredictMDExtra.jl) - Install all of the dependencies of PredictMD (but not PredictMD itself) - [PredictMDFull.jl](https://github.com/bcbi/PredictMDFull.jl) - Install PredictMD and all of its dependencies - [PredictMDSanitizer.jl](https://github.com/bcbi/PredictMDSanitizer.jl) - Remove potentially sensitive data from trained machine learning models ## Contributing If you would like to contribute to the PredictMD source code, please read the instructions in [CONTRIBUTING.md](CONTRIBUTING.md). ## Acknowledgements - This work was supported in part by National Institutes of Health grants U54GM115677, R01LM011963, and R25MH116440. The content is solely the responsibility of the authors and does not necessarily represent the official views of the National Institutes of Health. - PredictMD was created by [Dilum P. Aluthge](https://aluthge.com) and Ishan Sinha.
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
3745
## Instructions Select the test group to run by setting the `PREDICTMD_TEST_GROUP` environment variable before running the test suite. For example, to run the `all` test group, you would run the following lines in Julia: ```julia ENV["PREDICTMD_TEST_GROUP"] = "all" import Pkg Pkg.test("PredictMD") Pkg.test("PredictMDExtra") Pkg.test("PredictMDFull") ``` ## Available test groups | group | `default` | `all` | `test-plots` | `import-only` | `travis-1` | `travis-2` | `travis-3` | `travis-4` | `travis-5` | `travis-6` | `travis-7` | `docker-1` | `docker-2` | `docker-3` | `docker-4` | | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | | Import package | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | | Unit tests | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | | Integration tests 1/7 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | | Integration tests 2/7 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | | Integration tests 3/7 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | | Integration tests 4/7 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | | Integration tests 5/7 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | | Integration tests 6/7 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :white_check_mark: | :x: | | Integration tests 7/7 | :white_check_mark: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :white_check_mark: | :x: | | Plot tests 1/7 | :x: | :white_check_mark: | :white_check_mark: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | | Plot tests 2/7 | :x: | :white_check_mark: | :white_check_mark: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | | Plot tests 3/7 | :x: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | | Plot tests 4/7 | :x: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | | Plot tests 5/7 | :x: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | | Plot tests 6/7 | :x: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :x: | :white_check_mark: | :x: | | Plot tests 7/7 | :x: | :white_check_mark: | :white_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :x: | :white_check_mark: | :x: | :x: | :white_check_mark: | :x: |
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
2695
# Zenodo entry for PredictMD This document contains instructions for updating the Zenodo entry for PredictMD. First go to [https://doi.org/10.5281/zenodo.1291209](https://doi.org/10.5281/zenodo.1291209), and then click on the yellow "Edit" button to edit the most recent release. Then, fill out the following fields with the specified values: ## Upload type: Software ## Basic information ### Title: PredictMD - Uniform interface for machine learning in Julia ### Authors: | Name | Affiliation | ORCID | | --- | -------- | ---- | | Aluthge DP | Brown Center for Biomedical Informatics, Brown University | 0000-0002-9247-0530 | | Sinha I | Brown Center for Biomedical Informatics, Brown University | 0000-0001-7796-819X | | Stey P | Brown Center for Biomedical Informatics, Brown University | 0000-0003-2112-6756 | | Restrepo MI | Brown Center for Biomedical Informatics, Brown University | 0000-0002-2708-8984 | | Chen ES | Brown Center for Biomedical Informatics, Brown University | 0000-0002-6181-3369 | | Sarkar IN | Brown Center for Biomedical Informatics, Brown University | 0000-0003-2054-7356 | ### Description: PredictMD is a free and open-source Julia package that provides a uniform interface for machine learning. ### Language: English ### Keywords: * biomedical informatics * Julia * machine learning * statistics ### Additional notes: Development of PredictMD was supported in part by National Institutes of Health grants U54GM115677, R01LM011963, and R25MH116440. The content is solely the responsibility of the authors and does not necessarily represent the official views of the National Institutes of Health. ## License MIT License ## Related/alternate identifiers ### Related identifiers: (Replace `vMAJOR.MINOR.PATCH` with the appropriate version number. In our example, you would replace `vMAJOR.MINOR.PATCH` with `v3.6.0`.) | Identifier | Relationship | Optional. Resource type of the related identifier. | | ---- | ---- | ---- | | `https://github.com/bcbi/PredictMD.jl/tree/vMAJOR.MINOR.PATCH` | is supplemented by this upload | Software | | `https://github.com/bcbi/PredictMD.jl/tree/vMAJOR.MINOR.PATCH` | is an alternate identifier of this upload | Software | | `https://github.com/bcbi/PredictMD.jl/releases/tag/vMAJOR.MINOR.PATCH` | is an alternate identifier of this upload | Software | | `https://predictmd.net/vMAJOR.MINOR.PATCH` | documents this upload | Software documentation | | `https://predictmd.net` | compiled/created this upload | Software documentation | After you have entered the correct information in all of the above fields, click the white "Save" button, and then click the blue "Publish" button. Congratulations, you are finished!
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
834
--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. iOS] - Browser [e.g. chrome, safari] - Version [e.g. 22] **Smartphone (please complete the following information):** - Device: [e.g. iPhone6] - OS: [e.g. iOS8.1] - Browser [e.g. stock browser, safari] - Version [e.g. 22] **Additional context** Add any other context about the problem here.
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
595
--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here.
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
1022
# [Docker image](@id docker_image) You can use the PredictMD Docker image for easy installation of PredictMD and all of its dependencies. Download and start the container by running the following line: ```bash docker run --name predictmd -it dilumaluthge/predictmd /bin/bash ``` Once you are inside the container, you can start Julia by running the following line: ```bash julia ``` In Julia, run the following line to load PredictMD: ```julia import PredictMDFull ``` You can run the test suite by running the following four lines in Julia: ```julia import Pkg ENV["PREDICTMD_TEST_GROUP"] = "all" Pkg.test("PredictMDExtra") Pkg.test("PredictMDFull") Pkg.test("PredictMD") ``` After you have exited the container, you can return to it by running the following line: ```bash docker start -ai predictmd ``` To delete your container, run the following line: ```bash docker container rm -f predictmd ``` To also delete the downloaded image, run the following line: ```bash docker image rm -f dilumaluthge/predictmd ```
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
1119
# PredictMD [PredictMD](https://predictmd.net) is a free and open-source Julia package that provides a uniform interface for machine learning. PredictMD makes it easy to automate machine learning workflows and create reproducible machine learning pipelines. ## Installation PredictMD is registered in the Julia General registry. Therefore, to install PredictMD, simply open Julia and run the following four lines: ```julia import Pkg Pkg.activate("PredictMDEnvironment"; shared = true) Pkg.add("PredictMDFull") import PredictMDFull ``` ## Running the package tests You can run the default PredictMD test suite by running the following five lines in Julia: ```julia import Pkg Pkg.activate("PredictMDEnvironment"; shared = true) Pkg.test("PredictMDExtra") Pkg.test("PredictMDFull") Pkg.test("PredictMD") ``` To run the full test suite, which includes tests of the plotting functionality, run the following six lines in Julia: ```julia import Pkg Pkg.activate("PredictMDEnvironment"; shared = true) ENV["PREDICTMD_TEST_GROUP"] = "all" Pkg.test("PredictMDExtra") Pkg.test("PredictMDFull") Pkg.test("PredictMD") ```
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
1745
# Requirements for plotting There are no requirements in order to run PredictMD--you can train, run, and evaluate models without installing any additional software. However, in order to generate plots (e.g. ROC curves), you need to install LaTeX on your system. See below for instructions on installing LaTeX. Once you have installed LaTeX, you can test PredictMD's plotting functionality by running two lines in Julia: ```julia import Pkg Pkg.activate("PredictMDEnvironment"; shared = true) ENV["PREDICTMD_TEST_GROUP"] = "test-plots" Pkg.test("PredictMD") ``` If you do not want to install LaTeX on your computer, you can use the [Docker image](@ref docker_image). ## Installing LaTeX To confirm that LaTeX is installed on your system, open a terminal window and run the following command: ```bash latex -v ``` You should see an output message that looks something like this: ``` pdfTeX 3.14159265-2.6-1.40.18 (TeX Live 2017) kpathsea version 6.2.3 Copyright 2017 Han The Thanh (pdfTeX) et al. There is NO warranty. Redistribution of this software is covered by the terms of both the pdfTeX copyright and the Lesser GNU General Public License. For more information about these matters, see the file named COPYING and the pdfTeX source. Primary author of pdfTeX: Han The Thanh (pdfTeX) et al. Compiled with libpng 1.6.29; using libpng 1.6.29 Compiled with zlib 1.2.11; using zlib 1.2.11 Compiled with xpdf version 3.04 ``` If you receive an error (e.g. "command not found"), download and install a TeX distribution from the appropriate link below: * Windows: [https://tug.org/protext/](https://tug.org/protext/) * macOS: [https://tug.org/mactex/](https://tug.org/mactex/) * GNU/Linux: [https://tug.org/texlive/](https://tug.org/texlive/)
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
1130
# Generating example files locally You can generate the example files using the `generate_examples` function. Instructions for using the `generate_examples` are given below. In the following code snippets, `output_directory` is the directory where you want to save the generated example files. `output_directory` should NOT be an existing directory. If `output_directory` already exists, you should delete it before running the `generate_examples` function. ## Generating scripts (.jl files) To generate the examples as Julia scripts (.jl files), use the following code. ```julia PredictMD.generate_examples(output_directory; scripts = true) ``` ## Generating IJulia/Jupyter notebooks (.ipynb files) To generate the examples as IJulia/Jupyter notebooks (.ipynb files), use the following code. `output_directory` is the directory where you want to save the generated example files. `output_directory` should NOT be an existing directory. If `output_directory` already exists, you should delete it before running the `generate_examples` function. ```julia PredictMD.generate_examples(output_directory; notebooks = true) ```
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
965
# Documentation of internals ```@contents Pages = ["internals.md"] ``` ## Modules ```@autodocs Modules = [ PredictMD, PredictMD.Cleaning, PredictMD.Compilation, PredictMD.GPU, PredictMD.Server, ] Order = [:module] ``` ## Constants ```@autodocs Modules = [ PredictMD, PredictMD.Cleaning, PredictMD.Compilation, PredictMD.GPU, PredictMD.Server, ] Order = [:constant] ``` ## Types ```@autodocs Modules = [ PredictMD, PredictMD.Cleaning, PredictMD.Compilation, PredictMD.GPU, PredictMD.Server, ] Order = [:type] ``` ## Functions ```@autodocs Modules = [ PredictMD, PredictMD.Cleaning, PredictMD.Compilation, PredictMD.GPU, PredictMD.Server, ] Order = [:function] ``` ## Macros ```@autodocs Modules = [ PredictMD, PredictMD.Cleaning, PredictMD.Compilation, PredictMD.GPU, PredictMD.Server, ] Order = [:macro] ``` ## Index ```@index ```
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
28
# Boston housing regression
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.34.21
6af1dc255a34ea50e2ea16f11dfe941a2c3965ad
docs
38
# Breast cancer biopsy classification
PredictMD
https://github.com/bcbi/PredictMD.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
553
using BubbleBath using Distributions: Uniform using Plots function circle(x,y,r,n=500) θ = LinRange(0, 2π, n) x .+ r.*sin.(θ), y .+ r.*cos.(θ) end # function radius_pdf = Uniform(1,5) extent = (100, 50) ϕ_max = 0.4 spheres = bubblebath(radius_pdf, ϕ_max, extent) ϕ = round(packing_fraction(spheres, extent), digits=3) plot( xlims=(0,extent[1]), ylims=(0,extent[2]), ratio=1, legend=false, grid=false, title="target ϕ=$(ϕ_max); actual ϕ=$(ϕ)" ) for s in spheres plot!(circle(s.pos..., s.radius), seriestype=:shape) end plot!()
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
858
using BubbleBath using Distributions: Exponential using Plots function circle(x,y,r,n=100) θ = LinRange(0, 2π, n) x .+ r.*sin.(θ), y .+ r.*cos.(θ) end # function Lx = 400 Ly = 400 extent = (Lx,Ly) R = 50 D = 60 spheres = [ Sphere((Lx/2-D,Ly/2-D), R), Sphere((Lx/2+D,Ly/2-D), R), Sphere((Lx/2,Ly/2+3D/4), R) ] radius_pdf = Exponential(2.0) ϕ_max = 0.25 - packing_fraction(spheres, extent) min_distance = 2.0 bubblebath!(spheres, radius_pdf, ϕ_max, extent; min_distance) plot( xlims=(0,extent[1]), ylims=(0,extent[2]), ratio=1, legend=false, grid=false, axis=false, bgcolor=:transparent, size=(Lx,Ly) ) for i in eachindex(spheres) s = spheres[i] plot!(circle(s.pos..., s.radius), seriestype = :shape, lw = 0, fillcolor = i ≤ 3 ? i : :gray, alpha = i ≤ 3 ? 1.0 : 0.7, ) end plot!()
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
586
using BubbleBath using Distributions: Uniform using Plots function circle(x,y,r,n=500) θ = LinRange(0, 2π, n) x .+ r.*sin.(θ), y .+ r.*cos.(θ) end # function radius_pdf = Uniform(1,5) extent = (100, 50) ϕ_max = 0.4 min_distance = 2.0 spheres = bubblebath(radius_pdf, ϕ_max, extent; min_distance) ϕ = round(packing_fraction(spheres, extent), digits=3) plot( xlims=(0,extent[1]), ylims=(0,extent[2]), ratio=1, legend=false, grid=false, title="target ϕ=$(ϕ_max); actual ϕ=$(ϕ)" ) for s in spheres plot!(circle(s.pos..., s.radius), seriestype=:shape) end plot!()
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
759
using BubbleBath using Distributions: Uniform using Plots function circle(x₀,y₀,z₀,r,n=20) θ = LinRange(-π, π, n) φ = LinRange(0, π, n) x = x₀ .+ r.*cos.(θ).*sin.(φ)' y = y₀ .+ r.*sin.(θ).*sin.(φ)' z = z₀ .+ r.*ones(n).*cos.(φ)' return x, y, z end # function radius_pdf = Uniform(10, 25) extent = (100, 100, 100) ϕ_max = 0.3 min_distance = 10.0 spheres = bubblebath(radius_pdf, ϕ_max, extent; min_distance) ϕ = round(packing_fraction(spheres, extent), digits=3) plot( xlims=(0,extent[1]), ylims=(0,extent[2]), zlims=(0,extent[3]), size=(400,400), aspect_ratio=:equal, legend=false, colorbar=false, ticks=0:50:100, camera=(20,20) ) for s in spheres surface!(circle(s.pos..., s.radius), alpha=0.7) end plot!()
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
710
module BubbleBath using LinearAlgebra: norm using Random: AbstractRNG, default_rng export Sphere """ Sphere(pos::NTuple{D,Real}, radius::Real) where D Create a `Sphere{D}` object centered at `pos` with radius `radius`. """ struct Sphere{D} pos::NTuple{D,Float64} radius::Float64 function Sphere(pos::NTuple{D,Real}, radius::Real) where D if radius ≤ 0 throw(ArgumentError("Sphere radius must be a non-negative real number.")) end new{D}(Float64.(pos), Float64(radius)) end end Sphere(pos::AbstractVector{<:Real}, radius::Real) = Sphere(Tuple(pos), radius) include("bubblebath_algorithm.jl") include("walkmaps.jl") include("packing_fraction.jl") end
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
8471
export bubblebath, bubblebath! """ bubblebath( radius_pdf, ϕ_max::Real, extent::NTuple{D,Real}; through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true ) where D Generate a bath of spheres in the domain `extent`, extracting radii from `radius_pdf` trying to reach a target packing fraction `ϕ_max`. The domain is filled with spheres in order of decreasing radius. ## Keywords * `min_distance = 0.0`: Minimum allowed distance between spheres. Negative values can be used to allow overlaps. * `through_boundaries = false`: Whether spheres can cross through the domain boundaries. * `max_tries = 10000`: Maximum number of insertion tries for each sphere. When `max_tries` is reached, the sphere is discarded and the algorithm moves on to the next one. * `max_fails = 100`: Maximum number of failures (i.e. discarded spheres) allowed. Once `max_fails` is reached, the program halts. * `verbose = true`: Whether info logs should be printed. * `rng = Random.default_rng()`: Random number generator. If a negative `min_distance` is used or `through_boundaries` is set to true, the packing fraction estimated during the generation will not correspond to the real packing fraction of the system. In these cases, `ϕ_max` has only a *semi*-quantitative value. """ function bubblebath( radius_pdf, ϕ_max::Real, extent::NTuple{D,Real}; min_distance::Real = 0.0, through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true, rng = default_rng() )::Vector{Sphere{D}} where D radii = generate_radii(radius_pdf, ϕ_max, extent; max_tries, verbose, rng) bubblebath(radii, extent; min_distance, through_boundaries, max_tries, max_fails, verbose, rng ) end """ generate_radii( radius_pdf, ϕ_max::Real, extent::NTuple{D,Real}; max_tries = 10000, verbose = true, rng = default_rng() ) where D Generate a vector of radii from the `radius_pdf` distribution, with a limit packing fraction `ϕ_max` in the domain `extent`. """ function generate_radii( radius_pdf, ϕ_max::Real, extent::NTuple{D,Real}; max_tries = 10000, verbose = true, rng = default_rng() )::Vector{Float64} where D # allow ϕ_max=1 as a way to fill the box as much as possible if ~(0 < ϕ_max ≤ 1) throw(ArgumentError("Packing fraction should be between 0 and 1.")) end radii = Float64[] V₀ = prod(extent) tries = 0 while true r = rand(rng, radius_pdf) V = volume(r, D) ϕ = (sum(volume.(radii,D))+V)/V₀ if ϕ ≤ ϕ_max push!(radii, r) else tries += 1 tries > max_tries && break end end if verbose @info "Generated $(length(radii)) spheres." end return radii end """ bubblebath( radii::Vector{<:Real}, extent::NTuple{D,Real}; min_distance = 0.0, through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true, rng = default_rng() ) where D Generate a bath of spheres with radii `radii` in the domain `extent`. """ function bubblebath( radii::Vector{<:Real}, extent::NTuple{D,Real}; min_distance::Real = 0.0, through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true, rng = default_rng() )::Vector{Sphere{D}} where D spheres = Sphere{D}[] bubblebath!(spheres, radii, extent; min_distance, through_boundaries, max_tries, max_fails, verbose, rng ) return spheres end """ is_overlapping(p::NTuple{D,Real}, r::Real, spheres::Vector{Sphere{D}}) where D Test if a sphere of radius `r` centered at `p` overlaps with any sphere in `spheres`. Surface contact is not counted as overlap. """ function is_overlapping( p::NTuple{D,Real}, r::Real, spheres::Vector{Sphere{D}} )::Bool where D for sphere in spheres if is_overlapping(p, r, sphere) return true end end return false end """ is_overlapping(p₁::NTuple{D,Real}, r₁::Real, s₂::Sphere{D}) where D Test if a sphere of radius `r₁` centered at `p₁` overlaps with sphere `s₂`. Surface contact is not counted as overlap. """ @inline function is_overlapping( p₁::NTuple{D,Real}, r₁::Real, s₂::Sphere{D} )::Bool where D is_overlapping(p₁, r₁, s₂.pos, s₂.radius) end """ is_overlapping(p₁::NTuple{D,Real}, r₁::Real, p₂::NTuple{D,Real}, r₂::Real) where D Test if two spheres with radii `r₁` and `r₂`, centered at `p₁` and `p₂` respectively, are overlapping. Surface contact is not counted as overlap. """ @inline function is_overlapping( p₁::NTuple{D,Real}, r₁::Real, p₂::NTuple{D,Real}, r₂::Real )::Bool where D norm(p₁ .- p₂) < r₁ + r₂ end """ is_inside_boundaries(pos::NTuple{D,Real}, radius::Real, extent::NTuple{D,Real}) where D Check if a sphere of radius `radius` centered at `pos` is within domain `extent`. """ function is_inside_boundaries( pos::NTuple{D,Real}, radius::Real, extent::NTuple{D,Real} )::Bool where D for i in 1:D if !(radius ≤ pos[i] ≤ extent[i]-radius) return false end end return true end """ bubblebath!( spheres::Vector{Sphere{D}}, radius_pdf, ϕ_max::Real, extent::NTuple{D,Real}; min_distance::Real = 0.0, through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true, rng = default_rng() ) where D In-place version of `bubblebath`, adds new spheres to the `spheres` vector, which can be already populated. Here, `ϕ_max` does **not** account for spheres that might already be present in the `spheres` vector. E.g. if `packing_fraction(spheres, extent)` is 0.2 and `ϕ_max=0.3`, then the algorithm generates new spheres for a packing fraction of 0.3, which upon insertion will (try to) add up to a total packing fraction of 0.5. To account for the pre-initialized spheres, decrease `ϕ_max` accordingly (`ϕ_max = 0.3-packing_fraction(spheres,extent)` giving 0.1 for this example). """ function bubblebath!( spheres::Vector{Sphere{D}}, radius_pdf, ϕ_max::Real, extent::NTuple{D,Real}; min_distance::Real = 0.0, through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true, rng = default_rng() )::Nothing where D radii = generate_radii(radius_pdf, ϕ_max, extent; max_tries, verbose, rng) bubblebath!(spheres, radii, extent; min_distance, through_boundaries, max_tries, max_fails, verbose, rng ) end """ bubblebath!( spheres::Vector{Sphere{D}}, radii::Vector{<:Real}, extent::NTuple{D,Real}; min_distance::Real = 0.0, through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true, rng = default_rng() ) where D In-place version of `bubblebath`, adds new spheres to the `spheres` vector (which can be already populated). """ function bubblebath!( spheres::Vector{Sphere{D}}, radii::Vector{<:Real}, extent::NTuple{D,Real}; min_distance::Real = 0.0, through_boundaries = false, max_tries = 10000, max_fails = 100, verbose = true, rng = default_rng() )::Nothing where D for r in radii if r ≤ 0 throw(ArgumentError("Sphere radii must be non-negative real numbers.")) end end n₀ = length(spheres) sizehint!(spheres, length(spheres)+n₀) fails = 0 for radius in sort(radii, rev=true) tries = 0 Δ = through_boundaries ? 0.0 : radius while true if tries > max_tries if fails > max_fails @warn "Reached max. number of tries. Interrupting." @goto packing_complete else fails += 1 break end end pos = Δ .+ Tuple(rand(rng, D)) .* (extent .- 2Δ) isvalid_pos = ( !is_overlapping(pos, radius+min_distance, spheres) && (through_boundaries || is_inside_boundaries(pos, radius, extent)) ) if isvalid_pos push!(spheres, Sphere(pos, radius)) break else tries += 1 end end end @label packing_complete if verbose @info "$(length(spheres)-n₀)/$(length(radii)) new spheres inserted." end return nothing end
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
2089
export packing_fraction """ packing_fraction(spheres::Vector{Sphere{D}}, extent::NTuple{D,Real}) where D Evaluate the packing fraction of `spheres` in domain `extent`. This measurement is not exact if spheres are overlapping or cross through the domain boundaries. """ function packing_fraction( spheres::Vector{Sphere{D}}, extent::NTuple{D,Real} )::Float64 where D V₀ = prod(extent) V = 0.0 for sphere in spheres V += volume(sphere) end return V/V₀ end """ volume(sphere::Sphere{2}) Evaluate volume of two-dimensional sphere, i.e. the area of a circle (πr²). """ volume(sphere::Sphere{2})::Float64 = π * sphere.radius^2 """ volume(sphere::Sphere{3}) Evaluate volume of a three-dimensional sphere (4πr³/3) """ volume(sphere::Sphere{3})::Float64 = 4π/3 * sphere.radius^3 """ packing_fraction(radii::Vector{Real}, extent::NTuple{D,Real}) where D Evaluate the packing fraction of a collection of spheres with radii `radii` in domain `extent`. This measurement is not exact if spheres are overlapping or cross through the domain boundaries. """ function packing_fraction( radii::Vector{<:Real}, extent::NTuple{D, Real} )::Float64 where D V₀ = prod(extent) V = 0.0 for radius in radii V += volume(radius, D) end return V/V₀ end """ volume(r::Real, D::Int) Evaluate volume of a sphere of radius `r` in `D` dimensions. Only D=2 and D=3 currently supported. """ function volume(r::Real, D::Int)::Float64 if D == 2 return π*r^2 elseif D == 3 return 4π/3*r^3 end end """ packing_fraction(wm::BitArray) Evaluate the packing fraction in a walkmap `wm`. If `wm` was generated with `probe_radius=0` this represents the real packing fraction, instead if `probe_radius` was not zero, it represents the effective packing fraction experienced by the probe. Unlike the other instances of `packing_fraction`, this one is exact, independently of overlaps and boundary conditions, within the resolution of the walkmap. """ packing_fraction(wm::BitArray) = 1 - count(wm)/length(wm)
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
2672
export walkmap """ walkmap( spheres::AbstractVector{Sphere{D}}, extent::NTuple{D,<:Real}, resolution::Real, probe_radius::Real = 0; boundaries::Symbol = :cut ) where D Generate a walkmap for the given configuration of `spheres` in the domain `extent`, with the desired `resolution.` A positive `probe_radius` restricts the walkable space assuming that the "probe" has a finite size. `boundaries` can be set to `:cut` or `:wrap` to define how to deal with spheres that cross through the domain boundaries (in case there is any). """ function walkmap( spheres::AbstractVector{Sphere{D}}, extent::NTuple{D,<:Real}, resolution::Real, probe_radius::Real = 0; boundaries::Symbol = :cut )::BitArray{D} where D grid = ntuple(i -> (resolution/2):resolution:(extent[i]-resolution/2), D) itr = Iterators.product(grid...) BitArray{D}([is_walkable(pos, probe_radius, spheres, extent, boundaries) for pos in itr]) end """ is_walkable( pos::NTuple{D,<:Real}, r::Real, spheres::AbstractVector{Sphere{D}}, extent::NTuple{D,<:Real}, boundaries::Symbol ) where D Determines whether an object of size `r` can occupy position `pos` in a domain `extent` filled by `spheres`. """ function is_walkable( pos::NTuple{D,<:Real}, r::Real, spheres::AbstractVector{Sphere{D}}, extent::NTuple{D,<:Real}, boundaries::Symbol )::Bool where D if boundaries == :cut return is_walkable(pos, r, spheres) elseif boundaries == :wrap return is_walkable_periodic(pos, r, spheres, extent) else throw(ArgumentError( "Mode $(boundaries) unrecognized. Choose between `:cut` and `:wrap`." )) end end function is_walkable( pos::NTuple{D,<:Real}, r::Real, spheres::AbstractVector{Sphere{D}} )::Bool where D for sphere in spheres if ~is_walkable(pos, r, sphere) return false end end return true end function is_walkable(pos::NTuple{D,<:Real}, r::Real, sphere::Sphere{D})::Bool where D return norm(pos .- sphere.pos) ≥ r + sphere.radius end function is_walkable_periodic( pos::NTuple{D,<:Real}, r::Real, spheres::AbstractVector{Sphere{D}}, extent::NTuple{D,<:Real} )::Bool where D for sphere in spheres if ~is_walkable_periodic(pos, r, sphere, extent) return false end end return true end function is_walkable_periodic( pos::NTuple{D,<:Real}, r::Real, sphere::Sphere{D}, extent::NTuple{D,<:Real} )::Bool where D a = @. (pos - sphere.pos) / extent d = @. (a - round(a)) * extent # minimum-image distance return norm(d) ≥ r + sphere.radius end
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
code
11734
using BubbleBath using Distributions: Uniform using LinearAlgebra: norm using Random: Xoshiro using Test function capture_stderr(f, args, kwargs) original_stderr = stderr out_read, out_write = redirect_stderr() f(args...; kwargs...) # without this the program hangs if f does not write to stderr @info "dummy text" close(out_write) data = readavailable(out_read) close(out_read) s = String(copy(data)) redirect_stderr(original_stderr) return s end @testset "BubbleBath.jl" begin @testset "Spheres" begin # sphere dimensionality is always inherited from pos radius = 1 pos = ntuple(_ -> 5.0, 2) sphere = Sphere(pos, radius) @test sphere isa Sphere{2} pos = ntuple(_ -> 5.0, 3) sphere = Sphere(pos, radius) @test sphere isa Sphere{3} # check fields are assigned correctly @test sphere.pos == pos @test sphere.radius == radius # should work identically when pos is NTuple{D,Float64} or NTuple{D,Int} pos = ntuple(_ -> 5, 3) sphere2 = Sphere(pos, radius) @test sphere2.pos == sphere.pos # if pos is an AbstractVector it should be converted to a tuple pos = rand(3) sphere = Sphere(pos, 1) @test sphere.pos == Tuple(pos) pos = 1:5 sphere = Sphere(pos, 1) @test sphere.pos == Tuple(pos) # non-positive radius not allowed @test_throws ArgumentError Sphere((5,5), 0) @test_throws ArgumentError Sphere((5,5), -1) end @testset "Bubblebath" begin L = 10 extent = ntuple(_ -> L, 3) r = 4.0 # negative radii not allowed @test_throws ArgumentError bubblebath([-r], extent) # packing fraction must be ϕ∈(0,1] @test_throws ArgumentError bubblebath([r], -0.1, extent) @test_throws ArgumentError bubblebath([r], 1.1, extent) bath = bubblebath([r], extent) # should be a vector with only one sphere @test bath isa Vector{Sphere{3}} @test length(bath) == 1 # sphere radius should be r @test bath[1].radius == r # sphere position should not overlap with domain boundaries for i in 1:3 @test r ≤ bath[1].pos[i] ≤ L-r end # packing fraction should be volume of the sphere over domain volume ϕ = packing_fraction(bath, extent) @test ϕ ≈ (4π*r^3/3)/prod(extent) L = 10 extent = ntuple(_ -> L, 3) r = 8.0 # with a large sphere radius (r > L/2), # if through_boundaries = false (default), sphere can't be inserted bath = bubblebath([r], extent) @test isempty(bath) # if max fails are reached, should print info message msg = capture_stderr(bubblebath, ([r,r], extent), (max_tries=0, max_fails=0) ) @test contains(msg, "Reached max. number of tries") # if through_boundaries = true, it will surely cross all domain boundaries bath = bubblebath([r], extent; through_boundaries=true) for i in 1:3 @test !(r ≤ bath[1].pos[i] ≤ L-r) end extent = (10, 15, 12) radius_pdf = Uniform(1, 2) ϕ_max = 0.4 bath = bubblebath(radius_pdf, ϕ_max, extent) # all the spheres should have radius between 1 and 2 @test all(map(s -> 1 ≤ s.radius ≤ 2, bath)) # no sphere should cross domain boundaries @test all(map(s -> BubbleBath.is_inside_boundaries(s.pos, s.radius, extent), bath)) # packing fraction is below ϕ_max ϕ = packing_fraction(bath, extent) @test ϕ ≤ ϕ_max extent = ntuple(_ -> 10, 3) radius_pdf = [2.0] ϕ_max = 0.4 min_distance = 0.5 bath = bubblebath(radius_pdf, ϕ_max, extent; min_distance) # all spheres should be at distance > min_distance (between their surfaces) surface_distances = vec([ norm(bath[i].pos .- bath[j].pos) - (bath[i].radius + bath[j].radius) for i in eachindex(bath), j in eachindex(bath) if j>i ]) @test all(surface_distances .≥ min_distance) # test the verbose keyword L = 10 extent = (L,L) radius_pdf = Uniform(1,2) ϕ_max = 0.3 msg = capture_stderr(bubblebath, (radius_pdf, ϕ_max, extent), (verbose=true,) # default ) @test contains(msg, r"Generated \d+ spheres") @test contains(msg, r"\d+/\d+ new spheres inserted") msg = capture_stderr(bubblebath, (radius_pdf, ϕ_max, extent), (verbose=false,) ) @test ~contains(msg, r"Generated \d+ spheres") @test ~contains(msg, r"\d+/\d+ new spheres inserted") end @testset "In-place Bubbleath" begin L = 50 extent = (L,L) # initialize with one sphere of radius 3 spheres = [Sphere((L/2,L/2), 3.0)] # add 10 more spheres of radius 1 r = 1.0 radii = repeat([r], 10) bubblebath!(spheres, radii, extent) # should be a total of 11 spheres @test length(spheres) == 11 @test count(map(s -> s.radius==3, spheres)) == 1 @test count(map(s -> s.radius==1, spheres)) == 10 # the new spheres should not overlap with the original one overlaps = [ norm(spheres[1].pos .- s.pos) ≤ spheres[1].radius + s.radius for s in spheres[2:end] ] @test !(any(overlaps)) L = 10 extent = (L,L) r = L/2 spheres_old = [Sphere((L/2,L/2), r)] # largest sphere to fit extent spheres_new = copy(spheres_old) # should add nothing since r is too large to fit another sphere bubblebath!(spheres_new, [r], extent) @test spheres_new == spheres_old # if max fails are reached, should print info message max_tries = 1 max_fails = 1 msg = capture_stderr(bubblebath!, (spheres_new, [r,r], extent), (max_tries=0, max_fails=0) ) @test contains(msg, "Reached max. number of tries") end @testset "RNG" begin L = 50 extent = (L,L) radius_pdf = Uniform(5, 10) ϕ_max = 0.35 rng = Xoshiro(1) spheres_1 = bubblebath(radius_pdf, ϕ_max, extent; rng) rng = Xoshiro(1) spheres_2 = bubblebath(radius_pdf, ϕ_max, extent; rng) @test spheres_1 == spheres_2 end @testset "Walkmap" begin extent = (10, 10) pos = (5,5) r = 3 spheres = [Sphere(pos, r)] res = 0.1 wm = walkmap(spheres, extent, res) # walkmap has same dimensions as extent @test ndims(wm) == length(extent) extent = (5.07, 12.0, 8.15) pos = (3, 3, 3) r = 1 spheres = [Sphere(pos, r)] res = 0.1 wm = walkmap(spheres, extent, res) # res defines the size of wm n_nodes = @. floor(Int, extent / res) @test size(wm) == n_nodes extent = (10, 10) pos = (5, 5) r = 3 spheres = [Sphere(pos, r)] res = 0.1 wm = walkmap(spheres, extent, res) xs = range(res/2, extent[1]-res/2; step=res) ys = range(res/2, extent[2]-res/2; step=res) grid = (xs, ys) function getidx(pos, grid, res) ntuple(i -> findfirst(j -> grid[i][j]-res/2 ≤ pos[i] ≤ grid[i][j]+res/2, eachindex(grid[i]) ), length(pos) ) end # wm should be 0 in positions occupied by spheres p₁ = pos p₂ = pos .+ (r-res/2, 0) p₃ = pos .+ (-r/6, r/6) I₁, I₂, I₃ = map(p -> CartesianIndex(getidx(p,grid,res)), (p₁,p₂,p₃)) @test ~wm[I₁] @test ~wm[I₂] @test ~wm[I₃] # 1 in unoccupied positions p₄ = pos .+ (r+res/2, 0) p₅ = pos .+ (0, r+1) I₄, I₅ = map(p -> CartesianIndex(getidx(p,grid,res)), (p₄,p₅)) @test wm[I₄] @test wm[I₅] # if probe_radius>0 the occupied region increases wm₂ = walkmap(spheres, extent, res, 1.0) I = CartesianIndex(getidx(pos.+(r+0.5,0), grid, res)) @test wm[I] && ~wm₂[I] # put a sphere at the boundary extent = (10, 10) pos = (0, 5) r = 4 spheres = [Sphere(pos, r)] res = 0.1 xs = range(res/2, extent[1]-res/2; step=res) ys = range(res/2, extent[2]-res/2; step=res) grid = (xs, ys) wm₁ = walkmap(spheres, extent, res) # boundaries = :cut wm₂ = walkmap(spheres, extent, res; boundaries=:wrap) # if boundaries=:cut the opposite edge is free I = CartesianIndex(getidx((10-res,5), grid, res)) @test wm₁[I] # if boundaries=:wrap the oppposite edge is occupied @test ~wm₂[I] # throw error if boundaries is not :cut or :wrap @test_throws ArgumentError walkmap(spheres, extent, res; boundaries=:periodic) end @testset "Packing fraction" begin # packing fraction should match theoretical values L = 10 extent = (L,L) r = 4 bath = bubblebath([r], extent) @test packing_fraction(bath, extent) ≈ π*r^2 / L^2 extent = (L,L,L) bath = bubblebath([r], extent) @test packing_fraction(bath, extent) ≈ 4π*r^3/3 / L^3 # test same behavior on radii vector instead of bath @test packing_fraction([r], (L,L)) ≈ π*r^2 / L^2 @test packing_fraction([r], (L,L,L)) ≈ 4π*r^3/3 / L^3 # an empty collection should give 0 packing fraction @test packing_fraction(Sphere{2}[], (L,L)) == 0 @test packing_fraction(Float64[], (L,L)) == 0 # packing fractions produced by bubblebath should never be > ϕ_max extent = (8, 10) radius_pdf = Uniform(2,5) ϕ_max = 0.2 bath = bubblebath(radius_pdf, ϕ_max, extent) @test packing_fraction(bath, extent) ≤ ϕ_max extent = (8, 10, 12) radius_pdf = Uniform(2,5) ϕ_max = 0.2 bath = bubblebath(radius_pdf, ϕ_max, extent) @test packing_fraction(bath, extent) ≤ ϕ_max # pre-initialize a bath extent = (15, 15) r = 3 bath = [Sphere((7.5,7.5), r)] ϕ₀ = packing_fraction(bath, extent) # ≈ 0.126 # fill with more spheres radius_pdf = [0.1] ϕ_max = 0.3 bubblebath!(bath, radius_pdf, ϕ_max, extent) # final ϕ will be ϕ_max+ϕ₀ ≈ 0.426 @test packing_fraction(bath, extent) ≈ ϕ_max+ϕ₀ atol=0.02 bath = [Sphere((7.5,7.5), r)] bubblebath!(bath, radius_pdf, ϕ_max-ϕ₀, extent) # now final ϕ will be ϕ_max @test packing_fraction(bath, extent) ≈ ϕ_max atol=0.02 # packing fraction of a walkmap extent = (10, 10) r = 3 spheres = [Sphere((5,5), r)] ϕ₁ = packing_fraction(spheres, extent) res = 0.1 wm = walkmap(spheres, extent, res) ϕ₂ = packing_fraction(wm) @test ϕ₂ ≈ ϕ₁ atol=res^2 # if half of a sphere goes through a boundary # packing fraction of the walkmap is correct spheres = [Sphere((10,5), r)] ϕ = (π*r^2 / prod(extent)) / 2 # exact packing fraction ϕ₀ = packing_fraction(spheres, extent) wm₁ = walkmap(spheres, extent, res) wm₂ = walkmap(spheres, extent, res; boundaries=:wrap) ϕ₁ = packing_fraction(wm₁) ϕ₂ = packing_fraction(wm₂) @test ϕ₀ ≈ 2ϕ @test ϕ₁ ≈ ϕ atol=res^2 @test ϕ₂ ≈ 2ϕ atol=res^2 end end
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
0.2.1
f0c51786db6be8c3a957b6afb67e7707995206b8
docs
3485
# BubbleBath.jl <p align="center" width="100%"> <img src="examples/bubblebath_logo.svg"> </p> [![Build Status](https://github.com/mastrof/BubbleBath.jl/workflows/CI/badge.svg)](https://github.com/mastrof/BubbleBath.jl/actions) [![codecov](https://codecov.io/gh/mastrof/BubbleBath.jl/branch/main/graphs/badge.svg)](https://codecov.io/gh/mastrof/BubbleBath.jl) Generate loose packings of spheres in orthorhombic domains, in 2 and 3 dimensions. ## Features * Fill a domain with spheres from a given distribution of radii to reach a target packing fraction, or from already-sampled radii. * Control minimum allowed distance between spheres. * Decide whether spheres can cross through domain boundaries or not. `BubbleBath.jl` just employs the trivial brute-force method, with the only peculiarity that spheres are introduced in order of decreasing radius. Dense packings are obtained with reasonable performance, but spatial correlations between sphere sizes are introduced. This is **not** an algorithm to generate tight, space-filling packings. ## Example usage The package exports a `Sphere{D}` type, which is just a wrapper around a position `pos::NTuple{D,Float64}` and a radius `radius::Float64`, and the `bubblebath` function, which creates a loose packing of spheres in a domain. To generate a (2D) distribution of spheres with radii uniformly distributed within 1 and 5, in a rectangular domain of edges 100 and 50, with a packing fraction 0.4, we can do ```julia using BubbleBath using Distributions: Uniform radius_pdf = Uniform(1,5) extent = (100, 50) ϕ_max = 0.4 bath = bubblebath(radius_pdf, ϕ_max, extent) ``` ![Bubblebath in 2D](examples/2d.svg) If we want to impose a minimal distance between the surface of spheres, the `min_distance` keyword can be used ```julia radius_pdf = Uniform(1,5) extent = (100, 50) ϕ_max = 0.4 min_distance = 2.0 bath = bubblebath(radius_pdf, ϕ_max, extent; min_distance) ``` ![Bubblebath in 2D with minimum separation](examples/2d_mindist.svg) Again, the procedure in 3D is identical ```julia radius_pdf = Uniform(10,25) extent = (100, 100, 100) ϕ_max = 0.3 min_distance = 10.0 bath = bubblebath(radius_pdf, ϕ_max, extent; min_distance) ``` ![Bubblebath in 3D with minimum separation](examples/3d_mindist.svg) We can verify that the generated radii closely match the chosen distribution, even at relatively high packing fractions. ```julia using Distributions: Exponential θ = 3.0 # average radius radius_pdf = Exponential(θ) extent = ntuple(_->300, 3) bath1 = bubblebath(radius_pdf, 0.3, extent) # this can take a while bath2 = bubblebath(radius_pdf, 0.6, extent) r1 = map(s -> s.radius, bath1) r2 = map(s -> s.radius, bath2) ``` ![Comparison of theoretical and generated radius distributions](examples/radius_pdf.svg) Finally, `bubblebath` also has an in-place version `bubblebath!`, which can operate on pre-initialised vectors of `Sphere`s. For example, to produce the `BubbleBath.jl` logo: ```julia using Distributions: Exponential # initialise vector with three spheres at desired locations Lx = 400 Ly = 400 extent = (Lx,Ly) R = 50 D = 60 spheres = [ Sphere((Lx/2-D,Ly/2-D), R), Sphere((Lx/2+D,Ly/2-D), R), Sphere((Lx/2,Ly/2+3D/4), R) ] # add new spheres with exponential distribution of radii radius_pdf = Exponential(2.0) ϕ_max = 0.25 - packing_fraction(spheres, extent) min_distance = 2.0 bubblebath!(spheres, radius_pdf, ϕ_max, extent; min_distance) ``` <img src="examples/2d_inplace.svg" width="600">
BubbleBath
https://github.com/mastrof/BubbleBath.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
2555
#!/usr/bin/env julia using Cumulants using JLD2 using FileIO using ArgParse #import Cumulants: mom2cums include("../test/testfunctions/leeuw_cumulants_no_nested_func.jl") """ comptime(data::Matrix{Float}, f::Function, m::Int) Returns Float, a computional time of m'th statisitics calulation of multivariate data """ function comptime(data::Matrix{Float64}, f::Function, m::Int) f(data[1:4, 1:4], m) t = time_ns() f(data, m) Float64(time_ns()-t)/1.0e9 end """ comtimes(m::Int, t::Vector{Int}, n::Vector{Int}, f::Function) Returns Matrix, a computional time of m'th statisitics of multivariate data, given statisitcs's order m, number of variables n, number of data realisation t """ function comtimes(m::Int, t::Vector{Int}, n::Vector{Int}, f::Function) compt = zeros(length(n), length(t)) for i in 1:length(t) for j in 1:length(n) data = randn(t[i], n[j]) println("n = ", n[j]) println("t = ", t[i]) compt[j,i] = comptime(data, f, m) end end compt end """ savecomptime(m::Int, T::Vector{Int}, n::Vector{Int}, cache::Bool) Save a file in jld2 format of the computional times of moment, naivemoment, rawmoment """ function savecomptime(m::Int, t::Vector{Int}, n::Vector{Int}) filename = replace("res/"*string(m)*string(t)*string(n)*"leeuw_cums.jld2", "["=>"_") filename = replace(filename, "]"=>"") fs = [cumulants_upto_p, cumulants] compt = Dict{String, Any}() for f in fs fname = "$(f)" println(fname) println("called function " , fname) push!(compt, fname => comtimes(m, t, n, f)) end push!(compt, "t" => t) push!(compt, "n" => n) push!(compt, "m" => m) push!(compt, "x" => "n") push!(compt, "functions" => [["cumulants_upto_p", "cumulants"]]) save(filename, compt) end """ main(args) Returns file of the speedup of momant, naivemoment rawmoment, .... Takes optional arguments from bash """ function main(args) s = ArgParseSettings("description") @add_arg_table s begin "--order", "-m" help = "m, the order of cumulant, ndims of cumulant's tensor" default = 4 arg_type = Int "--nvar", "-n" nargs = '*' default = [20, 24, 28] help = "n, numbers of marginal variables" arg_type = Int "--dats", "-t" help = "t, numbers of data records" nargs = '*' default = [10000] arg_type = Int end parsed_args = parse_args(s) m = parsed_args["order"] n = parsed_args["nvar"] t = parsed_args["dats"] savecomptime(m, t, n) end main(ARGS)
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
1650
#!/usr/bin/env julia using Cumulants using JLD2 using FileIO using ArgParse function comptime(data::Matrix{Float64}, ccalc::Function, m::Int, b::Int) ccalc(data[1:4, 1:4], m, 2) t = time_ns() ccalc(data, m, b) Float64(time_ns()-t)/1.0e9 end function savect(t::Vector{Int}, n::Int, m::Int) maxb = round(Int, sqrt(n)) comptimes = zeros(maxb, length(t)) println("max block size = ", maxb) for k in 1:length(t) data = randn(t[k], n) for b in 1:maxb comptimes[b, k] = comptime(data, cumulants, m, b) println("n = ", n) println("bloks size = ", b) end end filename = replace("res/$(m)_$(t)_$(n)_nblocks.jld2", "["=>"") filename = replace(filename, "]"=>"") compt = Dict{String, Any}("cumulants"=> comptimes) push!(compt, "t" => t) push!(compt, "n" => n) push!(compt, "m" => m) push!(compt, "x" => "block size") push!(compt, "block size" => [collect(1:maxb)...]) push!(compt, "functions" => [["cumulants"]]) save(filename, compt) end function main(args) s = ArgParseSettings("description") @add_arg_table s begin "--order", "-m" help = "m, the order of cumulant, ndims of cumulant's tensor" default = 4 arg_type = Int "--nvar", "-n" default = 48 help = "n, numbers of marginal variables" arg_type = Int "--dats", "-t" help = "t, numbers of data records" nargs = '*' default = [10000, 20000] arg_type = Int end parsed_args = parse_args(s) m = parsed_args["order"] n = parsed_args["nvar"] t = parsed_args["dats"] savect(t::Vector{Int}, n::Int, m::Int) end main(ARGS)
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
2139
#!/usr/bin/env julia using Cumulants using JLD2 using FileIO using ArgParse using Distributed function comptime(data::Matrix{Float64}, ccalc::Function, m::Int, b::Int) ccalc(data[1:4, 1:4], m, b) t = time_ns() ccalc(data, m, b) Float64(time_ns()-t)/1.0e9 end function comptimesonprocs(t::Int, n::Int, m::Int, p::Int, b::Int) data = randn(t, n) times = zeros(p) for i in 1:p addprocs(i) println("number of workers = ", nworkers()) eval(Expr(:toplevel, :(@everywhere using Cumulants))) times[i] = comptime(data, moment, m, b) rmprocs(workers()) end times end function savect(t::Int, n::Int, m::Int, maxprocs::Int, b::Int) comptimes = zeros(maxprocs) comptimes = comptimesonprocs(t,n,m,maxprocs, b) onec = fill(comptimes[1], maxprocs) filename = replace("res/$(m)_$(t)_$(n)_$(b)_nprocs.jld2", "["=>"") filename = replace(filename, "]"=>"") compt = Dict{String, Any}("cumulants"=> onec, "cumulantsnc"=> comptimes) push!(compt, "t" => [t]) push!(compt, "n" => n) push!(compt, "m" => m) push!(compt, "x" => "procs") push!(compt, "procs" => collect(1:maxprocs)) push!(compt, "functions" => [["cumulants", "cumulantsnc"]]) save(filename, compt) end function main(args) s = ArgParseSettings("description") @add_arg_table s begin "--order", "-m" help = "m, the order of cumulant, ndims of cumulant's tensor" default = 4 arg_type = Int "--nvar", "-n" default = 50 help = "n, numbers of marginal variables" arg_type = Int "--dats", "-t" help = "t, numbers of data records" #nargs = '*' default = 100000 arg_type = Int "--maxprocs", "-p" help = "maximal number of procs" default = 4 arg_type = Int "--blocksize", "-b" help = "set a block size" default = 2 arg_type = Int end parsed_args = parse_args(s) m = parsed_args["order"] n = parsed_args["nvar"] t = parsed_args["dats"] p = parsed_args["maxprocs"] b = parsed_args["blocksize"] savect(t::Int, n::Int, m::Int, p::Int, b::Int) end main(ARGS)
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
2473
#!/usr/bin/env julia using Cumulants using JLD2 using FileIO using ArgParse """ comptime(data::Matrix{Float}, f::Function, m::Int) Returns Float, a computional time of m'th statisitics calulation of multivariate data """ function comptime(data::Matrix{Float64}, f::Function, m::Int) f(data[1:4, 1:4], m) t = time_ns() f(data, m) Float64(time_ns()-t)/1.0e9 end """ comtimes(m::Int, t::Vector{Int}, n::Vector{Int}, f::Function) Returns Matrix, a computional time of m'th statisitics of multivariate data, given statisitcs's order m, number of variables n, number of data realisation t """ function comtimes(m::Int, t::Vector{Int}, n::Vector{Int}, f::Function) compt = zeros(length(n), length(t)) for i in 1:length(t) for j in 1:length(n) data = randn(t[i], n[j]) println("n = ", n[j]) println("t = ", t[i]) compt[j,i] = comptime(data, f, m) end end compt end """ savecomptime(m::Int, T::Vector{Int}, n::Vector{Int}, cache::Bool) Save a file in jld2 format of the computional times of moment, naivemoment, rawmoment """ function savecomptime(m::Int, t::Vector{Int}, n::Vector{Int}) filename = replace("res/"*string(m)*string(t)*string(n)*".jld2", "["=>"_") filename = replace(filename, "]"=>"") fs = [moment, naivemoment, cumulants, naivecumulant] compt = Dict{String, Any}() for f in fs fname = "$(f)" println("called function " , fname) push!(compt, fname => comtimes(m, t, n, f)) end push!(compt, "t" => t) push!(compt, "n" => n) push!(compt, "m" => m) push!(compt, "x" => "n") push!(compt, "functions" => [["naivemoment", "moment"], ["naivecumulant", "cumulants"]]) save(filename, compt) end """ main(args) Returns file of the speedup of momant, naivemoment rawmoment, .... Takes optional arguments from bash """ function main(args) s = ArgParseSettings("description") @add_arg_table s begin "--order", "-m" help = "m, the order of cumulant, ndims of cumulant's tensor" default = 4 arg_type = Int "--nvar", "-n" nargs = '*' default = [20, 24, 28] help = "n, numbers of marginal variables" arg_type = Int "--dats", "-t" help = "t, numbers of data records" nargs = '*' default = [10000] arg_type = Int end parsed_args = parse_args(s) m = parsed_args["order"] n = parsed_args["nvar"] t = parsed_args["dats"] savecomptime(m, t, n) end main(ARGS)
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
1266
#!/usr/bin/env julia using Distributions using FileIO using JLD2 using Random using SpecialFunctions """ gendat(nu::Int, t::Int) Returns Matrix{Float64} - t realisations from t-student multivatiate distribution with nu degress of freedom """ function gendat(nu::Int, t::Int = 150000000) cm = [[1. 0.7 0.7 0.7];[0.7 1. 0.7 0.7]; [0.7 0.7 1. 0.7]; [0.7 0.7 0.7 1]] p = MvTDist(nu, [0., 0., 0., 0.],cm) return Array(transpose(rand(p, t))) end """ tmom(nu::Int, k::Int) Returns Float64, the k'th moment of standard t distribution with nu degreed of freedom """ tmom(nu::Int, k::Int) = gamma((k+1)/2)*gamma((nu-k)/2)*nu^(k/2)/(sqrt(pi)*gamma(nu/2)) """ tcum(nu::Int, k::Int) Returns Float64, the k'th cumulant of standard t distribution with nu degreed of freedom """ function tcum(nu::Int, k::Int) if k in (1,3,5) return 0. elseif k == 2 return tmom(nu, 2) elseif k == 4 return tmom(nu, 4) - 3*tmom(nu, 2)^2 elseif k == 6 return tmom(nu, 6) - 15*tmom(nu, 4)*tmom(nu, 2) + 30*tmom(nu, 2)^3 end end function main() nu = 14 Random.seed!(42) data = gendat(nu::Int) d = Dict{String, Any}("theoretical diag" => Float64[tcum(14, k) for k in 1:6]) push!(d, "data" => data) save("data/datafortests.jld2", d) end main()
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
281
#!/usr/bin/env julia using JLD2 using FileIO using Cumulants function main() d = try load("data/datafortests.jld2") catch println("please run gendata.jl") return () end c = cumulants(d["data"], 6) save("data/cumulants.jld2", Dict("cumulants" => c)) end main()
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
1169
#!/usr/bin/env julia using JLD2 using FileIO using SymmetricTensors using PyCall @pyimport matplotlib as mpl using PyPlot mpl.rc("text", usetex=true) mpl.rc("font", family="serif", size = 8) """ pltdiag() Plots a chart of superdiagonal elements of cumulants of and its theoretical values """ function pltdiag() tdiag = try load("datafortests.jld2")["theoretical diag"] catch println("please run test/gandata.jl and test/testondata.jl") return () end cum = try load("cumulants.jld2")["cumulants"] catch println("please run test/testondata.jl") return () end n = cum[1].dats fig, ax = subplots(figsize = (3., 2.3)) col = ["cyan", "brown", "green", "red", "blue", "black"] for order in (2,4,5,6) c = cum[order] ax[:plot](diag(c), "o", color = col[order], label = "$order cumulant", markersize=3) ax[:plot]([fill(tdiag[order], n)...], "--", color = col[order], label = "theoretical") end PyPlot.ylabel("superdiagonal elements", labelpad = -1) PyPlot.xlabel("superdiagonal index", labelpad = -3) ax[:legend](fontsize = 4.5, loc = 5) fig[:savefig]("diagcumels.pdf") end function main() pltdiag() end main()
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
1724
#!/usr/bin/env julia using PyCall using PyPlot using JLD2 using FileIO using ArgParse function singleplot(filename::String, name::String, compare::String = "") d = load(filename*".jld2") if compare == "" comptimes = d[name] ylab = "computional time [s]" else comptimes = d[name]./d[compare] ylab = "speedup" end x = d["x"] t = d["t"] m = d["m"] fig, ax = subplots(figsize = (2.5, 2.)) col = ["red", "blue", "black", "green", "yellow", "orange"] marker = [":s", ":o", ":v", ":<", ":>", ":d"] for i in 1:size(comptimes, 2) tt = t[i] ax[:plot](d[x], comptimes[:,i], marker[i], label= "t = $tt", color = col[i], markersize=2.5, linewidth = 1) end PyPlot.ylabel(ylab, labelpad = -1) PyPlot.xlabel(x, labelpad = -1) if maximum(comptimes) > 10 f = matplotlib[:ticker][:ScalarFormatter]() f[:set_powerlimits]((-3, 2)) else f = matplotlib[:ticker][:FormatStrFormatter]("%.1f") end ax[:yaxis][:set_major_formatter](f) ax[:legend](fontsize = 6, loc = 2, ncol = 1) subplots_adjust(left = 0.22, bottom = 0.20,top=0.92) fig[:savefig](name*filename*".pdf") end """ pltspeedup(comptimes::Array{Float}, m::Int, n::Vector{Int}, T::Vector{Int}, label::String) Returns a figure in .pdf format of the computional speedup of cumulants function """ function pltspeedup(filename::String) d = load(filename) filename = replace(filename, ".jld2"=>"") for f in d["functions"] singleplot(filename::String, f...) end end function main(args) s = ArgParseSettings("description") @add_arg_table s begin "file" help = "the file name" arg_type = String end parsed_args = parse_args(s) pltspeedup(parsed_args["file"]) end main(ARGS)
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
502
module Cumulants using SymmetricTensors using Combinatorics using Distributions using Distributed import SymmetricTensors: pyramidindices, ind2range, sizetest, getblockunsafe import Distributions: moment if VERSION >= v"1.3" using CompilerSupportLibraries_jll end #calculates moments and cumulants using block structures (SymmetricTensors) include("cumulant.jl") #naive implementation include("naivecumulants.jl") export moment, cumulants, naivecumulant, naivemoment end
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
9177
# following code is used to caclulate moments in SymmetricTensor form ## """ blockel(X::Matrix{T}, i::Tuple, j::Tuple, b::Int) Returns Float, the element of the block (indexed by j) of the moment's tensor of X, at index cd i inside a block, where b is a standard blocks' size ```jldoctest julia> M = [1. 2. 5. 6. ; 3. 4. 7. 8.]; julia> blockel(M, (1,1), (1,1), 2) 5.0 julia> blockel(M, (1,1), (2,2), 2) 37.0 ``` """ function blockel(data, mi, mj, b) ret = 0. t = size(data, 1) for l in 1:t temp = 1. for k in 1:length(mi) @inbounds ind = (mj[k]-1)*b+mi[k] @inbounds temp *= data[l,ind] end ret += temp end ret/t end """ momentblock(X::Matrix{T}, j::Tuple, dims::Tuple, b::Int) Returns a block of a moment's tensor of X. A block is indexed by j and if size dims, b is a standatd block size. ```jldoctest julia> M = [1. 2. 5. 6. ; 3. 4. 7. 8.]; julia> momentblock(M, (1,1), (2,2), 2) 2×2 Array{Float64,2}: 5.0 7.0 7.0 10.0 ``` """ function momentblock(X::Matrix{T}, j::Tuple, dims::Tuple, b::Int) where {T <: AbstractFloat} ret = zeros(T, dims) for ind = 1:(prod(dims)) i = Tuple(CartesianIndices(dims)[ind]) @inbounds ret[i...] = blockel(X, i, j, b) end ret end """ usebl(bind::Tuple, n::Int, b::Int, nbar::Int) Returns: Tuple{Int}, sizes of the last block """ function usebl(bind::Tuple, n::Int, b::Int, nbar::Int) bl = n - b*(nbar-1) map(i -> (i == nbar) ? (bl) : (b), bind) end """ momentn1c(X::Matrix{Float}, m::Int, b::Int) Returns: SymmetricTensor{Float, m}, a tensor of the m'th moment of X, where b is a block size. Uses 1 core implementation """ function moment1c(X::Matrix{T}, m::Int, b::Int=2) where T <: AbstractFloat n = size(X, 2) sizetest(n, b) nbar = mod(n,b)==0 ? n÷b : n÷b + 1 ret = arraynarrays(T, fill(nbar, m)...,) for j in pyramidindices(m, nbar) dims = (mod(n,b) == 0 || !(nbar in j)) ? (fill(b,m)...,) : usebl(j, n, b, nbar) @inbounds ret[j...] = momentblock(X, j, dims, b) end SymmetricTensor(ret; testdatstruct = false) end """ momentnc(X::Matrix}, m::Int, b::Int) Returns: SymmetricTensor{Float, m}, a tensor of the m'th moment of X, where b is a block size. Uses multicore parallel implementation via pmap() """ function momentnc(x::Matrix{T}, m::Int, b::Int = 2) where T <: AbstractFloat t = size(x, 1) f(z::Matrix{T}) = moment1c(z, m, b) k = length(workers()) r = mod(t,k)==0 ? t÷k : t÷k + 1 y = [x[ind2range(i, r, t), :] for i in 1:k] ret = pmap(f, y) (r*sum(ret[1:(end-1)])+(t-(k-1)*r)*ret[end])/t end """ moment(X::Matrix}, m::Int, b::Int) Returns: SymmetricTensor{Float, m}, a tensor of the m'th moment of X, where b is a block size. Calls 1 core or multicore moment function. """ moment(X::Matrix{T}, m::Int, b::Int=2) where T <: AbstractFloat = (size(X,1)/10>nworkers()>1) ? momentnc(X, m, b) : moment1c(X, m, b) # ---- following code is used to caclulate cumulants in SymmetricTensor form---- """ Type that stores a partition of multiindex into subests, sizes of subests, size of original multitindex and number of subsets """ mutable struct IndexPart part::Vector{Vector{Int64}} subsetslen::Vector{Int64} nind::Int npart::Int (::Type{IndexPart})(part::Vector{Vector{Int64}}, subsetslen::Vector{Int64}, nind::Int, npart::Int) = new(part, subsetslen, nind, npart) end """ indpart(nind::Int, npart::Int, e::Int = 1) Returns vector of IndexPart type, that includes partitions of set [1, 2, ..., nind] into npart subests of size != e, sizes of each subest, size of original set and number of partitions ```jldoctest julia>indpart(4,2) 3-element Array{Cumulants.IndexPart,1}: IndexPart(Array{Int64,1}[[1,2],[3,4]],[2,2],4,2) IndexPart(Array{Int64,1}[[1,3],[2,4]],[2,2],4,2) IndexPart(Array{Int64,1}[[1,4],[2,3]],[2,2],4,2) ``` """ function indpart(nind::Int, npart::Int, e::Int = 1) part_set = IndexPart[] for part in partitions(1:nind, npart) subsetslen = map(length, part) if !(e in subsetslen) push!(part_set, IndexPart(part, subsetslen, nind, npart)) end end part_set end """ accesscum(mulind::Tuple{Int, ...}, ::IndexPart, cum::SymmetricTensor{Float}...) Returns: vector of blocks from cumulants. Each block correspond to a subests of partition (part) of multiindex (multiind). ```jldoctest julia> cum = SymmetricTensor([1.0 2.0 3.0; 2.0 4.0 6.0; 3.0 6.0 5.0]); julia> accesscum((1,1,1,1), IndexPart(Array{Int64,1}[[1,2],[3,4]],[2,2],4,2), cum) Array{Float64,N}[ [1.0 2.0; 2.0 4.0], [1.0 2.0; 2.0 4.0]] julia> accesscum((1,1,1,2), IndexPart(Array{Int64,1}[[1,2],[3,4]],[2,2],4,2), cum) Array{Float64,N}[ [1.0 2.0; 2.0 4.0], [3.0 0.0; 6.0 0.0]] julia> accesscum((1,1,1,1), IndexPart(Array{Int64,1}[[1,4],[2,3]],[2,2],4,2), cum) Array{Float64,N}[ [1.0 2.0; 2.0 4.0], [1.0 2.0; 2.0 4.0]] ``` """ function accesscum(mulind::Tuple, part::IndexPart, cum::SymmetricTensor{T}...) where T <: AbstractFloat blocks = Array{Array{T}}(undef, part.npart) sq = cum[1].sqr || !(cum[1].bln in mulind) for k in 1:part.npart data = getblockunsafe(cum[part.subsetslen[k]], mulind[part.part[k]]) if sq @inbounds blocks[k] = data else ind = map(i -> 1:size(data,i), 1:part.subsetslen[k]) datapadded = zeros(T, fill(cum[1].bls, part.subsetslen[k])...,) @inbounds datapadded[ind...] = data @inbounds blocks[k] = datapadded end end blocks end """ outprodblocks(n::Int, part::Vector{Vector{Int}}, blocks::Vector{Array{T}} Returns: n dims Array of outer product of blocks, given partition of indices, part. ```jldoctest julia> blocks = 2-element Array{Array{Float64,N},1}[[1.0 2.0; 2.0 4.0], [1.0 2.0; 2.0 4.0]]; julia> outprodblocks(IndexPart(Array{Int64,1}[[1,2],[3,4]],[2,2],4,2), blocks) 2×2×2×2 Array{Float64,4}: [:, :, 1, 1] = 1.0 2.0 2.0 4.0 [:, :, 2, 1] = 2.0 4.0 4.0 8.0 [:, :, 1, 2] = 2.0 4.0 4.0 8.0 [:, :, 2, 2] = 4.0 8.0 8.0 16.0 ``` """ function outprodblocks(inp::IndexPart, blocks::Vector{Array{T}}) where T <: AbstractFloat b = size(blocks[1], 1) block = zeros(T, fill(b, inp.nind)...,) for i = 1:(b^inp.nind) muli = Tuple(CartesianIndices((fill(b, inp.nind)...,))[i]) @inbounds block[muli...] = mapreduce(k -> blocks[k][muli[inp.part[k]]...], *, 1:inp.npart) end block end """ outerprodcum(retd::Int, npart::Int, cum::SymmetricTensor...; exclpartlen::Int = 1) Returns retd dims outer products of npart cumulants in SymmetricTensor form. exclpartlen is a length of partitions to be excluded in calculations, in this algorithm exclpartlen = 1 ```jldoctest julia> cum = SymmetricTensor([1.0 2.0 3.0; 2.0 4.0 6.0; 3.0 6.0 5.0]); julia> outerprodcum(4,2,cum, cum) SymmetricTensors.SymmetricTensor{Float64,4}(Union{Array{Float64,4}, Void}[[3.0 6.0; 6.0 12.0] [6.0 12.0; 12.0 24.0] [6.0 12.0; 12.0 24.0] [12.0 24.0; 24.0 48.0] nothing; nothing nothing] Union{Array{Float64,4}, Void}[nothing nothing; nothing nothing] Union{Array{Float64,4}, Void}[[9.0 18.0; 18.0 36.0] [18.0 36.0; 36.0 72.0] nothing; nothing nothing] Union{Array{Float64,4}, Void}[[23.0 46.0; 46.0 92.0] [45.0; 90.0]; nothing [75.0]], 2, 2, 3, false) ``` """ function outerprodcum(retd::Int, npart::Int, cum::SymmetricTensor{T}...; exclpartlen::Int = 1) where T <: AbstractFloat parts = indpart(retd, npart, exclpartlen) prodcum = arraynarrays(T, fill(cum[1].bln, retd)...,) for muli in pyramidindices(retd, cum[1].bln) block = zeros(T, fill(cum[1].bls, retd)...,) for part in parts blocks = accesscum(muli, part, cum...) @inbounds block += outprodblocks(part, blocks) end if !cum[1].sqr && cum[1].bln in muli ran = map(k->cum[1].bln == muli[k] ? (1:cum[1].dats% cum[1].bls) : (1:cum[1].bls), 1:retd) @inbounds block = block[ran...] end @inbounds prodcum[muli...] = block end SymmetricTensor(prodcum; testdatstruct = false) end """ cumulant(X::Vector{Matrix}, cum::SymmetricTensor...) Returns: SymmetricTensor{Float, m}, a tensor of the m'th cumulant of X, given Vector of cumulants of order 2, ..., m-2 """ function cumulant(X::Matrix{T}, cum::SymmetricTensor{T}...) where T <: AbstractFloat m = length(cum) + 2 ret = moment(X, m, cum[1].bls) for sigma in 2:div(m, 2) ret -= outerprodcum(m, sigma, cum...) end ret end """ cumulants(X::Matrix, m::Int, b::Int) Returns [SymmetricTensor{Float, 1}, SymmetricTensor{Float, 2}, ..., SymmetricTensor{Float, m}], vector of cumulant tensors ``` julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> convert(Array, cumulants(M, 3)[3]) 2×2×2 Array{Float64,3}: [:, :, 1] = 0.0 0.0 0.0 0.0 [:, :, 2] = 0.0 0.0 0.0 0.0 ``` """ function cumulants(X::Matrix{T}, m::Int = 4, b::Int = 2) where T <: AbstractFloat cvec = Array{SymmetricTensor{T}}(undef, m) cvec[1] = moment1c(X, 1, b) X = X .- mean(X, dims=1) for i = 2:m @inbounds cvec[i] = (i < 4) ? moment1c(X, i, b) : cumulant(X, cvec[1:(i-2)]...) end cvec end
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
5615
# --- calculates moment's tensor """ momel(X::Matrix{Float}, ind::Tuple) Returns Float, an element of moment's tensor at ind multiindex ```jldoctest julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> momel(M, (1,1,1,1)) 0.4318298020613279 ``` """ @inline momel(X::Matrix{T}, multind::Tuple) where T<: AbstractFloat = blockel(X, multind, multind, 0) """ naivemoment(data::Matrix{Float}, m::Int) Returns Array{Float, m} the m'th moment tensor ```jldoctest julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> naivemoment(M, 3) 2×2×2 Array{Float64,3}: [:, :, 1] = -0.523092 0.142552 0.142552 -0.0407653 [:, :, 2] = 0.142552 -0.0407653 -0.0407653 0.0120729 ``` """ function naivemoment(X::Matrix{T}, m::Int = 4) where T<: AbstractFloat n = size(X, 2) moment = zeros(T, fill(n, m)...,) for i = 1:(n^m) ind = Tuple(CartesianIndices((fill(n, m)...,))[i]) @inbounds moment[ind...] = momel(X, ind) end moment end # --- uses the naive method to calculate cumulants 2 - 6 """ mixel(X::Matrix{T}, ind::Tuple) Returns Float, mixed element for cumulants 4-6 at ind multi-index ```jldoctest julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> mixel(M, (1,1,1,1)) -1.232956812564408 mixel(M, (1,1,1,1,1,1)) 1.015431116914347 ``` """ function mixel(X::Matrix{T}, i::Tuple) where T<: AbstractFloat a = zero(T) if length(i) == 4 a -= momel(X, (i[1],i[2]))*momel(X, (i[3],i[4])) a -= momel(X, (i[1],i[3]))*momel(X, (i[2],i[4])) + momel(X, (i[1],i[4]))*momel(X, (i[2],i[3])) elseif length(i) == 5 a -= momel(X, (i[1],i[2],i[3]))*momel(X, (i[4],i[5])) + momel(X, (i[1],i[2],i[4]))*momel(X, (i[3],i[5])) a -= momel(X, (i[1],i[2],i[5]))*momel(X, (i[3],i[4])) + momel(X, (i[2],i[3],i[4]))*momel(X, (i[1],i[5])) a -= momel(X, (i[2],i[3],i[5]))*momel(X, (i[1],i[4])) + momel(X, (i[1],i[3],i[4]))*momel(X, (i[2],i[5])) a -= momel(X, (i[1],i[3],i[5]))*momel(X, (i[2],i[4])) + momel(X, (i[3],i[4],i[5]))*momel(X, (i[1],i[2])) a -= momel(X, (i[2],i[4],i[5]))*momel(X, (i[1],i[3])) + momel(X, (i[1],i[4],i[5]))*momel(X, (i[2],i[3])) elseif length(i) == 6 a1 = -momel(X, (i[1],i[2],i[3]))*momel(X, (i[4],i[5], i[6])) - momel(X, (i[1],i[2],i[4]))*momel(X, (i[3],i[5], i[6])) a1 -= momel(X, (i[1],i[2],i[5]))*momel(X, (i[3],i[4], i[6])) + momel(X, (i[1],i[2],i[6]))*momel(X, (i[3],i[4], i[5])) a1 -= momel(X, (i[1],i[3],i[4]))*momel(X, (i[2],i[5], i[6])) + momel(X, (i[1],i[3],i[5]))*momel(X, (i[2],i[4], i[6])) a1 -= momel(X, (i[1],i[3],i[6]))*momel(X, (i[2],i[4], i[5])) + momel(X, (i[1],i[4],i[5]))*momel(X, (i[2],i[3], i[6])) a1 -= momel(X, (i[1],i[4],i[6]))*momel(X, (i[2],i[3], i[5])) + momel(X, (i[1],i[5],i[6]))*momel(X, (i[2],i[3], i[4])) a2 = -momel(X, (i[1],i[2],i[3],i[4]))*momel(X, (i[5], i[6])) - momel(X, (i[1],i[2],i[3],i[5]))*momel(X, (i[4],i[6])) a2 -= momel(X, (i[1],i[2],i[3],i[6]))*momel(X, (i[4], i[5])) + momel(X, (i[1],i[2],i[4],i[5]))*momel(X, (i[3], i[6])) a2 -= momel(X, (i[1],i[2],i[4],i[6]))*momel(X, (i[3], i[5])) + momel(X, (i[1],i[2],i[5],i[6]))*momel(X, (i[3], i[4])) a2 -= momel(X, (i[3],i[4],i[5],i[6]))*momel(X, (i[1], i[2])) + momel(X, (i[1],i[3],i[4],i[5]))*momel(X, (i[2], i[6])) a2 -= momel(X, (i[1],i[3],i[4],i[6]))*momel(X, (i[2], i[5])) + momel(X, (i[1],i[3],i[5],i[6]))*momel(X, (i[2], i[4])) a2 -= momel(X, (i[2],i[4],i[5],i[6]))*momel(X, (i[1], i[3])) + momel(X, (i[1],i[4],i[5],i[6]))*momel(X, (i[2], i[3])) a2 -= momel(X, (i[2],i[3],i[5],i[6]))*momel(X, (i[1], i[4])) + momel(X, (i[2],i[3],i[4],i[6]))*momel(X, (i[1], i[5])) a2 -= momel(X, (i[2],i[3],i[4],i[5]))*momel(X, (i[1], i[6])) a3 = -momel(X, (i[1],i[2]))*momel(X, (i[3],i[4]))*momel(X, (i[5], i[6])) a3 -= momel(X, (i[1],i[2]))*momel(X, (i[3],i[5]))*momel(X, (i[4], i[6])) a3 -= momel(X, (i[1],i[2]))*momel(X, (i[3],i[6]))*momel(X, (i[4], i[5])) a3 -= momel(X, (i[1],i[3]))*momel(X, (i[2],i[4]))*momel(X, (i[5], i[6])) a3 -= momel(X, (i[1],i[3]))*momel(X, (i[2],i[5]))*momel(X, (i[4], i[6])) a3 -= momel(X, (i[1],i[3]))*momel(X, (i[2],i[6]))*momel(X, (i[4], i[5])) a3 -= momel(X, (i[1],i[4]))*momel(X, (i[2],i[3]))*momel(X, (i[5], i[6])) a3 -= momel(X, (i[1],i[5]))*momel(X, (i[2],i[3]))*momel(X, (i[4], i[6])) a3 -= momel(X, (i[1],i[6]))*momel(X, (i[2],i[3]))*momel(X, (i[4], i[5])) a3 -= momel(X, (i[1],i[4]))*momel(X, (i[2],i[5]))*momel(X, (i[3], i[6])) a3 -= momel(X, (i[1],i[4]))*momel(X, (i[2],i[6]))*momel(X, (i[3], i[5])) a3 -= momel(X, (i[1],i[5]))*momel(X, (i[2],i[4]))*momel(X, (i[3], i[6])) a3 -= momel(X, (i[1],i[6]))*momel(X, (i[2],i[4]))*momel(X, (i[3], i[5])) a3 -= momel(X, (i[1],i[5]))*momel(X, (i[2],i[6]))*momel(X, (i[3], i[4])) a3 -= momel(X, (i[1],i[6]))*momel(X, (i[2],i[5]))*momel(X, (i[3], i[4])) a += a1+a2-2*a3 end a end """ naivecumulant(data::Matrix, m::Int) Returns Array{Float, m} the m'th cumulant tensor ```jldoctest julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> naivecumulant(M, 3) 2×2×2 Array{Float64,3}: [:, :, 1] = 0.0 0.0 0.0 0.0 [:, :, 2] = 0.0 0.0 0.0 0.0 ``` """ function naivecumulant(X::Matrix{T}, m::Int = 4) where T<: AbstractFloat m < 7 || throw(AssertionError("naive implementation of $m cumulant not supported")) if m == 1 return naivemoment(X,m) end X = X .- mean(X, dims=1) ret = naivemoment(X,m) if m in [4,5,6] n = size(X, 2) for i = 1:(n^m) ind = Tuple(CartesianIndices((fill(n, m)...,))[i]) @inbounds ret[ind...] += mixel(X, ind) end end return ret end
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
5770
using Test using SymmetricTensors using Cumulants using Distributions using Combinatorics using Random using Distributed import Base: rand import Cumulants: indpart, momentblock, blockel, accesscum, outprodblocks, IndexPart, outerprodcum, usebl, momel, mixel import SymmetricTensors: pyramidindices include("testfunctions/pyramidcumulants.jl") include("testfunctions/mom2cum.jl") include("testfunctions/leeuw_cumulants_no_nested_func.jl") Random.seed!(42) x = randn(10,4); d = MvLogNormal(x'*x) data = Array(rand(d, 50)') @testset "Helper functions" begin @testset "moment helpers" begin M = [1. 2. 5. 6. ; 3. 4. 7. 8.] @test blockel(M, (1, 1), (1, 1), 2) == 5.0 @test blockel(M, (1, 1), (2, 2), 2) == 37.0 @test usebl((1, 1, 3), 5, 2, 3) == (2, 2, 1) @test momentblock(M, (1, 1), (2, 2), 2) == [[5.0 7.0]; [7.0 10.0]] end end @testset "Moment" begin M = [-0.88626 0.279571; -0.704774 0.131896] @testset "naivemoment" begin @test isapprox((naivemoment(M, 3))[:, :, 1], [-0.523092 0.142552; 0.142552 -0.0407653], atol=1.0e-5) @test isapprox((naivemoment(M, 3))[:, :, 2], [0.142552 -0.0407653; -0.0407653 0.0120729], atol=1.0e-5) end @testset "pyramidmoment" begin @test isapprox((pyramidmoment(M, 3))[:, :, 1], [-0.523092 0.142552; 0.142552 -0.0407653], atol=1.0e-5) @test isapprox((pyramidmoment(M, 3))[:, :, 2], [0.142552 -0.0407653; -0.0407653 0.0120729], atol=1.0e-5) end @testset "2" begin @test Array(moment(data, 2)) ≈ naivemoment(data, 2) end @testset "3" begin @test Array(moment(data, 3)) ≈ naivemoment(data, 3) end @testset "4" begin @test Array(moment(data, 4)) ≈ naivemoment(data, 4) @test Array(moment(data, 4, 3)) ≈ naivemoment(data, 4) end end @testset "Exceptions" begin @testset "Size of blocks" begin @test_throws Exception (DimensionMismatch, moment(data, 4, 25)) @test_throws Exception (DimensionMismatch, cumulants(data, 3, 25)) end end @testset "Cumulant helper functions" begin indexpart = indpart(4,2) @testset "indpart" begin @test indexpart[1].part == [[1, 2], [3, 4]] @test indexpart[2].part == [[1, 3], [2, 4]] @test indexpart[3].part == [[1, 4], [2, 3]] end @testset "operation on blocks" begin c2 = SymmetricTensor([1.0 2.0 3.0; 2.0 4.0 6.0; 3.0 6.0 5.0]) blocks = accesscum((1,1,1,1), indexpart[1], c2,c2) @test blocks == [[1.0 2.0; 2.0 4.0], [1.0 2.0; 2.0 4.0]] @test accesscum((1,1,1,2), indexpart[1], c2,c2) == [[1.0 2.0; 2.0 4.0], [3.0 0.0; 6.0 0.0]] @test accesscum((1,1,1,2), indexpart[3], c2,c2) == [[3.0 0.0; 6.0 0.0], [1.0 2.0; 2.0 4.0]] block = outprodblocks(indexpart[1], blocks) @test block[:, :, 1, 1] == [1.0 2.0; 2.0 4.0] @test block[:, :, 1, 2] == [2.0 4.0; 4.0 8.0] @test vec((outerprodcum(4, 2, c2, c2).frame[1, 1, 1, 1])[1, 1, :, :]) == [3.0, 6.0, 6.0, 12.0] end end gaus_dat = [[-0.88626 0.279571]; [-0.704774 0.131896]] @testset "Cumulants vs naive implementation" begin @testset "Test naive implentation" begin @test naivecumulant(gaus_dat, 3) ≈ zeros(Float64, 2, 2, 2) end cn = [naivecumulant(data, i) for i = 1:6] @testset "Square blocks" begin c1, c2, c3, c4, c5, c6 = cumulants(data, 6, 2) @test Array(c1) ≈ cn[1] @test Array(c2) ≈ cn[2] @test Array(c3) ≈ cn[3] @test Array(c4) ≈ cn[4] @test Array(c5) ≈ cn[5] @test Array(c6) ≈ cn[6] end @testset "Non-square blocks" begin c1, c2, c3, c4, c5, c6 = cumulants(data, 6, 3) @test Array(c1) ≈ cn[1] @test Array(c2) ≈ cn[2] @test Array(c3) ≈ cn[3] @test Array(c4) ≈ cn[4] @test Array(c5) ≈ cn[5] @test Array(c6) ≈ cn[6] end end @testset "test pyramid implementation" begin cn1, cn2, cn3, cn4, cn5, cn6, cn7, cn8 = pyramidcumulants(gaus_dat, 8) @test isapprox(cn1, naivecumulant(gaus_dat, 1), atol=1.0e-6) @test cn2 ≈ naivecumulant(gaus_dat, 2) @test cn3 ≈ zeros(Float64, 2, 2, 2) @test isapprox(cn4, zeros(Float64, 2, 2, 2, 2), atol=0.001) @test cn5 ≈ zeros(Float64, 2, 2, 2, 2, 2) @test isapprox(cn6, zeros(Float64, 2, 2, 2, 2, 2, 2), atol=0.0001) @test cn7 ≈ zeros(Float64, 2, 2, 2, 2, 2, 2, 2) @test isapprox(cn8, zeros(Float64, 2, 2, 2, 2, 2, 2, 2, 2), atol=1.0e-5) end @testset "Tests cumulants vs implementation from raw moments" begin c1, c2, c3, c4, c5, c6 = cumulants(data, 6, 2) cm1, cm2, cm3, cm4, cm5, cm6 = mom2cums(data, 6) @test cm2 ≈ Array(c2) @test cm3 ≈ Array(c3) @test cm4 ≈ Array(c4) @test cm5 ≈ Array(c5) @test cm6 ≈ Array(c6) llc = first_four_cumulants(data) @test llc[:c2] ≈ Array(c2) @test llc[:c3] ≈ Array(c3) @test llc[:c4] ≈ Array(c4) end cn1, cn2, cn3, cn4, cn5, cn6, cn7, cn8 = pyramidcumulants(data[:, 1:2], 8) @testset "Cumulants vs pyramid implementation square blocks" begin c1, c2, c3, c4, c5, c6, c7, c8 = cumulants(data[:, 1:2], 8, 2) @test Array((cumulants(gaus_dat, 3))[3]) ≈ zeros(Float64, 2, 2, 2) @test Array(c1) ≈ cn1 @test Array(c2) ≈ cn2 @test Array(c3) ≈ cn3 @test Array(c4) ≈ cn4 @test Array(c5) ≈ cn5 @test Array(c6) ≈ cn6 @test Array(c7) ≈ cn7 @test Array(c8) ≈ cn8 end addprocs(2) @everywhere using Cumulants @everywhere import Cumulants: momentnc @testset "test momentnc" begin x = ones(100, 2) m = momentnc(x ,2, 2) @test Array(m) == [1.0 1.0; 1.0 1.0] end @testset "Cumulants parallel implementation" begin c11, c12, c13, c14, c15, c16, c17, c18 = cumulants(data[:, 1:2], 8, 2) @test Array(c12) ≈ cn2 @test Array(c13) ≈ cn3 @test Array(c14) ≈ cn4 @test Array(c15) ≈ cn5 @test Array(c16) ≈ cn6 @test Array(c17) ≈ cn7 @test Array(c18) ≈ cn8 x = [1. 2. 3. 4. 5. 6. .7 .8 .9] @test Array(moment(x,1)) == [1., 2., 3., 4., 5., 6., .7, .8, .9] end
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
3061
using Combinatorics using DataStructures # implementation of J. De Leeuw Multivariate Cumulants in R (2012) function outer(a::Vector{T}, b::Vector{T}) where T<: AbstractFloat sa = size(a,1) sb = size(b,1) z = zeros(T, sa*sb) k = 1 for i = 1:sb for j = 1:sa @inbounds z[k] = a[j]*b[i] k += 1 end end return z end function setparts(n) ret = zeros(Int, n, length(partitions(collect(1:n)))) for (i, partition) in enumerate(partitions(collect(1:n))) group = 1 for p in partition for j in p ret[j,i] = group end group += 1 end end ret end function raw_moments_upto_p(x, p=4) n, m = size(x) if p==1 return vcat(1, mean(x, axis=2)) end y = zeros(eltype(x), (m+1)^p) for i in 1:n xi = vcat(1, x[i,:]) #z = kron([xi for _ in 1:p]...) z = xi for j in 2:p z = outer(xi, z) end y += z end reshape(y, repeat([m+1],p)...)./n end function cumulants_from_raw_moments(raw) dimr = size(raw) nvar::Int64 = dimr[1] cumu = zeros(eltype(raw), dimr...) nele = prod(dimr) ldim = length(dimr) spp = Array{Array{Int64,2}}(undef, ldim) qpp::Array{Int64} = Array{Int64}(undef, ldim) rpp = Array{Any}(undef, ldim) function one_cumulant_from_raw_moments(jnd, raw) jnd = [jnd[find(jnd.!=1)]...] - 1 nnd = length(jnd) ndr::Int64 = size(raw)[1] nrt = length(size(raw)) raw = rpp[nnd] nvar = ndr - 1 nraw = max(1, length(size(raw))) sp = spp[nraw] _, nbell = size(sp) sterm = 0.0 for i in 1:nbell ind = sp[:, i] und = unique(ind) term = qpp[length(und)] for j in und knd = jnd[find(ind.==j)] + 1 lnd = vcat(knd, repeat([1], nraw - length(knd))) term *= raw[lnd...] end sterm += term end return sterm end for i in 1:ldim spp[i] = setparts(i) qpp[i] = factorial(i) if mod(i,2)==1 qpp[i] = -qpp[i] end rpp[i] = raw[hcat([collect(1:nvar) for i in 1:i])...] end qpp = vcat(1, qpp) for i in 2:nele ind = ind2sub(dimr, i) cumu[i] = one_cumulant_from_raw_moments(ind, raw) end return cumu end function cumulants_upto_p(x, p = 4) return cumulants_from_raw_moments(raw_moments_upto_p(x, p)) end function first_four_cumulants(x) cumu = cumulants_upto_p(x) nsel = 2:size(cumu)[1] OrderedDict(:c1 => cumu[1, 1, 1, nsel], :c2 => cumu[1, 1, nsel, nsel], :c3 => cumu[1, nsel, nsel, nsel], :c4 => cumu[nsel, nsel, nsel, nsel] ) end
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
3273
using Combinatorics using DataStructures # implementation of J. De Leeuw Multivariate Cumulants in R (2012) function outer(a::Vector{T}, b::Vector{T}) where T<: AbstractFloat sa = size(a,1) sb = size(b,1) z = zeros(T, sa*sb) k = 1 for i = 1:sb for j = 1:sa @inbounds z[k] = a[j]*b[i] k += 1 end end return z end function setparts(n) ret = zeros(Int, n, length(partitions(collect(1:n)))) for (i, partition) in enumerate(partitions(collect(1:n))) group = 1 for p in partition for j in p ret[j,i] = group end group += 1 end end ret end function raw_moments_upto_p(x, p=4) n, m = size(x) if p==1 return vcat(1, mean(x, axis=2)) end y = zeros(eltype(x), (m+1)^p) for i in 1:n xi = vcat(1, x[i,:]) #z = kron([xi for _ in 1:p]...) z = xi for j in 2:p z = outer(xi, z) end y += z end reshape(y, repeat([m+1],p)...)./n end mutable struct CumulantsState spp::Array{Array{Int64,2}} qpp::Array{Int64} rpp::Array{Any} end function CumulantsState(ldim) spp = Array{Array{Int64,2}}(undef, ldim) qpp = Array{Int64}(undef, ldim) rpp = Array{Any}(undef, ldim) return CumulantsState(spp, qpp, rpp) end function one_cumulant_from_raw_moments(state::CumulantsState, jnd, raw) jnd = [jnd[findall(jnd.!=1)]...] .- 1 nnd = length(jnd) ndr::Int64 = size(raw)[1] nrt = length(size(raw)) raw = state.rpp[nnd] nvar = ndr - 1 nraw = max(1, length(size(raw))) sp = state.spp[nraw] _, nbell = size(sp) sterm = 0.0 for i in 1:nbell ind = sp[:, i] und = unique(ind) term = state.qpp[length(und)] for j in und knd = jnd[findall(ind.==j)] .+ 1 lnd = vcat(knd, repeat([1], nraw - length(knd))) term *= raw[lnd...] end sterm += term end return sterm end function cumulants_from_raw_moments(raw::Array{T, N}) where {T<: AbstractFloat, N} dimr = size(raw) nvar::Int64 = dimr[1] cumu = zeros(eltype(raw), dimr...) nele = prod(dimr) ldim = length(dimr) state = CumulantsState(ldim) for i in 1:ldim state.spp[i] = setparts(i) state.qpp[i] = factorial(i) if mod(i,2)==1 state.qpp[i] = -state.qpp[i] end inde = hcat([collect(1:nvar) for k in 1:i]) state.rpp[i] = raw[inde..., fill(1, N-length(inde))...,] end state.qpp = vcat(1, state.qpp) for i in 2:nele ind = Tuple(CartesianIndices(dimr)[i]) cumu[i] = one_cumulant_from_raw_moments(state, ind, raw) end return cumu end function cumulants_upto_p(x, p = 4) return cumulants_from_raw_moments(raw_moments_upto_p(x, p)) end function first_four_cumulants(x) cumu = cumulants_upto_p(x) nsel = 2:size(cumu)[1] OrderedDict(:c1 => cumu[1, 1, 1, nsel], :c2 => cumu[1, 1, nsel, nsel], :c3 => cumu[1, nsel, nsel, nsel], :c4 => cumu[nsel, nsel, nsel, nsel] ) end
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
3416
""" outer!(z::Vector{Float}, a::Vector{Float}, b::Vector{Float}) Return z - Vector{Float} , vectorsed outer/kroneker product o vectors a and b Auxiliary function for rawmoment """ function outer!(z::Vector{T}, a::Vector{T}, b::Vector{T}) where T<: AbstractFloat sa = size(a,1) sb = size(b,1) m = 1 for i = 1:sb for j = 1:sa @inbounds z[m] = a[j]*b[i] m += 1 end end end """ updvec!(A::Vector{Float}, B::Vector{Float}) Returns updated Vector{Float} A, by adding elementwisely Vector{Float} B Auxiliary function for rawmoment """ function updvec!(A::Vector{T}, B::Vector{T}) where T<: AbstractFloat n = size(A, 1) for i=1:n @inbounds A[i] += B[i] end return A end """ rawmoment(X::Matrix{T}, m::Int = 4) Simmilar to raw_moments_upto_p in R, does not expoloit tensor's symmetry pyramid structures and blocks Returns Array{Float, m}, the m'th moment's tensor """ function rawmoment(X::Matrix{T}, m::Int = 4) where T<: AbstractFloat t,n = size(X) if m == 1 return mean(X, dims=1)[1,:] else z = [map(i -> zeros(T, n^i), 1:m)...] y = zeros(T, n^m) for i in 1:t xi = X[i, :] z[1] = xi for j in 2:m outer!(z[j], xi, z[j-1]) end updvec!(y, z[m]) end end reshape(y/t, fill(n, m)...) end """ raw_moments_upto_k(X::Matrix, k::Int = 4) Returns [Array{Float, 1}, ..., Array{Float, k}] noncentral moment tensors of order 1, ..., k """ raw_moments_upto_k(X::Matrix{T}, k::Int = 4) where T<: AbstractFloat = [rawmoment(X, i) for i in 1:k] """ cumulants_from_moments(raw::Vector{Array{Float, i}, m = 1:k}) Returns [Array{Float, 1}, ..., Array{Float, k}] cumulant tensors of order 1, ..., k Uses relation between cumulants and multivariate moments from e.g. c_{ijkl} = m_{ijkl} - m_{ijk} m_{l} [4] - m_{ij} m_{kl} [3] + 2 m_{ij} m_{k} m_{l} -6 m_{i} m_{j} m_{k} m_{l} """ function cumulants_from_moments(raw::Vector{Array{T}}) where T<: AbstractFloat k = length(raw) cumarr = Array{Array{Float64}}(undef, k) for j in 1:k dimr = size(raw[j]) cumu = zeros(Float64, dimr) ldim = length(dimr) spp = collect(partitions(1:ldim)) qpp = [(-1)^i*factorial(i) for i in 0:(ldim-1)] sppl = [map(length, spp[i]) for i in 1:length(spp)] for i in 1:prod(dimr) @inbounds ind = Tuple(CartesianIndices(dimr)[i]) @inbounds cumu[ind...] = onecumulant(ind, raw, spp, sppl, qpp) end cumarr[j] = cumu end cumarr end """ onecumulant(ind::Tuple, raw::Vector{Array}, spp::Vector, sppl::Vector{Vector}, dpp::Vector) raw - vector of moment's tensors, spp - vector of partitions, sppl - vector of sizes of partitions dpp - vector of a factor for each product of moments (a factorial factor). Returns Array{Float, n} the n'th cumulant tensor """ function onecumulant(ind::Tuple, raw::Vector{Array{T}}, spp::Vector, sppl::Vector{Vector{Int}}, dpp::Vector{Int}) where T<: AbstractFloat ret = zero(T) for i in 1:length(spp) part = spp[i] beln = length(part) k = sppl[i] temp = one(T) for r in 1:beln temp *= raw[k[r]][ind[part[r]]...] end ret += dpp[beln]*temp end ret end """ cumulatsfrommoments(x::Matrix{Float}, k::Int) Returns a vector of 1,2, .., k dims Arrays{Float} of cumulant tensors """ mom2cums(x::Matrix{T}, k::Int) where T<: AbstractFloat = cumulants_from_moments(raw_moments_upto_k(x, k))
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
code
3146
#--- seminaive formula uses partitions and reccurence, but does not use blocks """ part(n::Int) Returns Vector{Vector{Vector}} that includes all partitions of set [1, 2, ..., m] into subests of size > 1 and < m ```jldoctest julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> part(4) 3-element Array{Array{Array{Int64,1},1},1}: Array{Int64,1}[[1,2],[3,4]] Array{Int64,1}[[1,3],[2,4]] Array{Int64,1}[[1,4],[2,3]] ``` """ function part(m::Int) parts = Vector{Vector{Int}}[] for part in partitions(1:m) subsetslen = map(length, part) if !((1 in subsetslen) | (m in subsetslen)) @inbounds push!(parts, part) end end parts end """ pyramidmoment(data::Matrix, m::Int) Returns Array{Float, m}, the m'th moment tensor ```jldoctest julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> pyramidmoment(M, 3) 2×2×2 Array{Float64,3}: [:, :, 1] = -0.523092 0.142552 0.142552 -0.0407653 [:, :, 2] = 0.142552 -0.0407653 -0.0407653 0.0120729 ``` """ function pyramidmoment(data::Matrix{T}, m::Int) where T<: AbstractFloat n = size(data,2) ret = zeros(T, fill(n, m)...) for ind in pyramidindices(m, n) @inbounds temp = momel(data, ind) for per in collect(permutations([ind...])) @inbounds ret[per...] = temp end end ret end """ mixedel(cum::Vector{Array{T}}, mulind::Tuple, parts::Vector{Vector{Vector{Int}}}) Returns Float, element of the sum of products of lower cumulants at given multi-index and set of its partitions """ function mixedel(cum::Vector{Array{T}}, mulind::Tuple, parts::Vector{Vector{Vector{Int}}}) where T<: AbstractFloat sum = 0. for k = 1:length(parts) prod = 1. for el in parts[k] @inbounds prod*= cum[size(el,1)][mulind[el]...] end sum += prod end sum end """ mixedarr(cumulants::Vector{Array}, m::Int) Returns Array{Float, m}, the mixed array (sum of products of lower cumulants) """ function mixedarr(cumulants::Vector{Array{T}}, m::Int) where T<: AbstractFloat n = size(cumulants[1], 1) sumofprod = zeros(fill(n, m)...) parts = part(m) for ind in pyramidindices(m, n) pyramid = mixedel(cumulants, ind, parts) for per in collect(permutations([ind...])) @inbounds sumofprod[per...] = pyramid end end sumofprod end """ pyramidcumulants(X::Matrix{Float}, m::Int) Returns [Array{Float, 2}, ..., Array{Float, m}], vector co cumulants tensors of order 2, .., m ``` julia> M = [[-0.88626 0.279571];[-0.704774 0.131896]]; julia> pyramidcumulants(M, 3)[2] 2×2×2 Array{Float64,3}: [:, :, 1] = 0.0 0.0 0.0 0.0 [:, :, 2] = 0.0 0.0 0.0 0.0 ``` """ function pyramidcumulants(X::Matrix{T}, m::Int = 4) where T<: AbstractFloat cumulants = Array{T}[] push!(cumulants, pyramidmoment(X, 1)) X = X .- mean(X, dims=1) for i in 2:m if i < 4 push!(cumulants, pyramidmoment(X, i)) else cumulant = pyramidmoment(X, i) - mixedarr(cumulants, i) push!(cumulants, cumulant) end end cumulants end
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
1.0.6
ecdae283cbdb5518bf3fdb61ff99eb973fab580b
docs
8876
# Cumulants.jl [![Coverage Status](https://coveralls.io/repos/github/iitis/Cumulants.jl/badge.svg?branch=master)](https://coveralls.io/github/iitis/Cumulants.jl?branch=master) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3446199.svg)](https://doi.org/10.5281/zenodo.3446199) Calculates cumulant tensors of any order for multivariate data. Functions return tensor or array of tensors in `SymmetricTensors` type. Requires [SymmetricTensors.jl](https://github.com/ZKSI/SymmetricTensors.jl). To convert to array, run: ```julia julia> Array(data::SymmetricTensors{T, N}) ``` As of 01/01/2017 [kdomino](https://github.com/kdomino) is the lead maintainer of this package. ## Installation Within Julia, run ```julia pkg> add Cumulants ``` to install the files. Julia 1.0 or later is required. ## Functions ### Moment ```julia julia> moment(data::Matrix{T}, m::Int, b::Int = 2) where T<: AbstractFloat ``` Returns a `SymmetricTensor{T, m}` of the moment of order `m` of multivariate data represented by a `t` by `n` matrix, i.e. data with `n` marginal variables and `t` realisations. The argument `b` with defalt value `2`, is an optional `Int` that determines the size of the blocks in `SymmetricTensors` type. ```julia julia> data = reshape(collect(1.:15.),(5,3)) 5×3 Array{Float64,2}: 1.0 6.0 11.0 2.0 7.0 12.0 3.0 8.0 13.0 4.0 9.0 14.0 5.0 10.0 15.0 ``` ```julia julia> m = moment(data, 3) SymmetricTensor{Float64,3}(Union{Nothing, Array{Float64,3}}[[45.0 100.0; 100.0 230.0] [100.0 230.0; 230.0 560.0] nothing; nothing nothing] Union{Nothing, Array{Float64,3}}[[155.0 360.0; 360.0 890.0] [565.0; 1420.0]; nothing [2275.0]], 2, 2, 3, false) ``` To convert to array use: ```julia julia> Array(m) 3×3×3 Array{Float64,3}: [:, :, 1] = 45.0 100.0 155.0 100.0 230.0 360.0 155.0 360.0 565.0 [:, :, 2] = 100.0 230.0 360.0 230.0 560.0 890.0 360.0 890.0 1420.0 [:, :, 3] = 155.0 360.0 565.0 360.0 890.0 1420.0 565.0 1420.0 2275.0 ``` ### Cumulants ```julia julia> cumulants(data::Matrix{T}, m::Int = 4, b::Int = 2) where T<: AbstractFloat ``` Returns a vector of `SymmetricTensor{T, i}` `i = 1,2,3,...,m` of cumulants of order `1,2,3,...,m`. Cumulants are calculated for multivariate data represented by matrix of size `t` by `n`, i.e. data with `n` marginal variables and `t` realisations. ```julia julia> c = cumulants(data, 3); julia> c[2] SymmetricTensor{Float64,2}(Union{Nothing, Array{Float64,2}}[[2.0 2.0; 2.0 2.0] [2.0; 2.0]; nothing [2.0]], 2, 2, 3, false) julia> c[3] SymmetricTensor{Float64,3}(Union{Nothing, Array{Float64,3}}[[0.0 0.0; 0.0 0.0] [0.0 0.0; 0.0 0.0] nothing; nothing nothing] Union{Nothing, Array{Float64,3}}[[0.0 0.0; 0.0 0.0] [0.0; 0.0]; nothing [0.0]], 2, 2, 3, false) ``` To convert to array: ```julia julia> Array(c[2]) 3×3 Array{Float64,2}: 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 julia> Array(c[3]) 3×3×3 Array{Float64,3}: [:, :, 1] = 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 [:, :, 2] = 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 [:, :, 3] = 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ``` #### Block size The argument `b` with default value `2`, is an optional `Int` that determines a size of blocks in `SymmetricTensors` type. This block size `b` is the parameter that affect the algorithm performance, for most cases the performance is optimal for `b = 2, 3`. The block size must fulfil `0 < b ≦ size(data, 2)` otherwise error will be raised. For the performance analysis for various bolck sizes see `Section 5.2.1` in Krzysztof Domino, Piotr Gawron, Łukasz Pawela, *Efficient Computation of Higher-Order Cumulant Tensors*, SIAM J. Sci. Comput. 40, A1590 (2018) [![DOI](10.1137/17M1149365)](https://doi.org/10.1137/17M1149365), https://arxiv.org/abs/1701.05420. For benchmarking one can also use `benchmarks/comptimeblocks.jl` The purpose of this package is to compute moments and cumulants for multivariate data. It works for univariate data `X` structured in the form of matrix with `size(X, 2) = 1` if taking `b=1`. Such univariate application is not efficient however. ```julia julia> X = [1., 2., 3., 4.]; julia> X = reshape(X, (4,1)); julia> c = cumulants(X,4,1); julia> map(x -> Array(x)[1], c) 4-element Array{Float64,1}: 2.5 1.25 0.0 -2.125 ``` We do not suply exact univariate fisher's k-statistics. #### Parallel computation Parallel computation is efficient for large number of data realisations, e.g. `t = 1000000`. For parallel computation just run ```julia julia> addprocs(n) julia> @everywhere using Cumulants ``` Naive algorithms of moment and cumulant tensors calculations are also available. ```julia julia> naivemoment(data::Matrix{T}, m::Int = 4) where T<: AbstractFloat ``` Returns array{T, m} of the m'th moment of data. calculated using a naive algorithm. ```julia julia> naivemoment(data, 3) 3×3×3 Array{Float64,3}: [:, :, 1] = 45.0 100.0 155.0 100.0 230.0 360.0 155.0 360.0 565.0 [:, :, 2] = 100.0 230.0 360.0 230.0 560.0 890.0 360.0 890.0 1420.0 [:, :, 3] = 155.0 360.0 565.0 360.0 890.0 1420.0 565.0 1420.0 2275.0 ``` ```julia julia> naivecumulant(data::Matrix{T}, m::Int = 4) where T<: AbstractFloat ``` Returns `Array{T, m}` of the `m`'th cumulant of data, calculated using a naive algorithm. Works for `1 <= m < 7`, for `m >= 7` throws exception. ```julia julia> naivecumulant(data, 2) 3×3 Array{Float64,2}: 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 ``` ```julia julia> naivecumulant(data, 3) 3×3×3 Array{Float64,3}: [:, :, 1] = 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 [:, :, 2] = 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 [:, :, 3] = 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ``` # Performance analysis, folder `benchmarks` To analyse the computational time of cumulants vs naivecumulants and moment vs naivemoment, we supply the executable script `comptimes.jl`. This script returns to a .jld file computational times, given following parameters: * `-m (Int)`: cumulant's order, by default `m = 4`, * `-n (vararg Int)`: numbers of marginal variables, by default `m = 20 24 28`, * `-t (vararg Int)`: number of realisations of random variable, by defalut `t = 10000`. Be careful while using `n`>`4` and large `m`, where naive algorithms might need a large computational time and memory usage. Naive algorithms does not use the block structures, hence they computes and stores a whole cumulant tensor regardless its symmetry. All comparisons performed by this script use one core. To analyse the computational time of cumulants for different block sizes `1 =< b =< Int(sqrt(n))`, we supply the executable script `comptimeblocks.jl`. This script returns to a .jld file computational times, given following parameters: * `-m (Int)`: cumulant's order, by default `m = 4`, * `-n (Int)`: numbers of marginal variables, by default `m = 48`, * `-t (vararg Int)`: number of realisations of random variable, by default `t = 10000 20000`. Computational times and parameters are saved in the .jld file in /res directory. All comparisons performed by this script use one core. To analyse the computational time of moment on different numbers of processes, we supply the executable script `comptimeprocs.jl`. This script returns to a .jld file computational times, given following parameters: * `-m (Int)`: moment's order, by default `m = 4`, * `-n (Int)`: numbers of marginal variables, by default `m = 50`, * `-t (Int)`: number of realisations of random variable, by default `t = 100000`, * `-p (Int)`: maximal number of processes, by default `p = 4`, * `-b (Int)`: blocks size, by default `b = 2`. All result files are saved in /res directory. To plot a graph run /res/plotcomptimes.jl followed by a `*.jld` file name For the computational example on data use the following. The script `gandata.jl` generates `t = 150000000` realisations of `n = 4` dimensional data form the `t`-multivariate distribution with `ν = 14` degrees of freedom, and theoretical super-diagonal elements of those cumulants. Results are saved in `data/datafortests.jld` The script `testondata.jl` computes cumulant tensors of order `m = 1 - 6` for `data/datafortests.jld`, results are saved in `data/cumulants.jld`. To read `cumulants.jld` please run ```julia julia> using JLD julia> using SymmetricTensors julia> load("cumulants.jld") ``` To plot super-diagonal elements of those cumulants and their theoretical values from t-student distribution pleas run `plotsuperdiag.jl` # Citing this work Krzysztof Domino, Piotr Gawron, Łukasz Pawela, *Efficient Computation of Higher-Order Cumulant Tensors*, SIAM J. Sci. Comput. 40, A1590 (2018) [![DOI](10.1137/17M1149365)](https://doi.org/10.1137/17M1149365), https://arxiv.org/abs/1701.05420 This project was partially financed by the National Science Centre, Poland – project number 2014/15/B/ST6/05204.
Cumulants
https://github.com/iitis/Cumulants.jl.git
[ "MIT" ]
0.2.0
38e36bad296e56f1ddf022029dd30129fcc5aff2
code
328
module QuadratureOnImplicitRegions using FastGaussQuadrature,LinearAlgebra,ForwardDiff import FiniteDiff.finite_difference_gradient! #non-allocating gradient export algoim_nodes_weights # export algoim_quad #nneds work include("algoim.jl") # include("integrate_f.jl") #Needs some work include("algoim_functions.jl") end
QuadratureOnImplicitRegions
https://github.com/Hmegh/QuadratureOnImplicitRegions.jl.git
[ "MIT" ]
0.2.0
38e36bad296e56f1ddf022029dd30129fcc5aff2
code
4702
function algoim_nodes_weights(ψ::F,sgn::N,a::Vector{T},b::Vector{S},q::I) where {F,N,T,I,S} x_ref,w_ref=gausslegendre(q) U=Float64.(vcat(a',b')) return algoim_nodes_weights([ψ], [sgn],U,x_ref,w_ref) end function algoim_nodes_weights(ψ_list,s_list,U::Matrix{T},x_ref,w_ref,recursion_depth=1) where T d=size(U,2); if d==1 x,w=d1_case(ψ_list,s_list,U,x_ref,w_ref) return x,w end xc=(U[1,:] + U[2,:])/2 #midpoint n_samples=100; #total number of samples nnsamples=Int(round(n_samples^(1/d))) # number of samples per dimension Samples=linsamples_creator(U,nnsamples) for i=length(s_list):-1:1 ψ=ψ_list[i] ψ_xc=ψ(xc) min_ψ=minimum(ψ(x) for x in eachcol(Samples)) max_ψ=maximum(ψ(x) for x in eachcol(Samples)) #= Here, I deviated a bit from the paper, to make the case ψ(x)=norm(x)^2 works on [0,ε]^d =# if min_ψ*max_ψ≥0 if s_list[i]*ψ(xc)≥0 s_list=deleteat!(copy(s_list),i) ψ_list=deleteat!(copy(ψ_list),i) else return Matrix{T}(undef,d,0), Float64[] end end end if isempty(s_list) x,w=tensor_GL_rule(U,x_ref,w_ref) return x,w; end new_ψ_list=Vector{Function}(undef,0) new_s_list=Vector{Float64}(undef,0) #the direction of the most change in ψ_1 ψ_1=ψ_list[1]; k=argmax(abs.(ForwardDiff.gradient(ψ_1,xc))) xkL=U[1,k]; xkU=U[2,k]; g=zeros(d) gtemp=zeros(d) δ=fill(-Inf,d) for i in eachindex(s_list) ψ=ψ_list[i] # δ[:] .=fill(-Inf,d) fill!(δ,-Inf) # g[:] .=ForwardDiff.gradient(ψ,xc) finite_difference_gradient!(g,ψ,xc) for i in axes(Samples,2) # gtemp[:] .=ForwardDiff.gradient(ψ,Samples[:,i]) finite_difference_gradient!(gtemp,ψ, @view Samples[:,i]) for kk=1:d δ[kk]=max(δ[kk],abs(gtemp[kk]-g[kk])) end end if abs(g[k])>δ[k]&& norm(g + δ)^2/(g[k]-δ[k])^2<20 ψ_L=(x->ψ(insert_kth(x,k,xkL))) ψ_U=(x->ψ(insert_kth(x,k,xkU))) si_L=sgn(g[k],s_list[i],-1); si_U=sgn(g[k],s_list[i],1); # new_ψ_list=vcat(new_ψ_list,ψ_L,ψ_U); # new_s_list=vcat(new_s_list,si_L,si_U) push!(new_ψ_list,ψ_L,ψ_U) push!(new_s_list,si_L,si_U) else #subdivide the domain (unless it is too small) Volume=prod(U[2,:] - U[1,:]); if recursion_depth>=16 flag=true for i in eachindex(s_list) if s_list[i]*ψ_list[i](xc)<= 0 flag=false end end printstyled("Warning: lower order method used in $U\n";color=:red) if flag return xc, Volume else return Vector{Float64}[],Float64[]; end end kk=argmax(U[2,:]-U[1,:]) U1=copy(U);U2=copy(U); U1[2,kk]=(U[1,kk]+U[2,kk])/2.0; U2[1,kk]=(U[1,kk]+U[2,kk])/2.0; x1,w1=algoim_nodes_weights(ψ_list,s_list,U1,x_ref,w_ref,recursion_depth+1); x2,w2=algoim_nodes_weights(ψ_list,s_list,U2,x_ref,w_ref,recursion_depth+1); x= hcat(x1,x2) w=vcat(w1,w2) return x,w end end U_tilde=hcat(U[:,1:k-1],U[:,k+1:end]) x_tilde,w_tilde=algoim_nodes_weights(new_ψ_list,new_s_list,U_tilde,x_ref,w_ref) #(d-1)xN matrix QQ=Vector{T}(undef,d-1) #This part is the one using 90% of the allocations #estimate the number of nodes cnt=0 for ii in axes(x_tilde,2) QQ[:] .=@view x_tilde[:,ii] #(d-1) vector # PP=w_tilde[ii] ψ_list_tilde=[t->ψ(insert_kth(QQ,k,t)) for ψ in ψ_list] cnt+=d1_count_subintervals(ψ_list_tilde,s_list,[xkL;xkU]) end x=Matrix{T}(undef,d,cnt*length(x_ref)) w=Vector{T}(undef,cnt*length(x_ref)) j=1 for ii in axes(x_tilde,2) QQ[:] .=@view x_tilde[:,ii] PP=w_tilde[ii] ψ_list_tilde=[t->ψ(insert_kth(QQ,k,t)) for ψ in ψ_list] x_slice,w_slice=d1_case(ψ_list_tilde,s_list,[xkL;xkU],x_ref,w_ref) n=length(w_slice) if isempty(w_slice) continue end w[j:j+n-1] .= PP*w_slice # x[:,j:j+n] = [repeat(QQ[1:k-1],1,n);x_slice;repeat(QQ[k:end],1,n)] x[1:k-1,j:j+n-1] = repeat(QQ[1:k-1],1,n) x[k,j:j+n-1] = x_slice x[k+1:end,j:j+n-1] = repeat(QQ[k:end],1,n) j+=n end return x,w end
QuadratureOnImplicitRegions
https://github.com/Hmegh/QuadratureOnImplicitRegions.jl.git
[ "MIT" ]
0.2.0
38e36bad296e56f1ddf022029dd30129fcc5aff2
code
5749
sgn(m,s,σ)= ( m==σ*s ? σ*m : 0.0) find_root(ψ::F,a::T,b::T) where {F,T<:Integer} = find_root(ψ,Float64(a),Float64(b)) find_roots(ψ::F,a::T,b::T) where {F,T<:Integer} = find_roots(ψ,Float64(a),Float64(b)) find_roots(ψ_list::Vector{F},a::T,b::T) where {F,T<:Integer} = find_roots(ψ_list,Float64(a),Float64(b)) """ find_root(ψ::F,a::T,b::T) Finds a root of a function ψ in the open interval `(a,b)` """ function find_root(ψ::F,a::T,b::T) where {F,T<:AbstractFloat} if ψ(a)*ψ(b)≥0 error("Find_root failed: Choose a smaller interval") end c=b cnext=(a+b)/2 while abs(c-cnext)>4eps(T) c=cnext cnext=cnext-ψ(cnext)/ForwardDiff.derivative(ψ,cnext) end return c end """ find_roots(ψ::F,a::T,b::T) where {F,T} Returns multiple roots of ψ in the open interval `[a,b]` """ function find_roots(ψ::F,a::T,b::T) where {F,T} n=10 #split the interval [a,b] into n sub-intervals h=(b-a)/n Z=Vector{Float64}(undef,0) for i=0:n-1 if ψ(a+i*h)*ψ(a+(i+1)*h)<0 z=find_root(ψ,a+i*h,a+(i+1)*h) push!(Z,z) end end for i=1:n if ψ(a+i*h)==0 push!(Z,a+i*h) end end sort!(Z) #remove duplicates for i=length(Z):-1:2 if abs(Z[i]-Z[i-1])≤4eps(T) deleteat!(Z,i) end end return Z end """ find_roots(ψ_list::Vector{F},a::T,b::T) where {F,T} Returns multiple roots of multiple functions ψ in the closed interval `[a,b]`, it includes the endpoints by default even if they are not roots. """ function find_roots(ψ_list::Vector{F},a::T,b::T) where {F,T} n=20 #split the interval [a,b] into n sub-intervals h=(b-a)/n Z=[a,b] for ψ in ψ_list zer=find_roots(ψ,a,b) append!(Z,zer) end sort!(Z) Z end """ shifted_gl(x_ref::Vector{T},w_ref::Vector{T},a::T,b::T) Shifts the Gauss-Legendre rule (x_ref,w_ref) from `(-1,1)` to the interval [a,b] """ function shifted_gl(x_ref::Vector{T},w_ref::Vector{T},a::T,b::T) where T x,w=similar(x_ref),similar(w_ref) for i in eachindex(x) x[i]=(a+b)/2+(b-a)/2*x_ref[i] end for i in eachindex(w) w[i]=(b-a)/2*w_ref[i] end return x,w end """ shifted_gl!(x_ref::Vector{T},w_ref::Vector{T},a::T,b::T,x::Vector{T},w::Vector{T}) Shifts the Gauss-Legendre rule (x_ref,w_ref) from `(-1,1)` to the interval [a,b] and stores them in x,w. """ function shifted_gl!(x_ref::Vector{T},w_ref::Vector{T},a::T,b::T,x::Vector{T},w::Vector{T}) where T for i in eachindex(x) x[i]=(a+b)/2+(b-a)/2*x_ref[i] end for i in eachindex(w) w[i]=(b-a)/2*w_ref[i] end return end """ d1_count_subintervals(ψ_list,s_list,domain) Counts how many sub-intervals of domain satisfiy s_iψ_i≥0 """ function d1_count_subintervals(ψ_list,s_list,domain) Z=find_roots(ψ_list,domain[1],domain[2]) cnt=0 n=length(Z) for i=1:n-1 a=Z[i];b=Z[i+1];c=(a+b)/2 flag=true for i in eachindex(ψ_list) if s_list[i]*ψ_list[i](c)<0 flag=false;break; end end if flag cnt+=1 end end return cnt end """ d1_case(ψ_list,s_list,domain,x_ref,w_ref) Returns a quadrature rule on the subset where s_i*ψ_i<0 (see the paper). """ function d1_case(ψ_list,s_list,domain,x_ref,w_ref) Z=find_roots(ψ_list,domain[1],domain[2]) x=Vector{eltype(x_ref)}(undef,0) w=Vector{eltype(w_ref)}(undef,0) xloc=similar(x_ref) wloc=similar(w_ref) n=length(Z) for i=1:n-1 a=Z[i];b=Z[i+1];c=(a+b)/2 flag=true for i in eachindex(ψ_list) if s_list[i]*ψ_list[i](c)<0 flag=false;break; end end if flag shifted_gl!(x_ref,w_ref,a,b,xloc,wloc) append!(x,xloc) append!(w,wloc) end end return reshape(x,1,:),w end """ tensor_GL_rule(U::Matrix{T},x_ref::Vector{T},w_ref::Vector{T}) Returns a matrix x and a vector w (multidimensional quadrature) Credit for the idea: https://discourse.julialang.org/t/about-storing-the-results-of-iterators-product-into-an-array-efficiently/115504 """ function tensor_GL_rule(U::Matrix{T},x_ref::Vector{T},w_ref::Vector{T}) where T d=size(U,2) n=size(x_ref,1) X=[(U[1,i]+U[2,i])/2 .+ x_ref .* (U[2,i]-U[1,i])/2 for i=1:d] W=[ w_ref/2 .* (U[2,i]-U[1,i]) for i=1:d] x_tuples=collect(Iterators.product(X...)) x=Matrix(reshape(reinterpret(T, x_tuples), d, n^d)) w=[prod(A) for A in collect(Iterators.product(W...))[:]] return x,w end """ linsamples_creator(U::Matrix{T},n::I) where {T,I} returns sample points in the cuboid U (as columns). """ function linsamples_creator(U::Matrix{T},n::I) where {T,I} d=size(U,2); #linspaces in each direction lins=[range(U[1,i],U[2,i],n) for i=1:d]; #Iterators.product returns the cartesian product as an object, # collect makes it a matrix and [:] makes it a vector of tuples. x_tuples= collect(Iterators.product(lins...)) return Matrix(reshape(reinterpret(T, x_tuples), d, n^d)) end # remove_kth(x::Vector,k::Integer)=vcat(x[1:k-1],x[k+1:end]); # remove_kth(x::Number,k::Integer)=Vector{typeof(x)}(undef,0); function remove_kth(x::V,k::I) where {I,V<:AbstractVector} return deleteat!(copy(x),k) end function remove_kth(x::T,k::I) where {I,T<:Number} return Vector{T}(undef,0) end function insert_kth(x::V,k::I,t::T) where {I,V<:AbstractVector,T<:Number} [@view x[1:k-1];t;@view x[k:end]] end function insert_kth(x::N,k::I,t::S) where {N<:Number,I,S<:Number} if k==1 return [t,x] elseif k==2 return [x,t] end end
QuadratureOnImplicitRegions
https://github.com/Hmegh/QuadratureOnImplicitRegions.jl.git
[ "MIT" ]
0.2.0
38e36bad296e56f1ddf022029dd30129fcc5aff2
code
5868
#instead of returning nodes and weights, we can integrate a function f directly. #this should be faster. """ int_f_1d(f,N,a,b) integrate f(x) on [a,b] using N quadrature points """ function int_f_1d(f,N,a,b) x,w=lgwtjl(N,a,b) return w'*f.(x) end # int_f_1d(x->x^3,4,0,1) ==1/4 # int_f_1d(x->sin(x),10,0,π) ==2 # int_f_1d(x->x^3,4,1,3) ==20 function d1_int_f(f,ψ_list,s_list,domain,q) #The one-dimensional case. s_list and psi_list # have the same length zer=findroots(ψ_list,domain); flag=1; s=0.0 for i=1:length(zer)-1 a=zer[i];b=zer[i+1];c=(a+b)/2; #check to see if s_i*psi_i(c)>0 for all i #I used count: if there is an instance where # psi_i(c)*s_i<0, then flag is 0. flag=count([s_list[i]*ψ_list[i](c)<0 for i=1:length(s_list)])==0; if flag #psi_i(c)s_i>0 for all i s+=int_f_1d(f,q,a,b) end end return s end # d1_int_f(x->x^3,[x->x-1.5],[-1],[0,2],10)≈ 1.5^4/4 function algoim_quad(f::Function,ψ::Function,sgn::Number,a,b,q::Integer) U=vcat(a',b') ∇ψ=x-> ForwardDiff.gradient(ψ,x) return algoim_quad(f,[ψ],[∇ψ],[sgn],U,q) end function algoim_quad(f,ψ_list::Vector,∇ψ_list::Vector,s_list::Vector,U,q::Integer,recursion_depth=1)::Float64 #integrate a function f d=size(U,2); if d==1 return d1_int_f(f,ψ_list,s_list,U,q); end xc=(U[1,:] + U[2,:])/2 n_samples=15625; n_samples=4096;#less samples: faster n_samples=729;#less samples: faster nnsamples=Int(round(n_samples^(1/d))); Samples=linsamples_creator(U,nnsamples) for i=length(s_list):-1:1 ψ=ψ_list[i]; ψ_xc=ψ(xc); ψ_x=ψ.(Samples) δ=maximum(abs.(ψ_x .- ψ_xc)); # println("ψ_xc =$ψ_xc ,δ = $δ") #pruning # if abs(ψ_xc)>=δ #does not prune certain cases such as norm(x)^2 on [0,1] if minimum(ψ_x)*maximum(ψ_x) >=0 if s_list[i]*ψ_xc>=0 #remove \psi_i s_list=vcat(s_list[1:i-1],s_list[i+1:end]); ψ_list=vcat(ψ_list[1:i-1],ψ_list[i+1:end]); ∇ψ_list=vcat(∇ψ_list[1:i-1],∇ψ_list[i+1:end]); else #nothing return 0.0; end end end if isempty(s_list) x,w=tensor_GL_rule(U,q); return w'*f.(x); end new_ψ_list=Vector{Function}(undef,0) new_∇ψ_list=Vector{Function}(undef,0) new_s_list=Vector{Float64}(undef,0) ψ_1=ψ_list[1]; ∇ψ_1=∇ψ_list[1]; #this does not strike me as the best method to choose k k=argmax(abs.(∇ψ_1(xc))) # println("dimension $(length(xc)), direction chosen $k, U=$U") # k=argmax(abs.(sum(∇ψ_1.(Samples)))) xkL=U[1,k]; xkU=U[2,k]; for i=1:length(s_list) ψ=ψ_list[i] ∇ψ=∇ψ_list[i] g=∇ψ(xc); ∇ψ_x=hcat([∇ψ(Samples[ii]) for ii=1:n_samples]...) #\delta is the max on each row δ=[maximum(abs.(∇ψ_x[kk,:] .- g[kk])) for kk=1:d] if abs(g[k])>δ[k]&& norm(g + δ)^2/(g[k]-δ[k])^2<20 #The restriction to the faces in the e_k direction. #I am using [x][1:k-1] instead of x[1:k-1] since # Vector[1:0] is well defined (empty array) but Number[1:0] is not. ψ_L=(x->ψ(insert_kth(x,k,xkL))) ψ_U=(x->ψ(insert_kth(x,k,xkU))) ∇ψ_L=x->remove_kth(∇ψ(insert_kth(x,k,xkL)),k) ∇ψ_U=x->remove_kth(∇ψ(insert_kth(x,k,xkU)),k) # println("xkL,xkU=$xkL, $xkU , psi L and psi U defined") si_L=sgn(g[k],s_list[i],-1); si_U=sgn(g[k],s_list[i],1); new_ψ_list=vcat(new_ψ_list,ψ_L,ψ_U); new_∇ψ_list=vcat(new_∇ψ_list,∇ψ_L,∇ψ_U); new_s_list=vcat(new_s_list,si_L,si_U) else Volume=prod(U[2,:] - U[1,:]); # if Volume<1e-3 #should be changed to something like #iterations>15 if recursion_depth>=16 #flag=1 if psi_i*s_i>0 for all i flag=prod([s_list[i]*ψ_list[i](xc)>0 for i=1:length(s_list)]); # display(flag) # display(∇ψ_x) # println("xc= $xc, ψ=[ $(ψ_list[1](xc))]") # println(" ψ(0,0)= $(ψ_list[1]([0,0.0]))") printstyled("Warning: lower order method used in $U\n";color=:red) # println((g,δ,k,abs(g[k]), δ[k], norm(g + δ)^2/(g[k]-δ[k])^2)) if flag #low order method return f(xc)*Volume; else return 0.0; end end # println("Domain split into two") kk=argmax(U[2,:]-U[1,:]); U1=deepcopy(U);U2=deepcopy(U); U1[2,kk]=(U[1,kk]+U[2,kk])/2.0; U2[1,kk]=(U[1,kk]+U[2,kk])/2.0; i1=algoim_quad(f,ψ_list,∇ψ_list,s_list,U1,q,recursion_depth+1); i2=algoim_quad(f,ψ_list,∇ψ_list,s_list,U2,q,recursion_depth+1); return i1+i2; end end U_tilde=hcat(U[:,1:k-1],U[:,k+1:end]); F_tilde=x->F1d(x,f,ψ_list,s_list,k,xkL,xkU,q) return algoim_quad(F_tilde, new_ψ_list,new_∇ψ_list,new_s_list,U_tilde,q) end function restrict(x::Vector,t::Number,k::Integer)#replace x[k] by t return vcat(x[1:k-1],t,x[k+1:end]) end function restrict(x::Number,t::Number,k::Integer)#replace x[k] by t if k==1 return [t,x] end if k==2 return [x,t] end end function F1d(x,f,ψ_list,s_list,k,a,b,q) f_tilde=t->f(restrict(x,t,k)) ψ_list_tilde=[t->ψ(restrict(x,t,k)) for ψ in ψ_list] return d1_int_f(f_tilde,ψ_list_tilde,s_list,[a,b],q) end
QuadratureOnImplicitRegions
https://github.com/Hmegh/QuadratureOnImplicitRegions.jl.git
[ "MIT" ]
0.2.0
38e36bad296e56f1ddf022029dd30129fcc5aff2
code
1536
using QuadratureOnImplicitRegions using Test using SpecialFunctions @testset "QuadratureOnImplicitRegions.jl" begin # Write your tests here. ψ(x)=x'*x-1 ## Testing the weights (should sum up to the area): #quarter of a circle a,b=zeros(2), ones(2) x,w=algoim_nodes_weights(ψ,-1.0, a,b,10) @test sum(w) ≈ π/4 #ellipse of radii 1,1/2 ell(x) = x[1]^2+(2*x[2])^2 -1.0 a,b=-2ones(2),2ones(2) x,w=algoim_nodes_weights(ell,-1.0, a,b,10) @test sum(w) ≈ π/2 #1/8 of a sphere a,b=zeros(3), ones(3) x,w=algoim_nodes_weights(ψ,-1.0, a,b,10) @test sum(w) ≈ π/6 ## Testing the quadrature rule for polynomials #This help to make sure that the nodes are mapped approperiately. #Note: Keep in mind that this quadrature is not exact (even for polynomials). #quarter of a circle a,b=zeros(2), ones(2) x,w=algoim_nodes_weights(ψ,-1.0, a,b,11) # ∫∫ x^i dxdy on the quarter circle # = √π/4*Γ((i+1)/2)/Γ(2+i/i) for i=1:10 exact_integral= √π/4 * gamma((i+1)/2)/gamma(2+i/2) approximate_integral= w'x[1,:].^i @test exact_integral≈ approximate_integral end # ∫∫ x^i y^j dxdy on the quarter circle # = Γ((i+1)/2)Γ((j+3)/2)/(2(j+1)Γ(2+(i+j)/2)) for i=1:10 for j=1:10 exact_integral=gamma((i+1)/2)*gamma((j+3)/2)/(2(j+1)*gamma(2+(i+j)/2)) approximate_integral=w'*(x[1,:].^i .* x[2,:].^j) @test exact_integral≈ approximate_integral end end end
QuadratureOnImplicitRegions
https://github.com/Hmegh/QuadratureOnImplicitRegions.jl.git
[ "MIT" ]
0.2.0
38e36bad296e56f1ddf022029dd30129fcc5aff2
code
3112
using QuadratureOnImplicitRegions using Test using Plots #to plot the quad points #Example 1: #consider the unit interval Ω=[0,1]², split into two regions: #Ω₁= {(x,y)∈Ω | x^2+y^2< 1 } # and Ω₂= {(x,y)∈Ω | x^2+y^2>1 } # Our goal is to generate quadrature nodes and weights on each region (subdomain) ψ(x)= x'*x-1.0 #basically x^2+y^2 -1 a,b=zeros(2), ones(2) #the unit interval. quad_order=10 #the higher, the more accurate the quadrature is xy1,w1=algoim_nodes_weights(ψ,-1.0, a,b,quad_order) xy2,w2=algoim_nodes_weights(ψ,+1.0, a,b,quad_order) #test the sum of the weights (it is equal to the area of each region) @test sum(w1)≈ π/4 @test sum(w2)≈ (1-π/4) #xy a matrix (each column is a node): x1,y1= xy1[1,:] , xy1[2,:] x2,y2= xy2[1,:] , xy2[2,:] #visualize the quadrature nodes: #the rectangle rect_x=[a[1],b[1],b[1],a[1],a[1]] rect_y=[a[2],a[2],b[2],b[2],a[2]] P=plot(rect_x,rect_y,c=:black,label="Ω",legend=:outerleft,axis=false,grid=false) #the interface ψ=0 plot!(P,range(a[1],b[1],50), range(a[2],b[2],50),(x,y)->ψ([x,y]),levels=[0.0],c=:green,seriestype=:contour,label="ψ=0",cbar=false) #the quadrature nodes scatter!(P,x1,y1,c=:blue,label="Ω₁") scatter!(P,x2,y2,c=:red,label="Ω₂") savefig(P,"tutorial/example_1.png") #Example 2: #Consider the domain [-2,2]² split by the unit circle into the unit disk and the remainder. #It can be handled similarly to the previous example. The algorithm will detect the need to split the domain automatically. ψ(x)= x'*x-1.0 #the same as before a,b=-2ones(2), 2ones(2) quad_order=5 xy1,w1=algoim_nodes_weights(ψ,-1.0, a,b,quad_order) xy2,w2=algoim_nodes_weights(ψ,+1.0, a,b,quad_order) # need quad_order≥20 to achieve this accuracy. For the sake of this tutorial, we will use a smaller quad_order # @test sum(w1)≈ π # @test sum(w2)≈ 16-π #plotting the quad points as before x1,y1= xy1[1,:] , xy1[2,:] x2,y2= xy2[1,:] , xy2[2,:] rect_x=[a[1],b[1],b[1],a[1],a[1]] rect_y=[a[2],a[2],b[2],b[2],a[2]] P2=plot(rect_x,rect_y,c=:black,label="Ω",legend=:outerleft,axis=false,grid=false) plot!(P2,range(a[1],b[1],50), range(a[2],b[2],50),(x,y)->ψ([x,y]),levels=[0.0],c=:green,seriestype=:contour,label="ψ=0",cbar=false) scatter!(P2,x1,y1,c=:blue,label="Ω₁") scatter!(P2,x2,y2,c=:red,label="Ω₂") savefig(P2,"tutorial/example_2.png") #Example 3: #It is the same as example 1, but in three dimensions ψ(x)= x'*x-1.0 #the same as before a,b=zeros(3), ones(3) quad_order=5 xyz1,w1=algoim_nodes_weights(ψ,-1.0, a,b,quad_order) xyz2,w2=algoim_nodes_weights(ψ,+1.0, a,b,quad_order) x1,y1,z1= xyz1[1,:],xyz1[2,:],xyz1[3,:] x2,y2,z2= xyz2[1,:],xyz2[2,:],xyz2[3,:] #the unit cube A=[0,1,1,0,0] B=[0,0,1,1,0] C=[0,0,0,0,0] D=[1,1,1,1,1] P3=plot() plot!(P3,A,B,C,label="Ω",c=:black,axis=false,grid=false) plot!(P3,A,B,D,c=:black,label=nothing) plot!(P3,A,C,B,c=:black,label=nothing) plot!(P3,A,D,B,c=:black,label=nothing) P31=deepcopy(P3) P32=deepcopy(P3) scatter!(P31,x1,y1,z1,c=:blue,label="Ω₁") scatter!(P32,x2,y2,z2,c=:red,label="Ω₂") plot!(P31,camera=(60,15)) # plot(P32,camera=(30,30)) savefig(P31,"tutorial/example_3.png")
QuadratureOnImplicitRegions
https://github.com/Hmegh/QuadratureOnImplicitRegions.jl.git
[ "MIT" ]
0.2.0
38e36bad296e56f1ddf022029dd30129fcc5aff2
docs
2053
# QuadratureOnImplicitRegions [![Build Status](https://github.com/hmegh/QuadratureOnImplicitRegions.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/hmegh/QuadratureOnImplicitRegions.jl/actions/workflows/CI.yml?query=branch%3Amain) This package implements a quadrature method on implicitly defined regions following the algorithm in: [R. I. Saye, High-Order Quadrature Methods for Implicitly Defined Surfaces and Volumes in Hyperrectangles, SIAM Journal on Scientific Computing, 37(2), A993-A1019 (2015).](https://epubs.siam.org/doi/10.1137/140966290). --- # Simple exmaples: Let $\Omega=[0,1]^2$ and let $\psi(x,y)=x^2+y^2-1$. Our goal is to create quadrature nodes and weights on the subdomains: $$\Omega_1=\left\\{(x,y)\in \Omega : \psi(x,y)<0\right\\},\qquad \Omega_2=\left\\{(x,y)\in \Omega : \psi(x,y)>0\right\\}.$$ ```julia using QuadratureOnImplicitRegions ψ(x)= x'*x-1.0 a,b=zeros(2), ones(2) #the unit interval. quad_order=10 #the nodes and weights on Ω₁ xy1,w1=algoim_nodes_weights(ψ,-1.0, a,b,quad_order) #the nodes and weights on Ω₂ xy2,w2=algoim_nodes_weights(ψ,+1.0, a,b,quad_order) ``` To plot the nodes, please see [this tutorial](https://github.com/Hmegh/QuadratureOnImplicitRegions.jl/blob/main/tutorial/circle_and_sphere.jl). <p align="center"> <img src="https://github.com/Hmegh/QuadratureOnImplicitRegions.jl/assets/8241188/8926d082-3b1c-48cb-a888-3882b1288f7f" width="250" height=auto/> </p> The same syntax can be used for higher dimensional regions. For example, in the case of the intersection of the unit sphere and unit cube, we only need to adjust `a` and `b`: ```julia using QuadratureOnImplicitRegions ψ(x)= x'*x-1.0 a,b=zeros(3), ones(3) #the unit cube. quad_order=5 xyz1,w1=algoim_nodes_weights(ψ,-1.0, a,b,quad_order) ``` For the outer region, we only need to change `-1.0` to `1.0` <p align="center"> <img src="https://github.com/Hmegh/QuadratureOnImplicitRegions.jl/assets/8241188/43354dab-7818-46eb-8ee2-c65b394b0369" width="250" height=auto/> </p>
QuadratureOnImplicitRegions
https://github.com/Hmegh/QuadratureOnImplicitRegions.jl.git
[ "MIT" ]
2.1.0
d7c686c778f2d8a43d831ef6bb9bad9053159340
code
13477
module Neo4j using HTTP using JSON using DocStringExtensions using Base64 export getgraph, version, createnode, getnode, deletenode, setnodeproperty, getnodeproperty, getnodeproperties, updatenodeproperties, deletenodeproperties, deletenodeproperty, addnodelabel, addnodelabels, updatenodelabels, deletenodelabel, getnodelabels, getnodesforlabel, getlabels, getrel, getrels, getneighbors, createrel, deleterel, getrelproperty, getrelproperties, updaterelproperties, cypherQuery export Connection, Result const DEFAULT_HOST = "localhost" const DEFAULT_PORT = 7474 const DEFAULT_URI = "/db/data/" const JSONObject{T <: AbstractString} = Union{Dict{T,Any},Nothing} # UTF8String const JSONArray = Union{Vector,Nothing} const JSONData{T <: AbstractString} = Union{JSONObject,JSONArray,T,Number,Nothing} const QueryData = Union{Dict{Any,Any},Nothing} # ---------- # Connection # ---------- """ Connection() ### Examples ```julia-repl julia> con = Neo4j.Connection("localhost") Neo4j.Connection(false, "localhost", 7474, "/db/data/", "http://localhost:7474/db/data/", "", "") ``` """ struct Connection host::AbstractString #UTF8String tls::Bool port::Int path::AbstractString #UTF8String url::AbstractString #UTF8String user::AbstractString #UTF8String password::AbstractString #UTF8String Connection(host::T; port = DEFAULT_PORT, path = DEFAULT_URI, tls = false, user = "", password = "") where {T <: AbstractString} = new(string(host), tls, port, string(path), string("http://$host:$port$path"), string(user), string(password)) Connection() = Connection(DEFAULT_HOST) end function connurl(c::Connection) proto = ifelse(c.tls, "https", "http") "$(proto)://$(c.host):$(c.port)$(c.path)" end function connurl(c::Connection, suffix::T) where {T <: AbstractString} url = connurl(c) "$(url)$(suffix)" end function connheaders(c::Connection) headers = Dict( "Accept" => "application/json; charset=UTF-8", "content-type" => "application/json", "Host" => "$(c.host):$(c.port)") if c.user != "" && c.password != "" payload = "$(c.user):$(c.password)" |> base64encode headers["Authorization"] = "Basic $(payload)" end headers end # ----- # Graph # ----- struct Graph # TODO extensions node::AbstractString #UTF8String node_index::AbstractString #UTF8String relationship_index::AbstractString #UTF8String extensions_info::AbstractString #UTF8String relationship_types::AbstractString #UTF8String batch::AbstractString #UTF8String cypher::AbstractString #UTF8String indexes::AbstractString #UTF8String constraints::AbstractString #UTF8String transaction::AbstractString #UTF8String node_labels::AbstractString #UTF8String version::AbstractString #UTF8String connection::Connection relationship::AbstractString #UTF8String # Not in the spec end # UTF8String Graph(data::Dict{T,Any}, conn::Connection) where {T <: AbstractString} = Graph(data["node"], data["node_index"], data["relationship_index"], data["extensions_info"], data["relationship_types"], data["batch"], data["cypher"], data["indexes"], data["constraints"], data["transaction"], data["node_labels"], data["neo4j_version"], conn, "$(conn.url)relationship") function getgraph(conn::Connection) resp = HTTP.get(conn.url; headers=connheaders(conn)) if resp.status != 200 error("Connection to server unsuccessful: $(resp.status)") end Graph(Dict{AbstractString,Any}(JSON.parse(String(resp.body))), conn) # UTF8String end function getgraph() getgraph(Connection()) end # ---- # Node # ---- struct Node # TODO extensions paged_traverse::AbstractString #UTF8String labels::AbstractString #UTF8String outgoing_relationships::AbstractString #UTF8String traverse::AbstractString #UTF8String all_typed_relationships::AbstractString #UTF8String all_relationships::AbstractString #UTF8String property::AbstractString #UTF8String self::AbstractString #UTF8String outgoing_typed_relationships::AbstractString #UTF8String properties::AbstractString #UTF8String incoming_relationships::AbstractString #UTF8String incoming_typed_relationships::AbstractString #UTF8String create_relationship::AbstractString #UTF8String data::JSONObject metadata::Dict{AbstractString, Any} #UTF8String id::Int64 graph::Graph #Constructors Node() = new() Node(data::JSONObject, graph::Graph) = new(data["paged_traverse"], data["labels"], data["outgoing_relationships"], data["traverse"], data["all_typed_relationships"], data["all_relationships"], data["property"], data["self"], data["outgoing_typed_relationships"], data["properties"], data["incoming_relationships"], data["incoming_typed_relationships"], data["create_relationship"], data["data"], data["metadata"], split(data["self"], "/")[end] |> Meta.parse, graph) end # ---------- # Statements # ---------- struct Statement statement::AbstractString parameters::Dict end # ------- # Results # ------- struct Result results::Vector errors::Vector end # ------------ # Transactions # ------------ include("transaction.jl") # -------- # Requests # -------- function request(url::AbstractString, method::Function, exp_code::Int, headers::Dict{T, T}; jsonDict::JSONData = nothing, query::QueryData = nothing)::AbstractString where {T <: AbstractString} resp = nothing try # Simplified to a single call body = jsonDict != nothing ? JSON.json(jsonDict) : "" resp = method(url; headers = headers, body=body, query=query) catch ex # Handle status errors specifically. if ex isa HTTP.ExceptionRequest.StatusError resp = ex.response else rethrow(ex) end finally if resp.status != exp_code respdata = JSON.parse(String(resp.body)) if respdata !== nothing && "message" in keys(respdata) error("Neo4j error: $(respdata["message"])") else error("Neo4j error: $(url) returned $(resp.status)") end end # Great, return the response body return String(resp.body) end end # ----------------- # External requests # ----------------- function createnode(graph::Graph, props::JSONData = nothing) resp = request(graph.node, HTTP.post, 201, connheaders(graph.connection); jsonDict=props) jsrsp = Dict{AbstractString,Any}(JSON.parse(resp)) # UTF8String # @show typeof(jsrsp) Node(jsrsp, graph) end function getnode(graph::Graph, id::Int) url = "$(graph.node)/$id" resp = request(url, HTTP.get, 200, connheaders(graph.connection)) Node(Dict{AbstractString,Any}(JSON.parse(resp)), graph) # UTF8String end function getnode(node::Node) getnode(node.graph, node.id) end function deletenode(node::Node) request(node.self, HTTP.delete, 204, connheaders(node.graph.connection)) end function deletenode(graph::Graph, id::Int) node = getnode(graph, id) deletenode(node) end function setnodeproperty(node::Node, name::T, value::Any) where {T <: AbstractString} url = replace(node.property, "{key}" => name) request(url, HTTP.put, 204, connheaders(node.graph.connection); jsonDict=value) end function setnodeproperty(graph::Graph, id::Int, name::T, value::Any) where {T <: AbstractString} node = getnode(graph, id) setnodeproperty(node, name, value) end function updatenodeproperties(node::Node, props::JSONObject) resp = request(node.properties, HTTP.put, 204, connheaders(node.graph.connection); jsonDict=props) end function getnodeproperty(node::Node, name::T) where {T <: AbstractString} url = replace(node.property, "{key}" => name) resp = request(url, HTTP.get, 200, connheaders(node.graph.connection)) JSON.parse(resp) end function getnodeproperties(node::Node) resp = request(node.properties, HTTP.get, 200, connheaders(node.graph.connection)) JSON.parse(resp) end function getnodeproperties(graph::Graph, id::Int) node = getnode(graph, id) getnodeproperties(node) end function deletenodeproperties(node::Node) request(node.properties, HTTP.delete, 204, connheaders(node.graph.connection)) end function deletenodeproperty(node::Node, name::T) where {T <: AbstractString} url = replace(node.property, "{key}" => name) request(url, HTTP.delete, 204, connheaders(node.graph.connection)) end function addnodelabel(node::Node, label::T) where {T <: AbstractString} request(node.labels, HTTP.post, 204, connheaders(node.graph.connection); jsonDict=label) end function addnodelabels(node::Node, labels::JSONArray) request(node.labels, HTTP.post, 204, connheaders(node.graph.connection); jsonDict=labels) end function updatenodelabels(node::Node, labels::JSONArray) request(node.labels, HTTP.put, 204, connheaders(node.graph.connection); jsonDict=labels) end function deletenodelabel(node::Node, label::T) where {T <: AbstractString} url = "$(node.labels)/$label" request(url, HTTP.delete, 204, connheaders(node.graph.connection)) end function getnodelabels(node::Node) resp = request(node.labels, HTTP.get, 200, connheaders(node.graph.connection)) JSON.parse(resp) end function getnodesforlabel(graph::Graph, label::T, props::JSONObject=nothing) where {T <: AbstractString} # TODO Shouldn't this url be available in the api somewhere? url = "$(graph.connection.url)label/$label/nodes" resp = request(url, HTTP.get, 200, connheaders(graph.connection); query=props) [Node(Dict{AbstractString,Any}(nodedata), graph) for nodedata = JSON.parse(resp)] end function getlabels(graph::Graph) resp = request(graph.node_labels, HTTP.get, 200, connheaders(graph.connection)) JSON.parse(resp) end # ------------- # Relationships # ------------- struct Relationship relstart::AbstractString #UTF8String property::AbstractString #UTF8String self::AbstractString #UTF8String properties::AbstractString #UTF8String metadata::Dict{AbstractString ,Any} #UTF8String reltype::AbstractString #UTF8String relend::AbstractString #UTF8String data::JSONObject id::Int graph::Graph end Relationship(data::JSONObject, graph::Graph) = Relationship(data["start"], data["property"], data["self"], data["properties"], data["metadata"], data["type"], data["end"], data["data"], split(data["self"], "/")[end] |> Meta.parse, graph) function getrels(node::Node; incoming::Bool = true, outgoing::Bool = true) rels = Vector{Relationship}() if(incoming) resp = request(node.incoming_relationships, HTTP.get, 200, connheaders(node.graph.connection)) for rel=JSON.parse(resp) push!(rels, Relationship(Dict{AbstractString,Any}(rel), node.graph)) #UTF8String end end if(outgoing) resp = request(node.outgoing_relationships, HTTP.get, 200, connheaders(node.graph.connection)) for rel=JSON.parse(resp) push!(rels, Relationship(Dict{AbstractString,Any}(rel), node.graph)) #UTF8String end end rels end function getneighbors(node::Node; incoming::Bool = true, outgoing::Bool = true) neighbors = Vector{Node}() # Do incoming if(incoming) rels = getrels(node, incoming = true, outgoing = false) for rel=rels resp = request(rel.relstart, HTTP.get, 200, connheaders(node.graph.connection)) push!(neighbors, Node(Dict{AbstractString,Any}(JSON.parse(resp)), node.graph)) # UTF8String end end if(outgoing) rels = getrels(node, incoming = false, outgoing = true) for rel=rels resp = request(rel.relend, HTTP.get, 200, connheaders(node.graph.connection)) push!(neighbors, Node(Dict{AbstractString,Any}(JSON.parse(resp)), node.graph)) # UTF8String end end neighbors end function getrel(graph::Graph, id::Int) url = "$(graph.relationship)/$id" resp = request(url, HTTP.get, 200, connheaders(graph.connection)) Relationship(Dict{AbstractString,Any}(JSON.parse(resp)), graph) # UTF8String end function createrel(from::Node, to::Node, reltype::AbstractString; props::JSONObject=nothing) body = Dict{AbstractString, Any}("to" => to.self, "type" => uppercase(reltype)) # UTF8String if props !== nothing body["data"] = props end resp = request(from.create_relationship, HTTP.post, 201, connheaders(from.graph.connection), jsonDict=body) Relationship(Dict{AbstractString,Any}(JSON.parse(resp)), from.graph) # UTF8String end function deleterel(rel::Relationship) request(rel.self, HTTP.delete, 204, connheaders(rel.graph.connection)) end function getrelproperty(rel::Relationship, name::AbstractString) url = replace(rel.property, "{key}" => name) resp = request(url, HTTP.get, 200, connheaders(rel.graph.connection)) JSON.parse(resp) end function getrelproperties(rel::Relationship) resp = request(rel.properties, HTTP.get, 200, connheaders(rel.graph.connection)) JSON.parse(resp) end function updaterelproperties(rel::Relationship, props::JSONObject) request(rel.properties, HTTP.put, 204, connheaders(rel.graph.connection); jsonDict=props) end # ------------ # Cypher query # ------------ include("cypherQuery.jl") end # module
Neo4j
https://github.com/glesica/Neo4j.jl.git
[ "MIT" ]
2.1.0
d7c686c778f2d8a43d831ef6bb9bad9053159340
code
3890
using DataFrames, Missings; """ $(SIGNATURES) Retrieve molecular identifier from other databases, `targetDb`, for single or mulitple query IDs, `queryId`, and moreover information on Ensembl gene, transcript and peptide IDs, such as ID and genomic loation. ### Arguments - `conn::Neo4j.Connection` : a valid connection to a Neo4j graph DB instance. - `cypher::String` : Cypher `MATCH` query returning tabular data. - `params::Pair` : parameters which are passed on to the cypher query. - `elTypes::Vector{Type}` : column types can be provided manually as a Vector{Type} - `nRowsElTypeCheck::Int` : Number of rows which are used to determine column datatypes (defaults to 1000) ### Examples ```julia-repl julia> cypherQuery( Neo4j.Connection("localhost"), "MATCH (p :Person {name: {name}}) RETURN p.name AS Name, p.age AS Age;", "name" => "John Doe") ``` """ function cypherQuery( conn::Connection, cypher::AbstractString, params::Pair...; elTypes::Vector{DataType} = Vector{DataType}(), nRowsElTypeCheck::Int = 1000)::DataFrames.DataFrame url = connurl(conn, "transaction/commit") headers = connheaders(conn) body = Dict("statements" => [Statement(cypher, Dict(params))]) resp = HTTP.post(url; headers=headers, body=JSON.json(body)) if resp.status != 200 error("Failed to commit transaction ($(resp.status)): $(txn)\n$(resp)") end respdata = JSON.parse(String(resp.body)) if !isempty(respdata["errors"]) error(join(map(i -> (i * ": " * respdata["errors"][1][i]), keys(respdata["errors"][1])), "\n")); end # parse results into data sink # Result(respdata["results"], respdata["errors"]) if !isempty(respdata["results"][1]["data"]) return parseResults(respdata["results"][1], elTypes = elTypes, nRowsElTypeCheck = nRowsElTypeCheck); else return DataFrames.DataFrame(); end end # Currently only supports DataFrames.DataFrame objects # -> Future: Allow different data sink types, such as tables from JuliaDB function parseResults(res::Dict{String, Any}; elTypes::Vector{DataType} = Vector(), nRowsElTypeCheck::Int = 100)::DataFrames.DataFrame # Get elementary types from a column where there is no NA value (nothing) if isempty(elTypes) elTypes = getElTypes(res["data"], nRowsElTypeCheck); end colNames = Symbol.(collect(res["columns"])) # collect(Symbol, res["columns"]); nRows = length(res["data"]); # x = DataFrames.DataFrame(elTypes, colNames, nRows); x = DataFrames.DataFrame(colNames .=> [type[] for type in elTypes]) for rowVal in res["data"] row = rowVal["row"] if row !== nothing push!(x, row) end end return x; end function getElTypes(x::Vector{Any}, nRowsElTypeCheck::Int = 0)::Vector{Type} nRecords = length(x); elTypes::Vector{Type} = Type[Union{Nothing, Missings.Missing} for i in 1:length(x[1]["row"])]; nMaxRows = nRecords; # elTypes = Type[Union{Nothing, Missings.Missing} for i in 1:length(x[1]["row"])]; nMaxRows = (nRowsElTypeCheck != 0 && nRowsElTypeCheck <= nMaxRows) ? nRowsElTypeCheck : nRecords; checkIdx = trues(length(x[1]["row"])); for i in 1:nMaxRows # check each column individually for el in findall(checkIdx) if !(x[i]["row"][el] == nothing) if !(typeof(x[i]["row"][el]) === Array{Any,1}) elTypes[el] = i > 1 ? Union{typeof(x[i]["row"][el]), Missings.Missing} : typeof(x[i]["row"][el]); else elTypes[el] = i > 1 ? Union{Vector{typeof(x[i]["row"][el][1])}, Missings.Missing} : Vector{typeof(x[i]["row"][el][1])}; end checkIdx[el] = false; end end if isempty(findall(checkIdx)) break; end end return elTypes; end
Neo4j
https://github.com/glesica/Neo4j.jl.git
[ "MIT" ]
2.1.0
d7c686c778f2d8a43d831ef6bb9bad9053159340
code
2412
# Transactions # A transaction is the primary type through which the database is accessed. A # transaction can be a single request, or it can be held open through many # requests as a means of batching jobs together. export transaction, rollback, commit struct Transaction conn::Connection commit::AbstractString location::AbstractString statements::Vector{Statement} end # TODO: Provide a version that accepts statements. function transaction(conn::Connection)::Transaction url = connurl(conn, "transaction") headers = connheaders(conn) body = Dict("statements" => [ ]) resp = HTTP.post(url; headers=headers, body=JSON.json(body)) if resp.status != 201 error("Failed to connect to database ($(resp.status)): $(conn)\n$(resp)") end respdata = JSON.parse(String(resp.body)) # Get the header with entry "Location" location = filter(h->h[1]=="Location", resp.headers) if length(location) == 0 error("Could not header with key 'Location' in response body of the transaction.") end return Transaction(conn, respdata["commit"], location[1][2], Statement[]) end function (txn::Transaction)(cypher::AbstractString, params::Pair...; submit::Bool=false) append!(txn.statements, [Statement(cypher, Dict(params))]) if submit url = txn.location headers = connheaders(txn.conn) body = Dict("statements" => txn.statements) resp = HTTP.post(url; headers=headers, body=JSON.json(body)) if resp.status != 200 error("Failed to submit transaction ($(resp.status)): $(txn)\n$(resp)") end respdata = JSON.parse(String(resp.body)) empty!(txn.statements) result = Result(respdata["results"], respdata["errors"]) return result end end function commit(txn::Transaction)::Result url = txn.commit headers = connheaders(txn.conn) body = Dict("statements" => txn.statements) resp = HTTP.post(url; headers=headers, body=JSON.json(body)) if resp.status != 200 error("Failed to commit transaction ($(resp.status)): $(txn)\n$(resp)") end respdata = JSON.parse(String(resp.body)) return Result(respdata["results"], respdata["errors"]) end function rollback(txn::Transaction)::HTTP.Response url = txn.location headers = connheaders(txn.conn) resp = HTTP.delete(url; headers=headers) if resp.status != 200 error("Failed to rollback transaction ($(resp.status)): $(txn)\n$(resp)") end return resp end
Neo4j
https://github.com/glesica/Neo4j.jl.git
[ "MIT" ]
2.1.0
d7c686c778f2d8a43d831ef6bb9bad9053159340
code
8217
using Neo4j, DataFrames using Test @testset "Module imports" begin @test (@isdefined Neo4j) == true @test typeof(Neo4j) == Module end # defaults for testing global username = "neo4j" global passwd = "neo5j" global graph = nothing global conn = nothing @testset "Creating a connection to localhost" begin try global graph = getgraph() catch @info "[TEST] Anonymous connection failed! Creating a Neo4j connection to localhost:7474 with neo4j:$(passwd) credentials..." #Trying with security. global conn = Neo4j.Connection("localhost"; user=username, password=passwd); global graph = getgraph(conn); end global conn = graph.connection; end @testset "Checking version of connected graph = Neo4j $(ascii(graph.version))..." begin # Have to account for newer Neo4j! Using version text - ref: http://docs.julialang.org/en/release-0.4/manual/strings/ @test VersionNumber(graph.version) > v"2.0.0" # convert(VersionNumber, graph.version) > v"2.0.0" # Check that @test graph.node == "http://localhost:7474/db/data/node" end global barenode = nothing global propnode = nothing @testset "Nodes: CRUD, properties, and labels..." begin global barenode = Neo4j.createnode(graph) @test barenode.self == "http://localhost:7474/db/data/node/$(barenode.id)" global propnode = Neo4j.createnode(graph, Dict{AbstractString,Any}("a" => "A", "b" => 1)) #UTF8String @test propnode.data["a"] == "A" @test propnode.data["b"] == 1 global gotnode = getnode(graph, propnode.id) @test gotnode.id == propnode.id @test gotnode.data["a"] == "A" @test gotnode.data["b"] == 1 setnodeproperty(barenode, "a", "A") global barenode = getnode(barenode) @test barenode.data["a"] == "A" global props = getnodeproperties(propnode) @test props["a"] == "A" @test props["b"] == 1 @test length(props) == 2 updatenodeproperties(barenode, Dict{AbstractString,Any}("a" => 1, "b" => "A")) #UTF8String global barenode = getnode(barenode) @test barenode.data["a"] == 1 @test barenode.data["b"] == "A" deletenodeproperties(barenode) global barenode = getnode(barenode) @test length(barenode.data) == 0 deletenodeproperty(propnode, "b") global propnode = getnode(propnode) @test length(propnode.data) == 1 @test propnode.data["a"] == "A" addnodelabel(barenode, "A") global barenode = getnode(barenode) @test getnodelabels(barenode) == ["A"] addnodelabels(barenode, ["B", "C"]) global barenode = getnode(barenode) global labels = getnodelabels(barenode) @test "A" in labels @test "B" in labels @test "C" in labels @test length(labels) == 3 updatenodelabels(barenode, ["D", "E", "F"]) global barenode = getnode(barenode) global labels = getnodelabels(barenode) @test "D" in labels @test "E" in labels @test "F" in labels @test length(labels) == 3 deletenodelabel(barenode, "D") global barenode = getnode(barenode) global labels = getnodelabels(barenode) @test "E" in labels @test "F" in labels @test length(labels) == 2 global nodes = getnodesforlabel(graph, "E") @test length(nodes) > 0 @test barenode.id in [n.id for n = nodes] global labels = getlabels(graph) end @testset "Relationships: CRUD, neighbors" begin global rel1 = createrel(barenode, propnode, "test"; props=Dict{AbstractString,Any}("a" => "A", "b" => 1)); #UTF8String global rel1alt = getrel(graph, rel1.id); @test rel1.reltype == "TEST" @test rel1.data["a"] == "A" @test rel1.data["b"] == 1 @test rel1.id == rel1alt.id global endnode = Neo4j.createnode(graph, Dict{AbstractString,Any}("a" => "A", "b" => 1)) # UTF8String global rel2 = createrel(propnode, endnode, "test"; props=Dict{AbstractString,Any}("a" => "A", "b" => 1)); # UTF8String @test length(Neo4j.getrels(endnode)) == 1 @test length(Neo4j.getrels(propnode)) == 2 @test length(Neo4j.getrels(barenode)) == 1 @test length(Neo4j.getrels(endnode, incoming=true, outgoing=false)) == 1 @test length(Neo4j.getrels(endnode, incoming=false, outgoing=true)) == 0 @test length(Neo4j.getrels(propnode, incoming=true, outgoing=false)) == 1 @test length(Neo4j.getrels(propnode, incoming=false, outgoing=true)) == 1 global neighbors = Neo4j.getneighbors(propnode) @test length(neighbors) == 2 global neighbors = Neo4j.getneighbors(propnode, incoming=true, outgoing=false) @test length(neighbors) == 1 @test neighbors[1].metadata["id"] == barenode.metadata["id"] global neighbors = Neo4j.getneighbors(propnode, incoming=false, outgoing=true) @test length(neighbors) == 1 @test neighbors[1].metadata["id"] == endnode.metadata["id"] global rel1prop = getrelproperties(rel1); @test rel1prop["a"] == "A" @test rel1prop["b"] == 1 @test length(rel1prop) == 2 @test getrelproperty(rel1, "a") == "A" @test getrelproperty(rel1, "b") == 1 deleterel(rel1) deleterel(rel2) @test_throws ErrorException getrel(graph, rel1.id) @test_throws ErrorException getrel(graph, rel2.id) end @testset "Nodes: Deleting nodes (cleaning up)" begin deletenode(graph, barenode.id) deletenode(graph, propnode.id) @test_throws ErrorException getnode(graph, barenode.id) @test_throws ErrorException getnode(graph, propnode.id) end # --- New transaction code from Glesica source --- function createnode(txn, name, age; submit=false) q = "CREATE (n:Neo4jjl) SET n.name = {name}, n.age = {age}" txn(q, "name" => name, "age" => age; submit=submit) end @testset "Transactions" begin global loadtx = transaction(conn) @test length(loadtx.statements) == 0 createnode(loadtx, "John Doe", 20) @test length(loadtx.statements) == 1 createnode(loadtx, "Jane Doe", 20) @test length(loadtx.statements) == 2 global query = "MATCH (n:Neo4jjl) WHERE n.age = {age} RETURN n.name"; global people = loadtx(query, "age" => 20; submit=true) @test length(loadtx.statements) == 0 @test length(people.results) == 3 @test length(people.errors) == 0 global matchresult = people.results[3] @test matchresult["columns"][1] == "n.name" @test "John Doe" in [row["row"][1] for row = matchresult["data"]] @test "Jane Doe" in [row["row"][1] for row = matchresult["data"]] global loadresult = commit(loadtx) @test length(loadresult.results) == 0 @test length(loadresult.errors) == 0 global query = "MATCH (n:Neo4jjl) WHERE n.age = {age} DELETE n" global deletetx = transaction(conn) deletetx(query, "age" => 20) global deleteresult = commit(deletetx) @test length(deleteresult.results) == 1 @test length(deleteresult.results[1]["columns"]) == 0 @test length(deleteresult.results[1]["data"]) == 0 @test length(deleteresult.errors) == 0 global rolltx = transaction(conn) global person = createnode(rolltx, "John Doe", 20; submit=true) @test length(rolltx.statements) == 0 @test length(person.results) == 1 @test length(person.errors) == 0 rollback(rolltx) global rolltx = transaction(conn) global rollresult = rolltx("MATCH (n:Neo4jjl) WHERE n.name = 'John Doe' RETURN n"; submit=true) @test length(rollresult.results) == 1 @test length(rollresult.results[1]["columns"]) == 1 @test length(rollresult.results[1]["data"]) == 0 @test length(rollresult.errors) == 0 end # --- New cypherQuery using transaction/commit endpoint --- @testset "DataFrames with cypherQuery()" begin # Open transaction and create node global loadtx = transaction(conn) createnode(loadtx, "John Doe", 20; submit=true) Neo4j.commit(loadtx) global matchresult = cypherQuery(conn, "MATCH (n:Neo4jjl {name: {name}}) RETURN n.name AS Name, n.age AS Age;", "name" => "John Doe") @test DataFrames.DataFrame(Name = "John Doe", Age = 20) == matchresult # Cleanup global deletetx = transaction(conn) global query = "MATCH (n:Neo4jjl) WHERE n.age = {age} DELETE n" deletetx(query, "age" => 20) global deleteresult = commit(deletetx) end
Neo4j
https://github.com/glesica/Neo4j.jl.git
[ "MIT" ]
2.1.0
d7c686c778f2d8a43d831ef6bb9bad9053159340
docs
1544
> This project is no longer actively maintained and probably doesn't work with recent versions of > Neo4j. PRs to fix aspects of its functionality are still welcome. # Neo4j.jl [![CI](https://github.com/glesica/Neo4j.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/glesica/Neo4j.jl/actions/workflows/CI.yml) [![codecov.io](https://codecov.io/github/glesica/Neo4j.jl/coverage.svg?branch=master)](https://codecov.io/github/glesica/Neo4j.jl?branch=master) A [Julia](http://julialang.org) client for the [Neo4j](http://neo4j.org) graph database. Really easy to use, have a look at ```test/runtests.jl``` for the available methods. ## Basic Usage ```julia c = Connection("localhost"; user="neo4j", password="neo4j") tx = transaction(c) tx("CREATE (n:Lang) SET n.name = \$name", "name" => "Julia") tx("MATCH (n:Lang) RETURN n LIMIT {limit}", "limit" => 10) results = commit(tx) ``` You can also submit a transaction to the server without committing it. This will return a result set but will keep the transaction open both on the client and server: ```julia results = tx("MATCH (n) RETURN n"; submit=true) ``` Rollbacks are also supported: ```julia rollback(tx) ``` If the goal is to simply run a MATCH query and get the result in the form of a `DataFrames.DataFrame` object, the `cypherQuery` function can be used. The `cypherQuery` implementation performs the query in a single transaction which automatically opens and closes the transaction: ```julia results = cypherQuery(c, "MATCH (n) RETURN n.property AS Property") ```
Neo4j
https://github.com/glesica/Neo4j.jl.git
[ "MIT" ]
0.3.0
855371d8fdfaed46dbb32a7c57a42db4441b9247
code
3176
module StaticGraphs using Graphs using JLD2 using SparseArrays import Base: convert, eltype, show, ==, Pair, Tuple, in, copy, length, issubset, zero, one, size, getindex, setindex!, length, IndexStyle import Graphs: _NI, AbstractEdge, AbstractEdgeIter, src, dst, edgetype, nv, ne, vertices, edges, is_directed, has_vertex, has_edge, inneighbors, outneighbors, indegree, outdegree, degree, insorted, squash, AbstractGraphFormat, loadgraph, savegraph, reverse import Graphs.SimpleGraphs: AbstractSimpleGraph, fadj, badj, SimpleEdge, AbstractSimpleEdge export AbstractStaticGraph, StaticEdge, StaticGraph, StaticDiGraph, StaticDiGraphEdge, # weight, # weighttype, # get_weight, out_edges, in_edges, SGraph, SDiGraph, SGFormat, SDGFormat include("utils.jl") const AbstractStaticEdge{T} = AbstractSimpleEdge{T} const StaticEdge{T} = SimpleEdge{T} """ AbstractStaticGraph{T, U} An abstract type representing a simple graph structure parameterized by integer types - `T`: the type representing the graph's vertices - `U`: the type representing the number of edges in the graph """ abstract type AbstractStaticGraph{T<:Integer, U<:Integer} <: AbstractSimpleGraph{T} end vectype(g::AbstractStaticGraph{T, U}) where T where U = T indtype(g::AbstractStaticGraph{T, U}) where T where U = U eltype(x::AbstractStaticGraph) = vectype(x) function show(io::IO, g::AbstractStaticGraph) dir = is_directed(g) ? "directed" : "undirected" print(io, "{$(nv(g)), $(ne(g))} $dir simple static {$(vectype(g)), $(indtype(g))} graph") end @inline function _fvrange(g::AbstractStaticGraph, s::Integer) @inbounds r_start = g.f_ind[s] @inbounds r_end = g.f_ind[s + 1] - 1 return r_start:r_end end @inline function fadj(g::AbstractStaticGraph, s::Integer) r = _fvrange(g, s) return view(g.f_vec, r) end @inline fadj(g::AbstractStaticGraph) = [fadj(g, v) for v in vertices(g)] nv(g::AbstractStaticGraph{T, U}) where T where U = T(length(g.f_ind) - 1) vertices(g::AbstractStaticGraph{T, U}) where T where U = Base.OneTo(nv(g)) has_edge(g::AbstractStaticGraph, e::AbstractStaticEdge) = insorted(dst(e), outneighbors(g, src(e))) edgetype(g::AbstractStaticGraph{T}) where T = StaticEdge{T} edges(g::AbstractStaticGraph) = StaticEdgeIter(g) has_vertex(g::AbstractStaticGraph, v::Integer) = v in vertices(g) outneighbors(g::AbstractStaticGraph, v::Integer) = fadj(g, v) inneighbors(g::AbstractStaticGraph, v::Integer) = badj(g, v) zero(g::T) where T<:AbstractStaticGraph = T() copy(g::T) where T <: AbstractStaticGraph = T(copy(g.f_vec), copy(g.f_ind)) const StaticGraphEdge = StaticEdge const StaticDiGraphEdge = StaticEdge include("staticgraph.jl") include("staticdigraph.jl") include("persistence.jl") const SGraph = StaticGraph const SDiGraph = StaticDiGraph const StaticEdgeIter{G} = Graphs.SimpleGraphs.SimpleEdgeIter{G} eltype(::Type{StaticEdgeIter{StaticGraph{T, U}}}) where T where U = StaticGraphEdge{T} eltype(::Type{StaticEdgeIter{StaticDiGraph{T, U}}}) where T where U = StaticDiGraphEdge{T} include("overrides.jl") end # module
StaticGraphs
https://github.com/JuliaGraphs/StaticGraphs.jl.git
[ "MIT" ]
0.3.0
855371d8fdfaed46dbb32a7c57a42db4441b9247
code
2418
import Graphs.LinAlg: adjacency_matrix import Graphs: induced_subgraph adjacency_matrix(g::StaticGraph{I,U}, T::DataType; dir = :out!) where I<:Integer where U<:Integer = SparseMatrixCSC{T,I}(nv(g), nv(g), g.f_ind, g.f_vec, ones(T, ne(g)*2)) function adjacency_matrix(g::StaticDiGraph{I,U}, T::DataType; dir = :out) where I<:Integer where U<:Integer if dir == :in return SparseMatrixCSC{T,I}(nv(g), nv(g), g.f_ind, g.f_vec, ones(T, ne(g)*2)) end z = SparseMatrixCSC{T,I}(nv(g), nv(g), g.b_ind, g.b_vec, ones(T, ne(g))) dir != :out && @warn("direction `$dir` not defined for adjacency matrices on StaticGraphs; defaulting to `out`") return z end # induced subgraphs preserve the eltypes of the vertices. function induced_subgraph(g::StaticDiGraph{I, U}, vlist::AbstractVector{T}) where T <: Integer where I <: Integer where U<:Integer vlist_len = length(vlist) f_vec = Vector{I}() b_vec = Vector{I}() f_ind = Vector{U}([1]) b_ind = Vector{U}([1]) let vset = I.(vlist) # needed because of julialang/julia/ issue #15276 sizehint!(f_ind, vlist_len+1) sizehint!(b_ind, vlist_len+1) vlist_len == length(vset) || throw(ArgumentError("Vertices in subgraph list must be unique")) fpos = 1 bpos = 1 @inbounds for v in vlist o = filter(x -> x in vset, outneighbors(g, v)) i = filter(x -> x in vset, inneighbors(g, v)) fpos += length(o) bpos += length(i) append!(f_vec, o) append!(b_vec, i) push!(f_ind, fpos) push!(b_ind, bpos) end end return StaticDiGraph(f_vec, f_ind, b_vec, b_ind), T.(vlist) end function induced_subgraph(g::StaticGraph{I, U}, vlist::AbstractVector{T}) where T <: Integer where I <: Integer where U<:Integer vlist_len = length(vlist) f_vec = Vector{I}() f_ind = Vector{U}([1]) let vset = I.(vlist) # needed because of julialang/julia/ issue #15276 sizehint!(f_ind, vlist_len + 1) vlist_len == length(vset) || throw(ArgumentError("Vertices in subgraph list must be unique")) fpos = 1 for v in vlist o = filter(x -> x in vset, outneighbors(g, v)) fpos += length(o) append!(f_vec, o) push!(f_ind, fpos) end end return StaticGraph(f_vec, f_ind), T.(vlist) end
StaticGraphs
https://github.com/JuliaGraphs/StaticGraphs.jl.git