Skip to content
Permalink
Browse files

further documentation, tests and refactoring

  • Loading branch information...
safiscet committed Nov 30, 2017
1 parent c145c89 commit bf812ed72c4be88b953164b9299c2dcb165b3b04
@@ -1,6 +1,7 @@
namespace SafetySharp.CaseStudies.RailroadCrossing.Analysis
{
using System;
using System.Collections.Generic;
using Bayesian;
using ISSE.SafetyChecking;
using ISSE.SafetyChecking.Modeling;
@@ -15,10 +16,10 @@ class BayesianAnalysis
public void ConstraintBased()
{
var model = new Model();
model.Channel.MessageDropped.ProbabilityOfOccurrence = new Probability(0.0001);
model.Channel.MessageDropped.ProbabilityOfOccurrence = new Probability(0);
model.CrossingController.Motor.BarrierMotorStuck.ProbabilityOfOccurrence = new Probability(0.001);
model.CrossingController.Sensor.BarrierSensorFailure.ProbabilityOfOccurrence = new Probability(0.00003);
model.CrossingController.TrainSensor.ErroneousTrainDetection.ProbabilityOfOccurrence = new Probability(0.0002);
model.CrossingController.TrainSensor.ErroneousTrainDetection.ProbabilityOfOccurrence = new Probability(0);
model.TrainController.Brakes.BrakesFailure.ProbabilityOfOccurrence = new Probability(0.00002);
model.TrainController.Odometer.OdometerPositionOffset.ProbabilityOfOccurrence = new Probability(0.02);
model.TrainController.Odometer.OdometerSpeedOffset.ProbabilityOfOccurrence = new Probability(0.02);
@@ -28,21 +29,32 @@ public void ConstraintBased()
&&
(model.Train.Position <= Model.CrossingPosition &&
model.Train.Position + model.Train.Speed > Model.CrossingPosition);
Func<bool> timerHasElapsed = () => model.CrossingController.Timer.HasElapsed;
Func<bool> brakesActive = () => model.TrainController.Brakes.Acceleration == -1;
var states = new Dictionary<string, Func<bool>> { /*["TimerHasElapsed"] = timerHasElapsed, ["BrakesActive"] = brakesActive */ };
var faults = new[]
{
model.CrossingController.Motor.BarrierMotorStuck,
model.CrossingController.Sensor.BarrierSensorFailure,
model.TrainController.Brakes.BrakesFailure,
model.TrainController.Odometer.OdometerPositionOffset,
model.TrainController.Odometer.OdometerSpeedOffset
};

var config = BayesianLearningConfiguration.Default;
config.MaxConditionSize = 1;
var bayesianCreator = new BayesianNetworkCreator(model, 50, config);
bayesianCreator.LearnConstraintBasedBayesianNetwork(hazard);
config.MaxConditionSize = 0;
var bayesianCreator = new BayesianNetworkCreator(model, 230, config);
bayesianCreator.LearnConstraintBasedBayesianNetwork(hazard, null, faults);
}

[Test]
public void ScoreBased()
{
var model = new Model();
model.Channel.MessageDropped.ProbabilityOfOccurrence = new Probability(0.0001);
model.Channel.MessageDropped.ProbabilityOfOccurrence = new Probability(0);
model.CrossingController.Motor.BarrierMotorStuck.ProbabilityOfOccurrence = new Probability(0.001);
model.CrossingController.Sensor.BarrierSensorFailure.ProbabilityOfOccurrence = new Probability(0.00003);
model.CrossingController.TrainSensor.ErroneousTrainDetection.ProbabilityOfOccurrence = new Probability(0.0002);
model.CrossingController.TrainSensor.ErroneousTrainDetection.ProbabilityOfOccurrence = new Probability(0);
model.TrainController.Brakes.BrakesFailure.ProbabilityOfOccurrence = new Probability(0.00002);
model.TrainController.Odometer.OdometerPositionOffset.ProbabilityOfOccurrence = new Probability(0.02);
model.TrainController.Odometer.OdometerSpeedOffset.ProbabilityOfOccurrence = new Probability(0.02);
@@ -52,11 +64,48 @@ public void ScoreBased()
&&
(model.Train.Position <= Model.CrossingPosition &&
model.Train.Position + model.Train.Speed > Model.CrossingPosition);
Func<bool> timerHasElapsed = () => model.CrossingController.Timer.HasElapsed;
Func<bool> brakesActive = () => model.TrainController.Brakes.Acceleration == -1;
var states = new Dictionary<string, Func<bool>> { /*["TimerHasElapsed"] = timerHasElapsed, ["BrakesActive"] = brakesActive */ };
var faults = new[]
{
model.CrossingController.Motor.BarrierMotorStuck,
model.CrossingController.Sensor.BarrierSensorFailure,
model.TrainController.Brakes.BrakesFailure,
model.TrainController.Odometer.OdometerPositionOffset,
model.TrainController.Odometer.OdometerSpeedOffset
};

var config = BayesianLearningConfiguration.Default;
config.UseRealProbabilitiesForSimulation = false;
var bayesianCreator = new BayesianNetworkCreator(model, 50, config);
bayesianCreator.LearnScoreBasedBayesianNetwork(@"D:\Sonstiges\SafetySharpSimulation", 20000000, hazard);
config.UseRealProbabilitiesForSimulation = true;
var bayesianCreator = new BayesianNetworkCreator(model, 230, config);
bayesianCreator.LearnScoreBasedBayesianNetwork(@"C:\SafetySharpSimulation\", 50000000, hazard, states, faults);
}

[Test]
public void CalculateProbabilities()
{
const string networkPath = @"Analysis/network.json";
var model = new Model();
Func<bool> hazard = () => (model.Barrier.Angle != 0)
&&
(model.Train.Position <= Model.CrossingPosition &&
model.Train.Position + model.Train.Speed > Model.CrossingPosition);
var faults = new[]
{
model.CrossingController.Motor.BarrierMotorStuck,
model.CrossingController.Sensor.BarrierSensorFailure,
model.TrainController.Brakes.BrakesFailure,
model.TrainController.Odometer.OdometerPositionOffset,
model.TrainController.Odometer.OdometerSpeedOffset
};

var bayesianCreator = new BayesianNetworkCreator(model, 230);
var network = bayesianCreator.FromJson(networkPath, hazard, null, faults);
var calculator = new BayesianNetworkProbabilityDistributionCalculator(network, 0.000000000001);

var result = calculator.CalculateConditionalProbabilityDistribution(new[] { "H" }, new[] { "OdometerSpeedOffset" });
Console.Out.WriteLine(string.Join("\n", result));
}
}
}
@@ -0,0 +1 @@
{"dag":{"edges":[0,1,0,1,1,0,0,0,1,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],"nodes":["BarrierMotorStuck","BarrierSensorFailure","BrakesFailure","OdometerPositionOffset","OdometerSpeedOffset","mcs_BarrierSensorFailure","mcs_OdometerSpeedOffset","mcs_OdometerPositionOffset","mcs_BarrierMotorStuck_BrakesFailure","H"]},"distributions":[{"randomVariable":"BarrierMotorStuck","conditions":[],"distribution":[0.205557824560254,0.79444217543974593]},{"randomVariable":"BarrierSensorFailure","conditions":["BarrierMotorStuck"],"distribution":[0.00060278319518936854,0.00059986364149937094,0.99939721680481064,0.99940013635850078]},{"randomVariable":"BrakesFailure","conditions":[],"distribution":[0.0045894819935232336,0.99541051800647673]},{"randomVariable":"OdometerPositionOffset","conditions":["BarrierMotorStuck","BarrierSensorFailure"],"distribution":[0.54464107652870219,0.5451970059544422,0.54462576680714558,0.54517331452460338,0.45535892347129775,0.4548029940455578,0.45537423319285425,0.45482668547539662]},{"randomVariable":"OdometerSpeedOffset","conditions":["BarrierMotorStuck","BarrierSensorFailure","OdometerPositionOffset"],"distribution":[0.54286250801573133,0.54579390205267153,0.54427789101394652,0.5452151253365678,0.54281656339015372,0.54580704604728891,0.54420528052071659,0.54523400657590637,0.45713749198426867,0.45420609794732841,0.45572210898605336,0.45478487466343237,0.45718343660984634,0.45419295395271136,0.45579471947928341,0.45476599342409391]},{"randomVariable":"mcs_BarrierSensorFailure","conditions":["BarrierSensorFailure"],"distribution":[1.0,0.0,0.0,1.0]},{"randomVariable":"mcs_OdometerSpeedOffset","conditions":["OdometerSpeedOffset"],"distribution":[1.0,0.0,0.0,1.0]},{"randomVariable":"mcs_OdometerPositionOffset","conditions":["OdometerPositionOffset"],"distribution":[1.0,0.0,0.0,1.0]},{"randomVariable":"mcs_BarrierMotorStuck_BrakesFailure","conditions":["BarrierMotorStuck","BrakesFailure"],"distribution":[0.99999999999999545,6.8883846012434364E-18,5.9472241401228993E-16,1.0968209641667932E-18,4.596979651652326E-15,1.0,0.99999999999999933,1.0]},{"randomVariable":"H","conditions":["mcs_BarrierSensorFailure","mcs_OdometerSpeedOffset","mcs_OdometerPositionOffset","mcs_BarrierMotorStuck_BrakesFailure"],"distribution":[0.55021689603133517,0.54323260838429477,0.50441756488678835,0.49795747576133242,0.51029524732910414,0.51007747053396468,0.45031954524513768,0.45012468001393885,0.21307379296294782,0.20448927439054998,0.12296412905737071,0.11497724679106067,0.10747713857654116,0.10743286766725016,3.4144899908558426E-08,1.1020514649009379E-14,0.44978310396866478,0.45676739161570529,0.49558243511321176,0.50204252423866758,0.48970475267089608,0.48992252946603565,0.549680454754862,0.549875319986062,0.78692620703705218,0.79551072560945013,0.87703587094262958,0.88502275320893942,0.89252286142345882,0.89256713233274942,0.99999996585509865,0.99999999999998712]}]}
@@ -98,6 +98,11 @@
<Analyzer Include="$(OutDir)\SafetySharp.Modeling.dll" />
<Analyzer Include="$(OutDir)\SafetySharp.Compiler.dll" />
</ItemGroup>
<ItemGroup>
<None Include="Analysis\network.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="../../Source/SafetySharp.targets" />
</Project>
@@ -22,7 +22,7 @@ public void TestScoreBasedLearning()

