Skip to main content

Sensitivity analysis in C#

using BayesServer.Analysis;
using BayesServer.Inference;
using BayesServer.Inference.RelevanceTree;
using System;
using System.Collections.Generic;
using System.Text;

namespace BayesServer.HelpSamples
{
public static class SensitivityAnalysisExample
{
public static void Main()
{
var network = new Network();

// TODO download the network from the Bayes Server User Interface (or Bayes Server Online)
// and adjust the following path
network.Load(@"Asia.bayes");

var visitToAsia = network.Variables["Visit to Asia", true];
var hasLungCancer = network.Variables["Has Lung Cancer", true];
var tuberculosisOrCancer = network.Variables["Tuberculosis or Cancer", true];
var smoker = network.Variables["Smoker", true];
var hasTuberculosis = network.Variables["Has Tuberculosis", true];
var dyspnea = network.Variables["Dyspnea", true];
var xRayResult = network.Variables["XRay Result", true];
var hasBronchitis = network.Variables["Has Bronchitis", true];

var xRayResultAbnormal = xRayResult.States["Abnormal", true];
var smokerFalse = smoker.States["False", true];
var hasLungCancerFalse = hasLungCancer.States["False", true];

var evidence = new Evidence(network);

// TODO set any evidence here if you need to...


var sensitivity = new SensitivityToParameters(network, new RelevanceTreeInferenceFactory());

var parameter = new ParameterReference(hasLungCancer.Node, new State[] {smokerFalse, hasLungCancerFalse });

var oneWay = sensitivity.OneWay(
evidence,
xRayResultAbnormal,
parameter
);

Console.WriteLine($"Parameter value = {oneWay.ParameterValue}");
Console.WriteLine($"Sensitivity value = {oneWay.SensitivityValue}");
Console.WriteLine($"P(Abnormal | e) = {oneWay.ProbabilityHypothesisGivenEvidence}");
Console.WriteLine($"Alpha = {oneWay.Alpha}");
Console.WriteLine($"Beta = {oneWay.Beta}");
Console.WriteLine($"Delta = {oneWay.Delta}");
Console.WriteLine($"Gamma = {oneWay.Gamma}");

Console.WriteLine($"Eval(0.2) = {oneWay.Evaluate(0.2)}");
Console.WriteLine($"Eval'(0.2) = {oneWay.EvaluateDeriv(0.2)}");


// Expected output...

// Parameter value = 0.99
// Sensitivity value = -0.460164
// P(Abnormal | e) = 0.11029004
// Alpha = -0.460164
// Beta = 0.5658524
// Delta = 1
// Gamma = 0
// Eval(0.2) = 0.4738196
// Eval'(0.2) = -0.460164

}
}
}