public void Execute(IExampleInterface app) { // build the bayesian network structure BayesianNetwork network = new BayesianNetwork(); BayesianEvent BlueTaxi = network.CreateEvent("blue_taxi"); BayesianEvent WitnessSawBlue = network.CreateEvent("saw_blue"); network.CreateDependency(BlueTaxi, WitnessSawBlue); network.FinalizeStructure(); // build the truth tales BlueTaxi.Table.AddLine(0.85, true); WitnessSawBlue.Table.AddLine(0.80, true, true); WitnessSawBlue.Table.AddLine(0.20, true, false); // validate the network network.Validate(); // display basic stats Console.WriteLine(network.ToString()); Console.WriteLine("Parameter count: " + network.CalculateParameterCount()); EnumerationQuery query = new EnumerationQuery(network); //SamplingQuery query = new SamplingQuery(network); query.DefineEventType(WitnessSawBlue, EventType.Evidence); query.DefineEventType(BlueTaxi, EventType.Outcome); query.SetEventValue(WitnessSawBlue, false); query.SetEventValue(BlueTaxi, false); query.Execute(); Console.WriteLine(query.ToString()); }
/// <summary> /// Calculate G. /// </summary> /// <param name="network">The network to calculate for.</param> /// <param name="e">The event to calculate for.</param> /// <param name="parents">The parents.</param> /// <returns>The value for G.</returns> public double CalculateG(BayesianNetwork network, BayesianEvent e, IList <BayesianEvent> parents) { double result = 1.0; int r = e.Choices.Count; var args = new int[parents.Count]; do { double n = EncogMath.Factorial(r - 1); double d = EncogMath.Factorial(CalculateN(network, e, parents, args) + r - 1); double p1 = n / d; double p2 = 1; for (int k = 0; k < e.Choices.Count; k++) { p2 *= EncogMath.Factorial(CalculateN(network, e, parents, args, k)); } result *= p1 * p2; } while (EnumerationQuery.Roll(parents, args)); return(result); }
static EnumerationQuery BuildEnumerationQuery() { Console.WriteLine("Building enumeration query"); EnumerationQuery ret = new EnumerationQuery(); return(ret); }
static void Enumerate() { // Search(string indexName, SearchQuery query, out SearchResult result) string indexName = InputString("Index name:", null, true); if (String.IsNullOrEmpty(indexName)) { return; } EnumerationQuery eq = new EnumerationQuery(); string filename = InputString("Enumeration filename:", "", true); if (!String.IsNullOrEmpty(filename)) { eq = DeserializeJson <EnumerationQuery>(File.ReadAllBytes(filename)); } EnumerationResult result = _Sdk.Enumerate(indexName, eq).Result; if (result != null) { Console.WriteLine(SerializeJson(result, true)); } }
public void Execute(IExampleInterface app) { // Create a Bayesian network BayesianNetwork network = new BayesianNetwork(); // Create the Uber driver event BayesianEvent UberDriver = network.CreateEvent("uber_driver"); // create the witness event BayesianEvent WitnessSawUberDriver = network.CreateEvent("saw_uber_driver"); // Attach the two network.CreateDependency(UberDriver, WitnessSawUberDriver); network.FinalizeStructure(); // build the truth tables UberDriver?.Table?.AddLine(0.85, true); WitnessSawUberDriver?.Table?.AddLine(0.80, true, true); WitnessSawUberDriver?.Table?.AddLine(0.20, true, false); network.Validate(); Console.WriteLine(network.ToString()); Console.WriteLine($"Parameter count: {network.CalculateParameterCount()}"); EnumerationQuery query = new EnumerationQuery(network); // The evidence is that someone saw the Uber driver hit the car query.DefineEventType(WitnessSawUberDriver, EventType.Evidence); // The result was the Uber driver did it query.DefineEventType(UberDriver, EventType.Outcome); query.SetEventValue(WitnessSawUberDriver, false); query.SetEventValue(UberDriver, false); query.Execute(); Console.WriteLine(query.ToString()); }
static void TestCase2() { List <string> docsToIndex = DocumentsToIndex("./TestCases/2/"); List <string> queriesToProcess = QueriesToProcess("./TestCases/2/"); ParseOptions options = new ParseOptions(); // load documents foreach (string curr in docsToIndex) { byte[] data = Common.ReadBinaryFile(curr); SourceDocument src = new SourceDocument("test", "test", curr, curr, null, DocType.Json, null, "application/json", data.Length, Common.Md5(data)); IndexResult result = _IndexClient.Add(src, data, options, true).Result; Console.WriteLine(""); Console.WriteLine("Add: " + curr); Console.WriteLine(Common.SerializeJson(result, true)); } Console.WriteLine(""); Console.WriteLine("Press ENTER to continue"); Console.ReadLine(); // execute queries foreach (string curr in queriesToProcess) { EnumerationQuery query = Common.DeserializeJson <EnumerationQuery>(Common.ReadBinaryFile(curr)); EnumerationResult result = _IndexClient.Enumerate(query); Console.WriteLine(""); Console.WriteLine("Query: " + curr); Console.WriteLine(Common.SerializeJson(result, true)); } }
public void TestEnumeration2() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent x1 = network.CreateEvent("x1"); BayesianEvent x2 = network.CreateEvent("x2"); BayesianEvent x3 = network.CreateEvent("x3"); network.CreateDependency(a, x1, x2, x3); network.FinalizeStructure(); a.Table.AddLine(0.5, true); // P(A) = 0.5 x1.Table.AddLine(0.2, true, true); // p(x1|a) = 0.2 x1.Table.AddLine(0.6, true, false); // p(x1|~a) = 0.6 x2.Table.AddLine(0.2, true, true); // p(x2|a) = 0.2 x2.Table.AddLine(0.6, true, false); // p(x2|~a) = 0.6 x3.Table.AddLine(0.2, true, true); // p(x3|a) = 0.2 x3.Table.AddLine(0.6, true, false); // p(x3|~a) = 0.6 network.Validate(); EnumerationQuery query = new EnumerationQuery(network); query.DefineEventType(x1, EventType.Evidence); query.DefineEventType(x2, EventType.Evidence); query.DefineEventType(x3, EventType.Evidence); query.DefineEventType(a, EventType.Outcome); query.SetEventValue(a, true); query.SetEventValue(x1, true); query.SetEventValue(x2, true); query.SetEventValue(x3, false); query.Execute(); TestPercent(query.Probability, 18); }
private static async Task PutEnumerateIndex(RequestMetadata md) { string header = "[Komodo.Server] " + md.Http.Request.Source.IpAddress + ":" + md.Http.Request.Source.Port + " PutEnumerateIndex "; if (md.Http.Request.Data == null || md.Http.Request.ContentLength < 1) { md.Http.Response.StatusCode = 400; md.Http.Response.ContentType = "application/json"; await md.Http.Response.Send(new ErrorResponse(400, "No request body.", null, null).ToJson(true)); return; } string indexName = md.Http.Request.Url.Elements[0]; if (!_Daemon.IndexExists(indexName)) { _Logging.Warn(header + "index " + indexName + " does not exist"); md.Http.Response.StatusCode = 404; md.Http.Response.ContentType = "application/json"; await md.Http.Response.Send(new ErrorResponse(404, "Unknown index.", null, null).ToJson(true)); return; } EnumerationQuery query = Common.DeserializeJson <EnumerationQuery>(Common.StreamToBytes(md.Http.Request.Data)); if (query.Filters == null) { query.Filters = new List <SearchFilter>(); } EnumerationResult result = _Daemon.Enumerate(indexName, query); if (!result.Success) { _Logging.Warn(header + "failed to execute enumeration in index " + indexName); md.Http.Response.StatusCode = 500; md.Http.Response.ContentType = "application/json"; await md.Http.Response.Send(new ErrorResponse(500, "Unable to enumerate index '" + indexName + "'.", null, result).ToJson(true)); return; } md.Http.Response.StatusCode = 200; md.Http.Response.ContentType = "application/json"; await md.Http.Response.Send(Common.SerializeJson(result, md.Params.Pretty)); return; }
/// <summary> /// Enumerate the index. /// </summary> /// <param name="indexName">Name of the index.</param> /// <param name="query">Enumeration query.</param> /// <returns>Enumeraiton result.</returns> public EnumerationResult Enumerate(string indexName, EnumerationQuery query) { if (String.IsNullOrEmpty(indexName)) { throw new ArgumentNullException(nameof(indexName)); } if (query == null) { throw new ArgumentNullException(nameof(query)); } KomodoIndex idx = GetIndexClient(indexName); return(idx.Enumerate(query)); }
static void Enumerate() { string indexName = Common.InputString("Index name :", null, false); EnumerationQuery query = BuildEnumerationQuery(); EnumerationResult result = _Komodo.Enumerate(indexName, query); if (result == null) { Console.WriteLine("(none)"); } else { Console.WriteLine(Common.SerializeJson(result, true)); } }
/// <summary> /// Enumerate source documents in the specified index. /// </summary> /// <param name="indexName">Name of the index.</param> /// <param name="query">Enumeration query.</param> /// <param name="token">Cancellation token used to cancel the request.</param> /// <returns>Enumeration result.</returns> public async Task <EnumerationResult> Enumerate(string indexName, EnumerationQuery query, CancellationToken token = default) { if (String.IsNullOrEmpty(indexName)) { throw new ArgumentNullException(nameof(indexName)); } if (query == null) { throw new ArgumentNullException(nameof(query)); } try { string url = indexName + "?enumerate"; RestRequest req = new RestRequest( _Endpoint + url, HttpMethod.PUT, _AuthHeaders, "application/json"); req.IgnoreCertificateErrors = AcceptInvalidCertificates; RestResponse resp = await req.SendAsync(KomodoCommon.SerializeJson(query, true), token).ConfigureAwait(false); KomodoException e = KomodoException.FromRestResponse(resp); if (e != null) { throw e; } if (resp.Data != null && resp.ContentLength > 0) { byte[] respData = KomodoCommon.StreamToBytes(resp.Data); return(KomodoCommon.DeserializeJson <EnumerationResult>(respData)); } return(null); } catch (TaskCanceledException) { return(null); } catch (OperationCanceledException) { return(null); } }
/// <summary> /// Reset the truth table to zero. /// </summary> public void Reset() { _lines.Clear(); IList <BayesianEvent> parents = _event.Parents; int l = parents.Count; int[] args = new int[l]; do { for (int k = 0; k < _event.Choices.Count; k++) { AddLine(0, k, args); } } while (EnumerationQuery.Roll(parents, args)); }
static void Main(string[] args) { /*Przykład 4.2.3 Teoria Bayesa - Zakłady Produkcyjne Etap Manualny * Lesson 1 - Machine Learning in C# for Amazon ML Group created by me :-) * PS. Kill me I use polish :-) */ BayesianNetwork network = new BayesianNetwork(); BayesianEvent WadliwyElement = network.CreateEvent("wadliwy_element"); BayesianEvent A1 = network.CreateEvent("wadliwy_element_zaklad_A1"); BayesianEvent A2 = network.CreateEvent("wadliwy_element_zaklad_A2"); BayesianEvent A3 = network.CreateEvent("wadliwy_element_zaklad_A3"); BayesianEvent A4 = network.CreateEvent("wadliwy_element_zaklad_A4"); network.CreateDependency(WadliwyElement, A1, A2, A3, A4); network.FinalizeStructure(); WadliwyElement?.Table?.AddLine(0.1083, true); A1?.Table.AddLine(0.069, true, true); A1?.Table.AddLine(1 - 0.069, true, false); A2?.Table.AddLine(0.277, true, true); A2?.Table.AddLine(1 - 0.277, true, false); A3?.Table.AddLine(0.007, true, true); A3?.Table.AddLine(1 - 0.007, true, false); A4?.Table.AddLine(0.646, true, true); A4?.Table.AddLine(1 - 0.646, true, false); network.Validate(); Console.WriteLine(network.ToString() + "\n"); Console.WriteLine($"Liczba parametrów: {network.CalculateParameterCount()}"); EnumerationQuery query = new EnumerationQuery(network); query.DefineEventType(WadliwyElement, EventType.Evidence); query.DefineEventType(A1, EventType.Outcome); query.DefineEventType(A2, EventType.Evidence); query.DefineEventType(A3, EventType.Evidence); query.DefineEventType(A4, EventType.Evidence); query.SetEventValue(WadliwyElement, false); query.SetEventValue(A1, false); query.SetEventValue(A2, false); query.SetEventValue(A3, false); query.SetEventValue(A4, false); query.Execute(); Console.WriteLine(query.ToString()); }
public void Execute(IExampleInterface app) { BayesianNetwork network = new BayesianNetwork(); BayesianEvent grass = network.CreateEvent("grass"); BayesianEvent sprinkler = network.CreateEvent("sprinkler"); BayesianEvent rain = network.CreateEvent("rain"); BayesianEvent DidRain = network.CreateEvent("did_rain"); BayesianEvent SprinklerOn = network.CreateEvent("sprinkler_on"); network.CreateDependency(rain, DidRain); network.CreateDependency(sprinkler, SprinklerOn); network.FinalizeStructure(); // build the truth tales rain.Table.AddLine(0.35, true); // 80% of the time they were right DidRain.Table.AddLine(0.80, false, true); // 20% of the time they were wrong DidRain.Table.AddLine(0.20, true, true); sprinkler.Table.AddLine(.65, true); // 60% of the time they were right SprinklerOn.Table.AddLine(.40, true, true); // 40% of the time they were wrong SprinklerOn.Table.AddLine(.60, false, true); // validate the network network.Validate(); // display basic stats Console.WriteLine(network.ToString()); Console.WriteLine("Parameter count: " + network.CalculateParameterCount()); EnumerationQuery query = new EnumerationQuery(network); //SamplingQuery query = new SamplingQuery(network); query.DefineEventType(SprinklerOn, EventType.Evidence); query.DefineEventType(sprinkler, EventType.Outcome); query.DefineEventType(DidRain, EventType.Evidence); query.DefineEventType(rain, EventType.Outcome); query.Execute(); Console.WriteLine(query.ToString()); }
public void TestEnumeration1() { BayesianNetwork network = new BayesianNetwork(); BayesianEvent a = network.CreateEvent("a"); BayesianEvent b = network.CreateEvent("b"); network.CreateDependency(a, b); network.FinalizeStructure(); a.Table.AddLine(0.5, true); // P(A) = 0.5 b.Table.AddLine(0.2, true, true); // p(b|a) = 0.2 b.Table.AddLine(0.8, true, false); // p(b|~a) = 0.8 network.Validate(); EnumerationQuery query = new EnumerationQuery(network); query.DefineEventType(a, EventType.Evidence); query.DefineEventType(b, EventType.Outcome); query.SetEventValue(b, true); query.SetEventValue(a, true); query.Execute(); TestPercent(query.Probability, 20); }
/// <summary> /// Construct a Bayesian network. /// </summary> public BayesianNetwork() { Query = new EnumerationQuery(this); }
/// <inheritdoc/> public Object Read(Stream istream) { BayesianNetwork result = new BayesianNetwork(); EncogReadHelper input = new EncogReadHelper(istream); EncogFileSection section; String queryType = ""; String queryStr = ""; String contentsStr = ""; while ((section = input.ReadNextSection()) != null) { if (section.SectionName.Equals("BAYES-NETWORK") && section.SubSectionName.Equals("BAYES-PARAM")) { IDictionary <String, String> p = section.ParseParams(); queryType = p["queryType"]; queryStr = p["query"]; contentsStr = p["contents"]; } if (section.SectionName.Equals("BAYES-NETWORK") && section.SubSectionName.Equals("BAYES-TABLE")) { result.Contents = contentsStr; // first, define relationships (1st pass) foreach (String line in section.Lines) { result.DefineRelationship(line); } result.FinalizeStructure(); // now define the probabilities (2nd pass) foreach (String line in section.Lines) { result.DefineProbability(line); } } if (section.SectionName.Equals("BAYES-NETWORK") && section.SubSectionName.Equals("BAYES-PROPERTIES")) { IDictionary <String, String> paras = section.ParseParams(); EngineArray.PutAll(paras, result.Properties); } } // define query, if it exists if (queryType.Length > 0) { IBayesianQuery query = null; if (queryType.Equals("EnumerationQuery")) { query = new EnumerationQuery(result); } else { query = new SamplingQuery(result); } if (query != null && queryStr.Length > 0) { result.Query = query; result.DefineClassificationStructure(queryStr); } } return(result); }