var config = BayesianLearningConfiguration.Default;
var bayesianCreator = new BayesianNetworkCreator(model, 10, config);
var result = bayesianCreator.LearnScoreBasedBayesianNetwork(@"D:\Sonstiges\SafetySharpSimulation\", 100000, hazard, states);
var result = bayesianCreator.LearnScoreBasedBayesianNetwork(@"C:\SafetySharpSimulation\", 100000, hazard, states);
}

[Test]
@@ -42,7 +42,7 @@ public void TestConstraintBasedLearning()
[Test]
public void SerializeAndDeserializeBayesianNetwork()
{
const string filePath = @"D:\Sonstiges\SafetySharpSimulation\network.txt";
const string filePath = "network.json";
var model = new SimpleBayesianExampleModel();
Func<bool> hazard = () => model.Component.Hazard;

@@ -57,15 +57,15 @@ public void SerializeAndDeserializeBayesianNetwork()

[Test]
public void CalculateBayesianNetworkProbabilities()
{
const string filePath = @"D:\Sonstiges\SafetySharpSimulation\network.txt";
{
const string filePath = "network.json";
var model = new SimpleBayesianExampleModel();
Func<bool> hazard = () => model.Component.Hazard;
var bayesianNetworkCreator = new BayesianNetworkCreator(model, 10);
var network = bayesianNetworkCreator.FromJson(filePath, hazard);

var calculator = new BayesianNetworkProbabilityDistributionCalculator(network, 0.0000000001);
var result = calculator.CalculateProbabilityDistribution(new [] { "FL", "FS", "FV" });
var result = calculator.CalculateConditionalProbabilityDistribution(new[] { "FS" }, new[] { "FV", "FL" });
Console.Out.WriteLine(string.Join("\n", result));
}

@@ -0,0 +1 @@
{"dag":{"edges":[0,1,1,0,1,0,0,0,1,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0],"nodes":["FL","FS","FV","mcs_FS_FV","H"]},"distributions":[{"randomVariable":"FL","conditions":[],"distribution":[0.39999999999999997,0.60000000000000009]},{"randomVariable":"FS","conditions":["FL"],"distribution":[0.14262500000000003,0.049999999999999989,0.857375,0.95]},{"randomVariable":"FV","conditions":["FL"],"distribution":[0.029701,0.009999999999999995,0.97029899999999991,0.99]},{"randomVariable":"mcs_FS_FV","conditions":["FS","FV"],"distribution":[1.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0]},{"randomVariable":"H","conditions":["FL","mcs_FS_FV"],"distribution":[0.68023571534948635,0.0,1.0,0.0,0.31976428465051365,1.0,0.0,0.99999999999999978]}]}
@@ -101,6 +101,9 @@
<Content Include="Model3\createGraphFigure.py">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="SimpleBayesianExample\network.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
@@ -0,0 +1,118 @@
namespace Tests.Bayesian
{
using System.Collections.Generic;
using System.Linq;
using SafetySharp.Bayesian;
using Xunit;

public class SubsetUtilsTests
{

[Fact]
public void TestGetIndex()
{
var allVariables = new[] { "A", "B", "C", "D" };
var foundVariables = new[] { "D", "B" };
var index = SubsetUtils.GetIndex(foundVariables, allVariables);

Assert.Equal(10, index);
}

[Fact]
public void TestFromIndex()
{
var allVariables = new[] { "A", "B", "C", "D" };
const int index = 11;
var variablesFromIndex = SubsetUtils.FromIndex(allVariables, index);
var expected = new[] { "A", "B", "D" };

Assert.True(!expected.Except(variablesFromIndex).Any() && expected.Length == variablesFromIndex.Count);
}

[Fact]
public void TestFromAndGetIndex()
{
const int index = 103;
var allVariables = new[] { "A", "B", "C", "D", "E", "F", "G" };
var variablesFromIndex = SubsetUtils.FromIndex(allVariables, index);
var calculatedIndex = SubsetUtils.GetIndex(variablesFromIndex, allVariables);

Assert.Equal(index, calculatedIndex);
}

[Fact]
public void TestAllSubsetsSize0()
{
var allVariables = new[] { "A", "B", "C" };
var subsets = SubsetUtils.AllSubsets<string>(allVariables, 0);

Assert.Equal(0, subsets.Count());
}

[Fact]
public void TestAllSubsetsSize1()
{
var allVariables = new[] { "A", "B", "C" };
var subsets = SubsetUtils.AllSubsets<string>(allVariables, 1);
var expected = new[]
{
new HashSet<string>() { "A" },
new HashSet<string>() { "B" },
new HashSet<string>() { "C" }
};

Assert.True(ContainsSameSubsets(subsets, expected));
Assert.True(ContainsSameSubsets(expected, subsets));
}

[Fact]
public void TestAllSubsetsSize2()
{
var allVariables = new[] { "A", "B", "C" };
var subsets = SubsetUtils.AllSubsets<string>(allVariables, 2);
var expected = new[]
{
new HashSet<string>() { "A", "B" },
new HashSet<string>() { "A", "C" },
new HashSet<string>() { "B", "C" }
};

Assert.True(ContainsSameSubsets(subsets, expected));
Assert.True(ContainsSameSubsets(expected, subsets));
}

[Fact]
public void TestAllSubsetsSize3()
{
var allVariables = new[] { "A", "B", "C" };
var subsets = SubsetUtils.AllSubsets<string>(allVariables, 3);
var expected = new[]
{
new HashSet<string>() { "A", "B", "C" }
};

Assert.True(ContainsSameSubsets(subsets, expected));
Assert.True(ContainsSameSubsets(expected, subsets));
}

private static bool ContainsSameSubsets(IEnumerable<HashSet<string>> elements, IEnumerable<HashSet<string>> container)
{
foreach (var element in elements)
{
var isContained = false;
foreach (var containerElement in container)
{
if (!element.Except(containerElement).Any() && element.Count == containerElement.Count)
{
isContained = true;
}
}
if (!isContained)
{
return false;
}
}
return true;
}
}
}
@@ -237,6 +237,7 @@
<Compile Include="Analysis\StateConstraints\deadlock.cs" />
<Compile Include="Bayesian\ConstraintBasedStructureLearnerTests.cs" />
<Compile Include="Bayesian\DagPatternTests.cs" />
<Compile Include="Bayesian\SubsetUtilsTests.cs" />
<Compile Include="Diagnostics\Bindings\Invalid\events.cs" />
<Compile Include="Analysis\Probabilistic\custom probability of transient fault.cs" />
<Compile Include="Analysis\Probabilistic\emulate dice with coin.cs" />
@@ -130,6 +130,9 @@ private void CheckResultingNetwork(BayesianNetwork network)
}
}

/// <summary>
/// Store the given BayesianNetwork in the file path of the config, if it is defined there
/// </summary>
private void StoreBayesianNetwork(BayesianNetwork bayesianNetwork)
{
if (!string.IsNullOrWhiteSpace(Config.BayesianNetworkSerializationPath))
@@ -138,6 +141,14 @@ private void StoreBayesianNetwork(BayesianNetwork bayesianNetwork)
}
}

/// <summary>
/// Create a BayesianNetwork from a JSON file.
/// </summary>
/// <param name="file">Path to the JSON file</param>
/// <param name="hazard">Hazard that was used in the bayesian network</param>
/// <param name="states">Boolen states that were used in the bayesian network</param>
/// <param name="faults">Faults that were used in the bayesian network</param>
/// <returns>a BayesianNetwork instance created from the given JSON file</returns>
public BayesianNetwork FromJson(string file, Func<bool> hazard, Dictionary<string, Func<bool>> states = null, IList<Fault> faults = null)
{
CreateRandomVariables(hazard, states, faults);
Oops, something went wrong.

0 comments on commit bf812ed

Please sign in to comment.
You can’t perform that action at this time.