### Build and Run Example on Linux Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/readme.txt Use these commands to build and run the example on a Linux system. Ensure CMake and a C++ compiler are installed. ```bash mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=Releas make ./example ``` -------------------------------- ### CMakeLists.txt Configuration for aGrUM Project Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/howtos/using_agrum.dox This CMakeLists.txt file sets up a project named 'EXAMPLE' and configures it to find and use the aGrUM library. Ensure AGRUM_INSTALLATION_DIRECTORY points to your aGrUM installation. ```cmake project(FOO) # do not forget to change "FOO", "FOO_SOURCE" and "FOO_SOURCE_DIR" with the name of your project # do not forget to change the target "foo" with the name of your executable cmake_minimum_required(VERSION 3.13) # make RELEASE the default option if(NOT DEFINED CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release) endif() project(EXAMPLE) # do not forget to change this line: the path where you installed aGrUM with ("act install -d...") set(AGRUM_INSTALLATION_DIRECTORY "/home/xxx/usr") set(aGrUM_DIR "${AGRUM_INSTALLATION_DIRECTORY}/lib/cmake/aGrUM/") find_package(aGrUM CONFIG REQUIRED) file(GLOB_RECURSE FOO_SOURCE ${FOO_SOURCE_DIR}/src/*.cpp) add_executable (foo ${FOO_SOURCE}) target_include_directories (foo PRIVATE src) # here we link to agrumBASE since we're only using the base component target_link_libraries (foo PRIVATE agrumBASE) # (in this folder) # to compile release version # # cmake -DCMAKE_BUILD_TYPE=RELEASE -B build . # cmake --build build # # to compile debug version # # cmake -DCMAKE_BUILD_TYPE=Debug -B build_debug . # cmake --build build_debug # ``` -------------------------------- ### Build and Run Example on Windows Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/readme.txt Use these commands to build and run the example on a Windows system using CMake and MSBuild. Alternatively, open the EXAMPLE.sln file in Visual C++. ```batch mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=Release MSBuild.exe .\EXAMPLE.sln /property:Configuration=Release .\Release\example.exe ``` -------------------------------- ### BNMixture Inference Setup Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/73-PyModels_BNMixture.ipynb Initializes BNMixture inference with a specified engine and performs inference to get the posterior distribution of a target variable. ```python bnm_ie = BNM.BNMixtureInference(bnm, engine=gum.LazyPropagation) bnm_ie.makeInference() p = bnm_ie.posterior("C") p0 = gum.getPosterior(bn0, target="C", evs={}) p1 = gum.getPosterior(bn1, target="C", evs={}) p2 = gum.getPosterior(bn2, target="C", evs={}) ``` -------------------------------- ### Create and Display BayesNet (Example 3) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Creates a BayesNet with a back-door path and displays it. This example demonstrates a scenario where a back-door set can be found. ```python e3 = gum.fastBN("B->X->Y;X->A<-B->Y") e3 ``` ```text (pyagrum.BayesNet@0x7fff91200) BN{nodes: 4, arcs: 5, domainSize: 16, dim: 11, mem: 176o} ``` -------------------------------- ### Create and Display BayesNet (Example 2) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Creates and displays a more complex BayesNet. This example also has no back-door paths between X and Y. ```python e2 = gum.fastBN("A->B->C;A->X->E->Y;B<-D->E") e2 ``` ```text (pyagrum.BayesNet@0x7fff90c00) BN{nodes: 7, arcs: 7, domainSize: 128, dim: 16, mem: 256o} ``` -------------------------------- ### System-Wide aGrUM Installation Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/howtos/installing_agrum.dox Install aGrUM system-wide using root privileges. ```bash sudo act install release agrum ``` -------------------------------- ### Install pyAgrum using pip Source: https://gitlab.com/agrumery/agrum/-/blob/master/README.md Use this command to install the pyAgrum library via pip. This is the standard method for Python package installation. ```bash pip install pyagrum ``` -------------------------------- ### Project Setup and aGrUM Integration Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/o3prm/prmBNReader/CMakeLists.txt This CMake script configures a project to use the aGrUM/pyAgrum library. It sets the minimum required CMake version, defines the installation directory for aGrUM, and attempts to find the aGrUM package. If aGrUM is not found, the build fails. ```cmake project(PRMBNREADER) cmake_minimum_required(VERSION 2.8) set(AGRUM_INSTALLATION_DIRECTORY "~/usr") message(STATUS "aGrUM installation path : ${AGRUM_INSTALLATION_DIRECTORY} ") if (NOT DEFINED aGrUM_DIR) set(aGrUM_DIR "${AGRUM_INSTALLATION_DIRECTORY}/lib/cmake/aGrUM/") endif () find_package(aGrUM NO_MODULE) if (aGrUM_FOUND) include(${AGRUM_USE_FILE}) else (aGrUM_FOUND) message(FATAL_ERROR "Please install aGrUM") endif (aGrUM_FOUND) ``` -------------------------------- ### Create and Display BayesNet (Example 1) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Creates a simple BayesNet representing causal relationships and displays its structure. This example has no back-door paths. ```python e1 = gum.fastBN("X->A->Y;A->B") e1 ``` ```text (pyagrum.BayesNet@0x7fff90600) BN{nodes: 4, arcs: 3, domainSize: 16, dim: 7, mem: 112o} ``` -------------------------------- ### User-Wide aGrUM Installation Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/howtos/installing_agrum.dox Install aGrUM for the current user in a specified directory (e.g., ~/usr). ```bash act install release agrum -d ~/usr ``` -------------------------------- ### Add Evidence and Perform Inference in C++ Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/howtos/using_bn.dox Demonstrates adding evidence to a Bayes Net and performing inference to get posterior probabilities. Requires prior setup of BayesNetInference and BayesNet objects. ```cpp // We can add some evidence // Index 0 is False, 1 True ie.addEvidence("B", "middle"); ie.makeInference(); for (const auto& idn : bn.nodes()) { const auto name = bn.variable(idn).name(); std::cout << name << " : " << ie.posterior(name) << std::endl; } auto updated_marginal = ie.posterior("A"); std::cout << updated_marginal << std::endl; ``` -------------------------------- ### HashTable Usage Example Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/modules/data_structures.dox Demonstrates various operations on HashTable, including creation, insertion, access, modification, and iteration. Ensure necessary headers are included before use. ```cpp // creation of an empty hash table HashTable table1; // insert two elements into the hash table table1.insert (10,"xxx"); table1.insert (20,"yyy"); table1.emplace (30,"zzz"); // creation of a nonempty hashtable using initializer lists HashTable table { std::make_pair (3,true), std::make_pair(2,false) }; // display the content of the hash table cerr << table1; // get the number of elements stored into the hash table cerr << "number of elements in table1 = " << table1.size () << endl; // create two copies of the hash table HashTable table2, table3 = table1; table2 = table3; // get the element whose key is 10 cerr << table1[10] << " = xxx" << endl; // check whether there exists an element with key 20 if (table1.exists (20)) cerr << "element found" << endl; // transform the hashtable of string into a hashtable of int assuming f is // defined as: int f (const string& str) { return str.size (); } HashTable table = table1.map (f); // remove two elements from table1 and table2 table1.erase (10); // key = 10 table1.eraseByVal ("yyy"); // val = "yyy" table2.clear (); // check whether the hash table is empty if (!table1.empty ()) cerr << "table not empty" << endl; // check wether hashtables contain the same elements if ((table1 == table2) && (table1 != table3)) cerr << "check for equality/inequality" << endl; // parse the content of a hashtable using an unsafe iterator for (HashTable::const_iterator iter = table1.cbegin(); iter != table1.cend(); ++iter) cerr << *iter; HashTable::iterator iter = table1.begin(); iter += 2; cerr << iter.key () << " " << iter.val (); // use an iterator to point the element we wish to erase HashTable::iterator_safe iterS = table1.beginSafe (); table1.erase ( table1.beginSafe () + 4 ); table1.erase ( iterS ); // this is safe because the iterator is safe // check for iterator's safety for (HashTable::iterator_safe iter = table1.beginSafe (); iter != table1.endSafe (); ++iter ) table1.eraseByVal ( *iter ); ``` -------------------------------- ### Create and Display BayesNet (Example 4) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Creates a BayesNet with multiple paths, including potential back-door paths, and displays its structure. ```python e4 = gum.fastBN("X<-A->B<-C->Y") e4 ``` ```text (pyagrum.BayesNet@0x7fff91800) BN{nodes: 5, arcs: 4, domainSize: 32, dim: 10, mem: 160o} ``` -------------------------------- ### Test aGrUM Installation Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/howtos/installing_agrum.dox Run all tests for the aGrUM release to ensure a correct installation. ```bash act test release agrum -t all ``` -------------------------------- ### Example ACT Command: Test pyAgrum Source: https://gitlab.com/agrumery/agrum/-/blob/master/README.md An example of how to use the ACT tool to run tests for the pyAgrum wrapper in release mode. This command is used to verify the integrity of the pyAgrum build. ```bash act test release pyAgrum ``` -------------------------------- ### Heap Usage Examples Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/modules/data_structures.dox Demonstrates the creation and manipulation of Heap objects. Supports custom comparators for ordering and various methods for insertion, deletion, and access. ```C++ // create a heap of integers, the top element is the smallest element Heap heap1; // create a heap of floats, the top element is the greatest Heap< float,std::greater > heap2; // insert elements into the heap heap1.insert (8); heap1.insert (10); heap1.insert (2); heap1.insert (23); heap1.insert (24); heap1.insert (10); heap1.insert (10); // copy a heap into another heap Heap heap2 = heap1; // get the number of elements of the heap std::cerr << heap2.size() << std::endl; // get the top element but do not remove it std::cerr << heap2.top() << std::endl; // get and remove the top element of the heap std::cerr << heap2.pop() << std::endl; // remove the top element but do not return it (faster than above) heap2.eraseTop(); // erase in heap1 value 8 heap1.eraseByVal (8); // erase element at position 3 (see function erase for the meaning of // position 3) heap1.erase (3); // get the element at position 3 heap1[3]; // check whether element 24 belongs to the heap heap1.contains (24); ``` -------------------------------- ### Display Causal Model (Example 2) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Displays the causal model structure for the second example using the gnb.show function. ```python m2 = csl.CausalModel(e2) gnb.show(m2) ``` ```text ``` -------------------------------- ### Get and Set BNMixture Weights Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/73-PyModels_BNMixture.ipynb Demonstrates how to retrieve names, weights, and size of a BNMixture, set a specific weight, and then re-query the updated weights. ```python print("names : ", bnm.names()) print("weights : ", bnm.weights()) print("size : ", bnm.size()) bnm.setWeight("bn0", 1.1) print("new weight of nb0 : ", bnm.weight("bn0")) print("weights after change : ", bnm.weights()) ``` -------------------------------- ### List Creation and Manipulation Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/modules/data_structures.dox Examples of creating and modifying List objects. Includes adding elements at the front and back, inserting at specific positions, and accessing elements. ```C++ // creation of an empty list List list1; List list2 { 3, 4, 5 }; // initializer list // adding elements to the list list1.pushFront (23); list1.pushBack (10); list1 += 25; list1.insert (12); list.emplaceBack (22); list.emplaceFront (10); // getting the second element of the list cerr << "10 = " << list1[2] << endl; // getting the first and last elements cerr << "first = " << list1.front() << " last = " << list1.back() << endl; // get the number of elements in the list cerr << "number of elements = " << list1.size () << endl; // display the content of the list cerr << list1 << endl; // copy the list List list2 = list1, list3; list3 = list1; // delete the second element from the list ``` -------------------------------- ### Interactive Program Startup Notice (GNU GPL) Source: https://gitlab.com/agrumery/agrum/-/blob/master/LICENSES/LGPL-3.0-or-later.txt For programs with terminal interaction, display this notice upon startup to inform users about the program's copyright, warranty status, and redistribution terms, referencing 'show w' and 'show c' commands for details. ```text Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. ``` -------------------------------- ### Visualize Bayesian Networks in Jupyter Notebooks Source: https://context7.com/agrumery/agrum/llms.txt Provides examples of using pyAgrum's notebook utilities to display Bayesian Network structures, inference results, CPTs, causal models, and influence diagrams. Also shows how to get HTML representations. ```python import pyagrum as gum import pyagrum.lib.notebook as gnb # Create a BN bn = gum.fastBN("Cloudy->Sprinkler->WetGrass<-Rain<-Cloudy") # Display the BN structure gnb.showBN(bn, size="8") # Show with inference results ie = gum.LazyPropagation(bn) ie.setEvidence({"WetGrass": 1}) ie.makeInference() # Display BN with posteriors gnb.showInference(bn, ie, size="10") # Show specific CPTs gnb.showPotential(bn.cpt("WetGrass")) # Display causal model import pyagrum.causal as causal cm = causal.CausalModel(bn, [("U", ["Cloudy", "Rain"])] ) gnb.showCausalModel(cm) # Show influence diagram diag = gum.fastID("Weather->*Forecast->$Umbrella->Utility<-Weather") gnb.showInfluenceDiagram(diag) # ROC curves for classifiers import pyagrum.lib.bn2roc as bn2roc # bn2roc.showROC_PR(bn, "data.csv", "Target", "1") # Get HTML representation (for non-notebook use) html = gnb.getBN(bn) html_inference = gnb.getInference(bn, ie) ``` -------------------------------- ### Initialize Trace and Model Files in C++ Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/MDPtest/spimddi.txt Opens output files for tracing simulation data and model generation. Ensures files are truncated if they already exist. Returns early if file opening fails. ```cpp std::ofstream traceFile; std::stringstream traceFileName; traceFileName << traceFilePath << "." << sdynaInstanceName.str() << "." << nbTest << ".csv"; traceFile.open ( traceFileName.str(), std::ios::out | std::ios::trunc ); if ( !traceFile ) { return; } std::ofstream modelFile; std::stringstream modelFileName; modelFileName << traceFilePath << "." << sdynaInstanceName.str() << "." << nbTest << ".model.dot"; modelFile.open ( modelFileName.str(), std::ios::out | std::ios::trunc ); if ( !modelFile ) { return; } ``` -------------------------------- ### Import necessary libraries Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/16-Examples_BayesianBetaCoin.ipynb Imports essential libraries for numerical operations, statistical distributions, and the aGrUM Bayesian network library. Ensure these are installed before running. ```python import time from pylab import * import scipy.stats import pyagrum as gum import pyagrum.lib.notebook as gnb ``` -------------------------------- ### Initialize and Compare Classifiers Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/53-Classifier_CompareClassifiersWithSklearn.ipynb Sets up a list of classifiers including KNeighborsClassifier, SVC, GaussianProcessClassifier, DecisionTreeClassifier, RandomForestClassifier, MLPClassifier, AdaBoostClassifier, GaussianNB, QuadraticDiscriminantAnalysis, and BNClassifier. These are then used with provided datasets and names for comparison. ```python names = [ "Nearest Neighbors", "Linear SVM", "RBF SVM", "Gaussian Process", "Decision Tree", "Random Forest", "Neural Net", "AdaBoost", "Naive Bayes", "QDA", "BNClassifier", ] classifiers = [ KNeighborsClassifier(3), SVC(kernel="linear", C=0.025), SVC(gamma=2, C=1), GaussianProcessClassifier(1.0 * RBF(1.0)), DecisionTreeClassifier(max_depth=5), RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1), MLPClassifier(alpha=1, max_iter=1000), AdaBoostClassifier(), GaussianNB(), QuadraticDiscriminantAnalysis(), BNClassifier( learningMethod="MIIC", prior="Smoothing", priorWeight=0.01, discretizationNbBins=5, discretizationStrategy="kmeans", # 'kmeans', 'uniform', 'quantile', 'NML', 'MDLP', 'CAIM', 'NoDiscretization' usePR=False, ), ] bnres = showComparison(names, classifiers, datasets, datasets_name) ``` -------------------------------- ### Build prm_run with CMake Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/o3prm/prm_run/README.txt Configure and build the prm_run project using CMake after installing aGrUM. Specify installation prefix and aGrUM installation path. ```bash cd path/to/prm_run/root/dir mkdir build cd build cmake .. -DCMAKE_INSTALL_PREFIX=/where/you/want/to/install/it -DCMAKE_PREFIX_PATH=/where/you/installed/agrum/ make install ``` -------------------------------- ### Install pyAgrum using conda Source: https://gitlab.com/agrumery/agrum/-/blob/master/README.md Use this command to install the pyAgrum library via conda, specifying the conda-forge channel. This is an alternative installation method for users managing environments with conda. ```bash conda install -c conda-forge pyagrum ``` -------------------------------- ### Initialize SDyna Instances Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/MDPtest/spimddi.txt This code demonstrates how to instantiate different types of SDyna algorithms within the Agrum framework. It iterates through various SDyna implementations, including SPIMDDI, SPITI, and different RMax variants. ```cpp #define xstrfy(s) strfy(s) #define strfy(x) #x #define GET_PATH_STR(x) xstrfy(GUM_SRC_PATH) "/run/ressources/" #x void run( gum::AbstractSimulator& sim, const std::string traceFilePath){ for( gum::Idx sdyi = 2; sdyi < 6; sdyi++ ){ std::stringstream sdynaInstanceName; switch(sdyi){ case 0 : sdynaInstanceName << "SPIMDDI"; break; case 1 : sdynaInstanceName << "SPITI"; break; case 2 : sdynaInstanceName << "AbstractRMaxMDD"; break; case 3 : sdynaInstanceName << "AbstractRMaxTree"; break; case 4 : sdynaInstanceName << "RMaxMDD"; break; case 5 : sdynaInstanceName << "RMaxTree"; break; } for( gum::Idx nbTest = 0; nbTest < 20; ++nbTest) { gum::SDYNA* spim; switch(sdyi){ case 0 : spim = gum::SDYNA::spimddiInstance(); break; case 1 : spim = gum::SDYNA::spitiInstance(); break; case 2 : spim = gum::SDYNA::AbstractRMaxMDDInstance(); break; case 3 : spim = gum::SDYNA::AbstractRMaxTreeInstance(); break; case 4 : spim = gum::SDYNA::RMaxMDDInstance(); break; case 5 : spim = gum::SDYNA::RMaxTreeInstance(); break; } std::cout << "Test n° : " << nbTest << std::endl; gum::Idx nbIte = 0; double rDisc = 0.0; // ********************************************************************************************* // Initialisation des divers objets // ********************************************************************************************* // Enregistrement des actions possibles auprès de SPIMDDI for( auto actionIter = sim.beginActions(); actionIter != sim.endActions(); ++actionIter){ //std::cout << *actionIter << " " << sim.actionName(*actionIter) << std::endl; spim->addAction( *actionIter, sim.actionName(*actionIter)); } // Enregistrement des variables caractérisant les états auprès de SPIMDDI for(auto varIter = sim.beginVariables(); varIter != sim.endVariables(); ++varIter){ spim->addVariable(*varIter); } sim.setInitialStateRandomly(); spim->initialize(sim.currentState()); // ====================================================================================== // Création du checker détat visité // ====================================================================================== gum::StatesChecker sc; sc.reset(sim.currentState()); // ====================================================================================== // Ouverture des fichiers de traces ``` -------------------------------- ### Initialize BNLearner with sample data Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/31-Learning_structuralLearning.ipynb Initializes the BNLearner with the generated sample data. The existing Bayesian Network 'bn' is used as a template for variable definitions. The learner's configuration is then printed. ```python learner = gum.BNLearner("out/sample_asia.csv", bn) # using bn as template for variables print(learner) ``` -------------------------------- ### Smart Pointer Usage Example (RefPtr) Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/modules/utilities.dox Demonstrates the creation, copying, clearing, modification, and comparison of RefPtr smart pointers. Ensure pointers are heap-allocated and not manually deallocated when passed to RefPtr. ```cpp // creation of smart pointer RefPtr ptr1 (new int (4)); // copying (and sharing) this pointer into new smart pointers RefPtr ptr2 = ptr1, ptr3; ptr3 = ptr1; // make ptr2 point toward nothing (this does not deallocate int (4) as it is // pointed to by ptr1 and ptr3) ptr2.clear (); // modifying the value pointed to by the dumb pointer contained in ptr1 *ptr1 = 5; // print the content of ptr3 cerr << *ptr3 << " = 5" << endl; // check whether ptr1 and ptr3 reference the same dumb pointer if (ptr1 == ptr3) cerr << "reference the same dumb pointer" << endl; // check whether ptr1 and ptr2 contain a dumb pointer if (ptr1 && !ptr2) cerr << "check containers" << endl; ``` -------------------------------- ### Display Agrum Installation Path Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/config.txt Logs the determined installation path for Agrum during the CMake configuration process. ```cmake message(STATUS "aGrUM installation path : ${AGRUM_INSTALLATION_DIRECTORY} ") ``` -------------------------------- ### Scikit-learn example source attribution Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/53-Classifier_CompareClassifiersWithSklearn.ipynb Provides attribution for the scikit-learn example code source and modification details. ```python # From https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html) # Code source: Gael Varoquaux Andreas Muller # Modified for documentation by Jaques Grobler # License: BSD 3 clause ``` -------------------------------- ### Build aGrUM using ACT Commands Source: https://gitlab.com/agrumery/agrum/-/blob/master/README.md Demonstrates the general syntax for using the ACT build tool. ACT is used for managing the build process of aGrUM and its wrappers. ```bash act [target] [version] [action] ``` -------------------------------- ### Create and Populate BootstrapMixture Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/73-PyModels_BNMixture.ipynb Demonstrates the creation of a BootstrapMixture with a reference BN and adding other BNs with specified weights. ```python bnm_boot = BNM.BootstrapMixture("bn0", bn0) bnm_boot.add("bn1", bn1, w=1.0) bnm_boot.add("bn2", bn2, w=2.0) print(bnm_boot) ``` -------------------------------- ### Set Agrum Installation Directory Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/config.txt Configures the installation directory for Agrum. It defaults to a virtual environment path if not explicitly set. ```cmake # add here the installation directory for agrum # do not forget to change this line if needed ("act install -d...") # system-wide # set(AGRUM_INSTALLATION_DIRECTORY "/usr") if (NOT DEFINED AGRUM_INSTALLATION_DIRECTORY) set(AGRUM_INSTALLATION_DIRECTORY "~/virtualenvs/devAgrum") endif () ``` -------------------------------- ### Set Creation and Iteration Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/modules/data_structures.dox Shows how to create a set with initial elements, add elements using the << operator, and iterate through the set to display its values. Requires including the 'Set' header. ```cpp // creation of a set with 10 elements Set set; for (int i = 0; i< 10; ++i) set< set2 { 1, 2, 3 }; // parse the set for (auto iter = set.begin (); iter != set.end (); ++iter) { // display the values cerr << *iter << endl; } ``` -------------------------------- ### Find Back-Door Set (Example 2) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Determines the back-door set for (X, Y) in the second example. As with the first, no such set exists. ```python # This function returns the set of variables which satisfies the back-door criterion for (X, Y) # None if there are no back-door paths. setOfVars = m2.backDoor("X", "Y") print("The set of variables which satisfies the back-door criterion for (X, Y) is :", setOfVars) ``` ```text The set of variables which satisfies the back-door criterion for (X, Y) is : None ``` -------------------------------- ### Queue Operations Example Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/modules/data_structures.dox Demonstrates basic operations on a queue, including accessing and removing the top element, and outputting the queue's content. Note the difference between `eraseTop` and `pop`. ```cpp // get the top element, then remove it std::cerr << queue2.top() << std::endl; queue2.eraseTop(); // get the top element, then remove it std::cerr << queue2.pop() << std::endl; // output the content of the queue std::cerr << queue1 << std::endl; // change the priority of the element at position 3 Size new_pos=queue1.setPriorityByPos (3,100); // change the priority of all instances of element "AAA" queue1.setPriority ("AAA",100); ``` -------------------------------- ### Prepare for Quantile Discretization Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/pyAgrum/notebooks/irisClassifier.ipynb Initializes numpy and sets up a discretization parameter for potential use with pandas.qcut. The 'disc' variable controls the number of bins. ```python import numpy disc=6 # Disc(retization) may be between 2 and 9 r=numpy.array(range(disc+1))/(1.0*disc) # quantiles are building using pandas.qcut ``` -------------------------------- ### Find Back-Door Set (Example 3) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Identifies the back-door set for (X, Y) in the third example. The output shows that {'B'} satisfies the criterion. ```python # This function returns the set of variables which satisfies the back-door criterion for (X, Y) # None if there are no back-door paths. setOfVars = m3.backDoor("X", "Y") print("The set of variables which satisfies the back-door criterion for (X, Y) is :", setOfVars) ``` ```text The set of variables which satisfies the back-door criterion for (X, Y) is : {'B'} ``` -------------------------------- ### Visualize Causal Impact (Example 3) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Visualizes the causal impact of X on Y for the third example. The presence of a back-door path influences the interpretation. ```python m3 = csl.CausalModel(e3) cslnb.showCausalImpact(m3, "Y", doing="X", values={}) ``` ```text ``` -------------------------------- ### Initialize aGrUM Source and Version Directories Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/CMakeLists.txt Sets the source directory for aGrUM and the location of the version file. Includes the version file and configuration settings. ```cmake set(AGRUM_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../src") set(AGRUM_FILE_VERSION "${CMAKE_CURRENT_SOURCE_DIR}/../../VERSION.txt") include(${AGRUM_FILE_VERSION}) include("${AGRUM_SOURCE_DIR}/cmake/Config.agrum.cmake") configure_file("${AGRUM_SOURCE_DIR}/cmake/config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/agrum/config.h") ``` -------------------------------- ### Visualize Causal Impact (Example 2) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Visualizes the causal impact of X on Y for the second example. Similar to the first, no back-door paths are identified. ```python cslnb.showCausalImpact(m2, "Y", doing="X", values={}) ``` ```text ``` -------------------------------- ### Run Factory FMDP Simulation in C++ Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/MDPtest/spimddi.txt Initializes a simulation using the 'tiny-factory.dat' FMDP dataset. This snippet is incomplete and likely intended for further configuration. ```cpp void runFactory(){ // ********************************************************************************************* // Chargement du fmdp servant de base // ********************************************************************************************* gum::FMDPSimulator sim(GET_PATH_STR ( FMDP/factory/tiny-factory.dat )); // gum::Instantiation theEnd; // for(gum::SequenceIteratorSafe varIter = sim.beginVariables(); varIter != sim.endVariables(); ++varIter) // if( (*varIter)->name().compare("connected")){ // theEnd.add(**varIter); // theEnd.chgVal(**varIter, (*varIter)->index("yes")); ``` -------------------------------- ### Learning BNMixture with BNMLearner Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/73-PyModels_BNMixture.ipynb This snippet shows how to learn a BNMixture using multiple databases. It initializes a BNMixture, generates data from different distributions, and then trains the BNMLearner. ```python new_bn = gum.fastBN("A->C<-B") generator = gum.BNDatabaseGenerator(new_bn) data = [] weights = [1 for i in range(5)] for i in range(5): generator.drawSamples(50000) data.append(generator.to_pandas()) learner = BNM.BNMLearner(weights, data, template=new_bn) learned_bnm = learner.learnBNM() learned_bnm.updateRef() bnmnb.showMixtureGraph(learned_bnm, ref=True) print(learned_bnm) ``` -------------------------------- ### Visualize Causal Impact (Example 4) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb Visualizes the causal impact of X on Y for the fourth example. This helps in understanding the effect in a more complex causal structure. ```python m4 = csl.CausalModel(e4) cslnb.showCausalImpact(m4, "Y", doing="X", values={}) ``` ```text ``` -------------------------------- ### Display pyAgrum Version and Warranty Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/testunits/ressources/o3prm/BNO3PRMIO.ipynb Use `gum.about()` to display the installed pyAgrum version and its licensing information. This is useful for verifying the installation and understanding usage rights. ```python import pyagrum as gum gum.about() ``` -------------------------------- ### Initialize CausalShallValues Explainer Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/92-Tools-ShapAndShallValues.ipynb Initialize the CausalShallValues explainer with a Bayesian network and background data. Logging is enabled. ```python background = train.sample(100) causalExplainer = expl.CausalShallValues(bn=bn, background=(background, False), log=True) ``` -------------------------------- ### Find Back-Door Set (Example 4) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c4p150-backDoorCriterion.ipynb This code snippet is intended to find the set of variables satisfying the back-door criterion for (X, Y) in the fourth example. The output is not provided in the source. ```python # This function returns the set of variables which satisfies the back-door criterion for (X, Y) ``` -------------------------------- ### Initialize and Configure BNLearner Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/66-Causality_CausalEffectEstimation.ipynb Initializes the BNLearner with discretized data and applies NML correction and smoothing prior. Sets a specific slice order for variables to guide structure learning. ```python template = discretizer.discretizedTemplate(df) structure_learner = gum.BNLearner(df, template) structure_learner.useNMLCorrection() structure_learner.useSmoothingPrior(1e-9) structure_learner.setSliceOrder([["X3", "X1", "X2", "V1", "V2", "V3"], ["T"], ["Y"]]) learned_bn = structure_learner.learnBN() learned_causal_model = csl.CausalModel(learned_bn) print(structure_learner) ``` -------------------------------- ### Initialize DiscreteTypeProcessor Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/52-Classifier_Discretization.ipynb Initialize `DiscreteTypeProcessor` with default discretization method and number of bins. This sets up the processor for subsequent data handling and BN learning. ```python import pyagrum.lib.notebook as gnb import pyagrum.skbn as skbn file_name = "res/discretizable.csv" data = pd.read_csv(file_name) type_processor = DiscreteTypeProcessor( defaultDiscretizationMethod="quantile", defaultNumberOfBins=10, discretizationThreshold=25 ) ``` -------------------------------- ### Display pyAgrum Library Information Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/pyAgrum/notebooks/irisClassifier.ipynb Imports necessary libraries and displays basic information about the installed pyAgrum version, including copyright and warranty details. This is useful for verifying the installation and understanding the library's context. ```python %matplotlib inline from pylab import * import matplotlib.pyplot as plt import pyagrum as gum import pyagrum.lib.notebook as gnb gum.about() ``` -------------------------------- ### Learn Bayesian Networks from Data and Prior Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/34-Learning_DirichletPriorAndWeigthedDatabase.ipynb Initializes two BNLearner instances, one with the observation database and another with the Dirichlet prior database. Both learners use the BIC score for learning. The resulting Bayesian Networks are then displayed side-by-side. ```python # bnPrior is used to give the variables and their domains learnerData = gum.BNLearner(obsDatabase) learnerPrior = gum.BNLearner(dirichletDatabase) learnerData.useScoreBIC() learnerPrior.useScoreBIC() gnb.sideBySide(learnerData.learnBN(), learnerPrior.learnBN(), captions=["Learning from Data", "Learning from Prior"]) ``` -------------------------------- ### CMake Configuration for aGrUM Project Source: https://gitlab.com/agrumery/agrum/-/blob/master/apps/aGrUM/operationsWithTensors/CMakeLists.txt This CMakeLists.txt file configures a project to use the aGrUM library. It finds the library, includes necessary paths, and links the executable against aGrUM. Ensure aGrUM is installed or its installation directory is specified. ```cmake project(EXAMPLE) cmake_minimum_required(VERSION 2.8) set (CMAKE_CXX_STANDARD 14) find_package(OpenMP) if (OPENMP_FOUND) set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}") endif() include("${EXAMPLE_SOURCE_DIR}/../config.txt") if (NOT DEFINED aGrUM_DIR) set(aGrUM_DIR "${AGRUM_INSTALLATION_DIRECTORY}/lib/cmake/aGrUM/") endif () find_package(aGrUM) if (aGrUM_FOUND) include(${AGRUM_USE_FILE}) else (aGrUM_FOUND) message(FATAL_ERROR "Please install aGrUM") endif (aGrUM_FOUND) file(GLOB EXAMPLE_SOURCE ${EXAMPLE_SOURCE_DIR}/*.cpp) file(GLOB EXAMPLE_INCLUDE ${EXAMPLE_SOURCE_DIR}/*.h) add_executable (example ${EXAMPLE_SOURCE}) target_link_libraries(example agrum) install (TARGETS example DESTINATION bin) ``` -------------------------------- ### Initialize and Learn BN using MIIC Algorithm Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/32-Learning_learningClassifier.ipynb Initializes a BNLearner with training data and learns a new Bayesian Network using the Maximum Information Independent Components (MIIC) algorithm. It also records the time taken for learning. ```python # Learning a BN from the database learner = gum.BNLearner("out/train.csv") bn2 = learner.useMIIC().learnBN() currentTime = learner.currentTime() ``` -------------------------------- ### Display All Configuration Properties Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/99-Tools_configForPyAgrum.ipynb Print the entire configuration object to see all available settings and their current values. This is useful for understanding the full scope of configurable options. ```python print(gum.config) ``` -------------------------------- ### Import pyAgrum package Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/01-Tutorial_pyAgrum.ipynb Import the pyAgrum library to start using its functionalities. ```python import pyagrum as gum ``` -------------------------------- ### Managing Structure Learning Constraints Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/BNLearning.rst Define and manage constraints to guide the structure learning process. ```APIDOC ## Structure Learning Constraints ### Description Methods for adding, erasing, and setting constraints on the Bayesian network structure during learning. ### Adding Constraints - `addForbiddenArc(u, v)`: Forbids an arc from node `u` to node `v`. - `addMandatoryArc(u, v)`: Requires an arc from node `u` to node `v`. - `addNoChildrenNode(node)`: Specifies that a node cannot have children. - `addNoParentNode(node)`: Specifies that a node cannot have parents. - `addPossibleEdge(u, v)`: Allows an edge between `u` and `v`. ### Erasing Constraints - `eraseForbiddenArc(u, v)`: Removes a forbidden arc constraint. - `eraseMandatoryArc(u, v)`: Removes a mandatory arc constraint. - `eraseNoChildrenNode(node)`: Removes the no-children constraint. - `eraseNoParentNode(node)`: Removes the no-parent constraint. - `erasePossibleEdge(u, v)`: Removes a possible edge constraint. ### Setting Constraints - `setForbiddenArcs(arcs)`: Sets a list of forbidden arcs. - `setMandatoryArcs(arcs)`: Sets a list of mandatory arcs. - `setMaxIndegree(max_degree)`: Sets the maximum indegree for all nodes. - `setSliceOrder(order)`: Sets a specific order for nodes (for slice-based learning). ``` -------------------------------- ### Standard GNU GPL Notice for Source Files Source: https://gitlab.com/agrumery/agrum/-/blob/master/LICENSES/LGPL-3.0-or-later.txt Include this notice at the beginning of each source file to clearly state the program's name, copyright, and licensing terms under the GNU GPL. Ensure it points to the full license text. ```text Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` -------------------------------- ### Get Feature Contributions Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/92-Tools-ShapAndShallValues.ipynb Retrieves the feature contributions (values) from a computed local explanation object. ```python localExpl._values ``` -------------------------------- ### Clone aGrUM Repository Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/howtos/installing_agrum.dox Clone the aGrUM repository from GitLab to get the latest source code. ```bash git clone git@gitlab.com:agrumery/aGrUM.git ``` -------------------------------- ### Show CPT Configuration in pyAgrum Notebook Source: https://gitlab.com/agrumery/agrum/-/blob/master/CHANGELOG.md Introduces new configuration options for displaying (LaTeX) fractions in `gum.lib.notebook.showCPT` within pyAgrum notebooks. ```python gum.lib.notebook.showCPT ``` -------------------------------- ### Get Configuration Property as String (DynamicBN) Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/99-Tools_configForPyAgrum.ipynb Retrieves the 'dynamicBN.default_graph_size' configuration property, which is stored and returned as a string. ```python gum.config["dynamicBN", "default_graph_size"] ``` -------------------------------- ### Initialize Bayesian Network Learner Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/34-Learning_DirichletPriorAndWeigthedDatabase.ipynb Initializes a Bayesian Network learner with an observation database and a prior Bayesian Network. This is a foundational step before applying learning algorithms or priors. ```python learner = gum.BNLearner(obsDatabase, bnPrior) print(learner) ``` -------------------------------- ### Get Configuration Property as String Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/99-Tools_configForPyAgrum.ipynb Retrieves the value of a configuration property, 'notebook.default_graph_size', which is stored and returned as a string. ```python gum.config["notebook", "default_graph_size"] ``` -------------------------------- ### Initializing Bayesian Network and Learner Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/34-Learning_DirichletPriorAndWeigthedDatabase.ipynb Initializes a Bayesian Network and a BNLearner instance. The base file for data is specified. ```python bn = gum.fastBN("X->Y") bn1 = gum.BayesNet(bn) bn2 = gum.BayesNet(bn) # the base will be saved in basefile="out/dataW.csv" basefile = "out/dataW.csv" ``` -------------------------------- ### Get Potential in pyAgrum Notebook Utils Source: https://gitlab.com/agrumery/agrum/-/blob/master/CHANGELOG.md pyAgrum.lib.notebook.getPotential is used in conjunction with async_html2image for generating visualizations of potentials. ```python pyAgrum.lib.notebook.getPotential ``` -------------------------------- ### Learn Bayesian Network using Local Search with Tabu List Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/33-Learning_LearningAndEssentialGraphs.ipynb Instantiate a BNLearner with Local Search with Tabu List algorithm to learn a Bayesian Network. The learner configuration is printed, and then the essential graph is derived and displayed alongside the learned BN. ```python learner = gum.BNLearner("res/sample_asia.csv") learner.useLocalSearchWithTabuList() print(learner) bnTL = learner.learnBN() geTL = gum.EssentialGraph(bnTL) geTL gnb.sideBySide(bnTL, geTL) ``` -------------------------------- ### Get Side by Side in pyAgrum Notebook Utils Source: https://gitlab.com/agrumery/agrum/-/blob/master/CHANGELOG.md pyAgrum.lib.notebook.getSideBySide is used in conjunction with async_html2image for generating side-by-side visualizations. ```python pyAgrum.lib.notebook.getSideBySide ``` -------------------------------- ### Configure and Run Gibbs Sampling for Convergence Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/44-Inference_ApproximateInference.ipynb Configures and runs Gibbs Sampling with specified epsilon, burn-in, and period size for convergence analysis. Use this to observe the approximation scheme. ```python ie2 = gum.GibbsSampling(bn) ie2.setEpsilon(10**-1.8) ie2.setBurnIn(300) ie2.setPeriodSize(300) ie2.setDrawnAtRandom(True) gnb.animApproximationScheme(ie2) ie2.makeInference() ``` -------------------------------- ### Define Door Probabilities Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c6p178-montyHallProblem.ipynb Sets the initial probabilities for the host opening specific doors. This is a setup for the probabilistic model. ```python v2.cpt("Door opened")[{"Your Door": "1"}] = [0, 0.5, 0.5] v2.cpt("Door opened")[{"Your Door": "2"}] = [0.5, 0, 0.5] v2.cpt("Door opened")[{"Your Door": "3"}] = [0.5, 0.5, 0] ``` -------------------------------- ### Counterfactual Query - All Potential Outcomes Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/BoW-c8p251-educationAndExperience.ipynb Example demonstrating how to retrieve all potential outcomes for a counterfactual query by omitting the 'values' parameter. ```APIDOC ## Counterfactual Query - All Potential Outcomes ### Description This example shows how to use the `counterfactual` function to get all potential outcomes by not specifying the `values` parameter. ### Method ```python import pyagrum.causal as csl import pyagrum.notebook as gnb # Assuming 'edex' is a pre-defined CausalModel # cm = csl.CausalModel(edex) pot = csl.counterfactual( cm=csl.CausalModel(edex), profile={"experience": 8, "education": "low", "salary": "86"}, whatif={"education"}, on={"salary"}, ) gnb.showProba(pot) ``` ### Response This will display the probability distribution for 'salary' under different potential values of 'education', given the specified profile and intervention. ``` -------------------------------- ### MultiPriorityQueue Element Insertion and Copying Source: https://gitlab.com/agrumery/agrum/-/blob/master/src/docs/modules/data_structures.dox Demonstrates creating a MultiPriorityQueue, inserting elements with priorities, and copying the queue. ```cpp // create a priority queue of strings, the priorities of which are integers // the element at the top of the queue has the smallest priority MultiPriorityQueue queue1; // insert elements into the queue queue1.insert (8, "AAA"); queue1.insert (10, "BBB"); queue1.insert (2, "CCC"); queue1.insert (23, "DDD"); queue1.insert (24, "EEE"); queue1.insert (10, "AAA"); // copy the queue MultiPriorityQueue queue2 = queue1; ``` -------------------------------- ### Initialize an Empty CLG Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/72-PyModels_CLG.ipynb Create a new, empty CLG object. This can serve as a starting point for defining a new model. ```python # We create a simple CLG with 3 variables clg = gclg.CLG() ``` -------------------------------- ### Get Configuration Property as Integer Source: https://gitlab.com/agrumery/agrum/-/blob/master/wrappers/pyagrum/doc/sphinx/notebooks/99-Tools_configForPyAgrum.ipynb Retrieves the 'dynamicBN.default_graph_size' configuration property using the 'asInt' accessor, which returns the value as an integer. ```python gum.config.asInt["dynamicBN", "default_graph_size"] ```