diff --git a/core/AeonTagHandlers/Bot.cs b/core/AeonTagHandlers/Bot.cs deleted file mode 100644 index 4935db7..0000000 --- a/core/AeonTagHandlers/Bot.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// An element called bot, which may be considered a restricted version of get, is used to tell the interpreter that it should substitute the contents of a "bot predicate". The value of a bot predicate is set at load-time, and cannot be changed at run-time. The interpreter may decide how to set the values of bot predicate at load-time. If the bot predicate has no value defined, the interpreter should substitute an empty string. The bot element has a required name attribute that identifies the bot predicate. - /// - /// The bot element does not have any content. - /// - public class Bot : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Bot(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "bot") - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "name") - { - string key = TemplateNode.Attributes["name"].Value; - return ThisAeon.GlobalSettings.GrabSetting(key); - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Condition.cs b/core/AeonTagHandlers/Condition.cs deleted file mode 100644 index 7b33329..0000000 --- a/core/AeonTagHandlers/Condition.cs +++ /dev/null @@ -1,239 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Text.RegularExpressions; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The condition element instructs the interpreter to return specified contents depending - /// upon the results of matching a predicate against a pattern. - /// - /// NB: The condition element has three different types. The three different types specified - /// here are distinguished by an xsi:type attribute, which permits a validating XML Schema - /// processor to validate them. Two of the types may contain li elements, of which there are - /// three different types, whose validity is determined by the type of enclosing condition. In - /// practice, an interpreter may allow the omission of the xsi:type attribute and may instead - /// heuristically determine which type of condition (and hence li) is in use. - /// - /// Block Condition - /// --------------- - /// - /// The blockCondition type of condition has a required attribute "name", which specifies a - /// predicate, and a required attribute "value", which contains a simple pattern expression. - /// - /// If the contents of the value attribute match the value of the predicate specified by name, then - /// the interpreter should return the contents of the condition. If not, the empty string "" - /// should be returned. - /// - /// Single-predicate Condition - /// -------------------------- - /// - /// The singlePredicateCondition type of condition has a required attribute "name", which specifies - /// a predicate. This form of condition must contain at least one li element. Zero or more of - /// these li elements may be of the valueOnlyListItem type. Zero or one of these li elements may be - /// of the defaultListItem type. - /// - /// The singlePredicateCondition type of condition is processed as follows: - /// - /// Reading each contained li in order: - /// - /// 1. If the li is a valueOnlyListItem type, then compare the contents of the value attribute of - /// the li with the value of the predicate specified by the name attribute of the enclosing - /// condition. - /// a. If they match, then return the contents of the li and stop processing this condition. - /// b. If they do not match, continue processing the condition. - /// 2. If the li is a defaultListItem type, then return the contents of the li and stop processing - /// this condition. - /// - /// Multi-predicate Condition - /// ------------------------- - /// - /// The multiPredicateCondition type of condition has no attributes. This form of condition must - /// contain at least one li element. Zero or more of these li elements may be of the - /// nameValueListItem type. Zero or one of these li elements may be of the defaultListItem type. - /// - /// The multiPredicateCondition type of condition is processed as follows: - /// - /// Reading each contained li in order: - /// - /// 1. If the li is a nameValueListItem type, then compare the contents of the value attribute of - /// the li with the value of the predicate specified by the name attribute of the li. - /// a. If they match, then return the contents of the li and stop processing this condition. - /// b. If they do not match, continue processing the condition. - /// 2. If the li is a defaultListItem type, then return the contents of the li and stop processing - /// this condition. - /// - /// **************** - /// - /// Condition List Items - /// - /// As described above, two types of condition may contain li elements. There are three types of - /// li elements. The type of li element allowed in a given condition depends upon the type of that - /// condition, as described above. - /// - /// Default List Items - /// ------------------ - /// - /// An li element of the type defaultListItem has no attributes. It may contain any template elements. - /// - /// Value-only List Items - /// --------------------- - /// - /// An li element of the type valueOnlyListItem has a required attribute value, which must contain - /// a simple pattern expression. The element may contain any template elements. - /// - /// Name and Value List Items - /// ------------------------- - /// - /// An li element of the type nameValueListItem has a required attribute name, which specifies a - /// predicate, and a required attribute value, which contains a simple pattern expression. The - /// element may contain any template elements. - /// - public class Condition : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Condition(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - IsRecursive = false; - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "condition") - { - // Heuristically work out the type of condition being processed. - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 2) // Block. - { - string name = ""; - string value = ""; - - if (TemplateNode.Attributes[0].Name == "name") - { - name = TemplateNode.Attributes[0].Value; - } - else if (TemplateNode.Attributes[0].Name == "value") - { - value = TemplateNode.Attributes[0].Value; - } - - if (TemplateNode.Attributes[1].Name == "name") - { - name = TemplateNode.Attributes[1].Value; - } - else if (TemplateNode.Attributes[1].Name == "value") - { - value = TemplateNode.Attributes[1].Value; - } - - if ((name.Length > 0) & (value.Length > 0)) - { - string actualValue = ThisUser.Predicates.GrabSetting(name); - Regex matcher = new Regex(value.Replace(" ", "\\s").Replace("*", "[\\sA-Z0-9]+"), RegexOptions.IgnoreCase); - if (matcher.IsMatch(actualValue)) - { - return TemplateNode.InnerXml; - } - } - } - else if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) // A single predicate. - { - if (TemplateNode.Attributes[0].Name == "name") - { - string name = TemplateNode.Attributes[0].Value; - foreach (XmlNode childLiNode in TemplateNode.ChildNodes) - { - if (childLiNode.Name.ToLower() == "li") - { - if (childLiNode.Attributes != null && childLiNode.Attributes.Count == 1) - { - if (childLiNode.Attributes[0].Name.ToLower() == "value") - { - string actualValue = ThisUser.Predicates.GrabSetting(name); - Regex matcher = new Regex(childLiNode.Attributes[0].Value.Replace(" ", "\\s").Replace("*", "[\\sA-Z0-9]+"), RegexOptions.IgnoreCase); - if (matcher.IsMatch(actualValue)) - { - return childLiNode.InnerXml; - } - } - } - else if (childLiNode.Attributes != null && childLiNode.Attributes.Count == 0) - { - return childLiNode.InnerXml; - } - } - } - } - } - else if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 0) // A multi-predicate. - { - foreach (XmlNode childLiNode in TemplateNode.ChildNodes) - { - if (childLiNode.Name.ToLower() == "li") - { - if (childLiNode.Attributes != null && childLiNode.Attributes.Count == 2) - { - string name = ""; - string value = ""; - if (childLiNode.Attributes[0].Name == "name") - { - name = childLiNode.Attributes[0].Value; - } - else if (childLiNode.Attributes[0].Name == "value") - { - value = childLiNode.Attributes[0].Value; - } - - if (childLiNode.Attributes[1].Name == "name") - { - name = childLiNode.Attributes[1].Value; - } - else if (childLiNode.Attributes[1].Name == "value") - { - value = childLiNode.Attributes[1].Value; - } - - if ((name.Length > 0) & (value.Length > 0)) - { - string actualValue = ThisUser.Predicates.GrabSetting(name); - Regex matcher = new Regex(value.Replace(" ", "\\s").Replace("*","[\\sA-Z0-9]+"), RegexOptions.IgnoreCase); - if (matcher.IsMatch(actualValue)) - { - return childLiNode.InnerXml; - } - } - } - else if (childLiNode.Attributes != null && childLiNode.Attributes.Count == 0) - { - return childLiNode.InnerXml; - } - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Date.cs b/core/AeonTagHandlers/Date.cs deleted file mode 100644 index 287134d..0000000 --- a/core/AeonTagHandlers/Date.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The date element tells the interpreter that it should substitute the system local date and time. No formatting constraints on the output are specified. - /// - /// The date element does not have any content. - /// - public class Date : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Date(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "date") - { - return DateTime.Now.ToString(ThisAeon.Locale); - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Formal.cs b/core/AeonTagHandlers/Formal.cs deleted file mode 100644 index d2a8078..0000000 --- a/core/AeonTagHandlers/Formal.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Text; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The formal element tells the interpreter to render the contents of the element - /// such that the first letter of each word is in uppercase, as defined (if defined) by - /// the locale indicated by the specified language (if specified). This is similar to methods - /// that are sometimes called "Title Case". - /// - /// If no character in this string has a different uppercase version, based on the Unicode - /// standard, then the original string is returned. - /// - public class Formal : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Formal(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "formal") - { - StringBuilder result = new StringBuilder(); - if (TemplateNode.InnerText.Length > 0) - { - string[] words = TemplateNode.InnerText.ToLower().Split(); - foreach (string word in words) - { - string newWord = word.Substring(0, 1); - newWord = newWord.ToUpper(); - if (word.Length > 1) - { - newWord += word.Substring(1); - } - result.Append(newWord + " "); - } - } - return result.ToString().Trim(); - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Gender.cs b/core/AeonTagHandlers/Gender.cs deleted file mode 100644 index 3362eb7..0000000 --- a/core/AeonTagHandlers/Gender.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Normalize; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The atomic version of the gender element is a shortcut for: - /// - /// - /// - /// The atomic gender does not have any content. Combined with person substitutions. - /// - /// The non-atomic gender element instructs the interpreter to: - /// - /// 1. Replace male-gendered words in the result of processing the contents of the gender element - /// with the grammatically-corresponding female-gendered words; and - /// - /// 2. Replace female-gendered words in the result of processing the contents of the gender element - /// with the grammatically-corresponding male-gendered words. - /// - /// The definition of "grammatically-corresponding" is left up to the implementation. - /// - public class Gender : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Gender(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "gender") - { - if (TemplateNode.InnerText.Length > 0) - { - // Non-atomic version of the node. - return ApplySubstitutions.Substitute(ThisAeon, ThisAeon.PersonSubstitutions, TemplateNode.InnerText); - } - // Atomic version of the node. - XmlNode starNode = GetNode(""); - Star recursiveStar = new Star(ThisAeon, ThisUser, Query, UserRequest, UserResult, starNode); - TemplateNode.InnerText = recursiveStar.Transform(); - if (!string.IsNullOrEmpty(TemplateNode.InnerText)) - { - return ProcessChange(); - } - return string.Empty; - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Get.cs b/core/AeonTagHandlers/Get.cs deleted file mode 100644 index c6b87f9..0000000 --- a/core/AeonTagHandlers/Get.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The get element tells the interpreter that it should substitute the contents of a predicate, if that predicate has a value defined. If the predicate has no value defined, the interpreter should substitute the empty string "". - /// - /// The interpreter implementation may optionally provide a mechanism that allows the author to designate default values for certain predicates (see [9.3.]). - /// - /// The get element must not perform any text formatting or other "normalization" on the predicate contents when returning them. - /// - /// The get element has a required name attribute that identifies the predicate with a predicate name. - /// - /// The get element does not have any content. - /// - public class Get : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Get(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "get") - { - if (ThisAeon.GlobalSettings.Count > 0) - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "name") - { - return ThisUser.Predicates.GrabSetting(TemplateNode.Attributes[0].Value); - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Gossip.cs b/core/AeonTagHandlers/Gossip.cs deleted file mode 100644 index 2fea363..0000000 --- a/core/AeonTagHandlers/Gossip.cs +++ /dev/null @@ -1,55 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The gossip element instructs the interpreter to capture the result of processing the contents of the gossip elements and to store these contents in a manner left up to the implementation. Most common uses of gossip have been to store captured contents in a separate file. - /// - /// The gossip element does not have any attributes. It may contain any template elements. - /// - public class Gossip : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Gossip(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "gossip") - { - // Gossip is merely logged by aeon and written to the log file. - if (TemplateNode.InnerText.Length > 0) - { - Logging.WriteLog("Gossip from the user: " + ThisUser.UserName + ", '" + TemplateNode.InnerText + "'", - Logging.LogType.Gossip, Logging.LogCaller.Gossip); - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Id.cs b/core/AeonTagHandlers/Id.cs deleted file mode 100644 index 1be5171..0000000 --- a/core/AeonTagHandlers/Id.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The id element tells the interpreter that it should substitute the user identification. The determination of the user ID is not specified, since it will vary by application. A suggested default return value is "localhost". - /// - /// The id element does not have any content. - /// - public class Id : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Id(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "id") - { - return ThisUser.UserName; - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Input.cs b/core/AeonTagHandlers/Input.cs deleted file mode 100644 index 754a321..0000000 --- a/core/AeonTagHandlers/Input.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The input element tells the interpreter that it should substitute the contents of a previous user input. - /// - /// The template-side input has an optional index attribute that may contain either a single integer or a comma-separated pair of integers. The minimum value for either of the integers in the index is "1". The index tells the interpreter which previous user input should be returned (first dimension), and optionally which "sentence" (see [8.3.2.]) of the previous user input. - /// - /// The interpreter should raise an error if either of the specified index dimensions is invalid at run-time. - /// - /// An unspecified index is the equivalent of "1,1". An unspecified second dimension of the index is the equivalent of specifying a "1" for the second dimension. - /// - /// The input element does not have any content. - /// - public class Input : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Input(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "input") - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 0) - { - return ThisUser.GetAeonReply(); - } - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "index") - { - if (TemplateNode.Attributes[0].Value.Length > 0) - { - try - { - // See if there is a split. - string[] dimensions = TemplateNode.Attributes[0].Value.Split(",".ToCharArray()); - if (dimensions.Length == 2) - { - int localResult = Convert.ToInt32(dimensions[0].Trim()); - int sentence = Convert.ToInt32(dimensions[1].Trim()); - if ((localResult > 0) & (sentence > 0)) - { - return ThisUser.GetAeonReply(localResult - 1, sentence - 1); - } - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.Input); - } - else - { - int result = Convert.ToInt32(TemplateNode.Attributes[0].Value.Trim()); - if (result > 0) - { - return ThisUser.GetAeonReply(result - 1); - } - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.Input); - } - } - catch - { - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.Input); - } - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Learn.cs b/core/AeonTagHandlers/Learn.cs deleted file mode 100644 index 6b63811..0000000 --- a/core/AeonTagHandlers/Learn.cs +++ /dev/null @@ -1,67 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.IO; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The learn element instructs the interpreter to retrieve a resource specified by a URI, and to process its aeon object contents. - /// - public class Learn : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Learn(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "learn") - { - // Currently only *.aeon files in the local filesystem can be referenced, as per design. - if (TemplateNode.InnerText.Length > 0) - { - string path = TemplateNode.InnerText; - FileInfo fi = new FileInfo(path); - if (fi.Exists) - { - XmlDocument doc = new XmlDocument(); - try - { - doc.Load(path); - ThisAeon.LoadAeonFromXml(doc, path); - } - catch - { - Logging.WriteLog("Failed to learn something new from the following URI: " + path, Logging.LogType.Error, Logging.LogCaller.Learn); - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Lowercase.cs b/core/AeonTagHandlers/Lowercase.cs deleted file mode 100644 index db0ad49..0000000 --- a/core/AeonTagHandlers/Lowercase.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The lowercase element tells the interpreter to render the contents of the element in lowercase, as defined (if defined) by the locale indicated by the specified language (if specified). - /// - /// If no character in this string has a different lowercase version, based on the Unicode standard, then the original string is returned. - /// - public class Lowercase : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Lowercase(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "lowercase") - { - return TemplateNode.InnerText.ToLower(ThisAeon.Locale); - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Person.cs b/core/AeonTagHandlers/Person.cs deleted file mode 100644 index 5880880..0000000 --- a/core/AeonTagHandlers/Person.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Normalize; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The atomic version of the person element is a shortcut for: - /// - /// - /// - /// The atomic person does not have any content. - /// - /// The non-atomic person element instructs the interpreter to: - /// - /// 1. replace words with first-person aspect in the result of processing the contents of the - /// person element with words with the grammatically-corresponding third-person aspect; and - /// - /// 2. replace words with third-person aspect in the result of processing the contents of the - /// person element with words with the grammatically-corresponding first-person aspect. - /// - /// The definition of "grammatically-corresponding" is left up to the implementation. - /// - /// The definition of "grammatically-corresponding" is left up to the implementation. - /// Historically, implementations of person have dealt with pronouns, likely due to the fact that most code is written in English. However, the decision about whether to transform the person aspect of other words is left up to the implementation. - /// - public class Person : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Person(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "person") - { - if (TemplateNode.InnerText.Length > 0) - { - // Non-atomic version of the node. - return ApplySubstitutions.Substitute(ThisAeon, ThisAeon.PersonSubstitutions, TemplateNode.InnerText); - } - // Atomic version of the node. - XmlNode starNode = GetNode(""); - Star recursiveStar = new Star(ThisAeon, ThisUser, Query, UserRequest, UserResult, starNode); - TemplateNode.InnerText = recursiveStar.Transform(); - if (TemplateNode.InnerText != null && TemplateNode.InnerText.Length > 0) - { - return ProcessChange(); - } - return string.Empty; - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Person2.cs b/core/AeonTagHandlers/Person2.cs deleted file mode 100644 index cf31f1e..0000000 --- a/core/AeonTagHandlers/Person2.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Normalize; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The atomic version of the person2 element is a shortcut for: - /// - /// - /// - /// The atomic person2 does not have any content. Combined with person substitutions. - /// - /// The non-atomic person2 element instructs the interpreter to: - /// - /// 1. Replace words with first-person aspect in the result of processing the contents of the - /// person2 element with words with the grammatically-corresponding second-person aspect; and, - /// - /// 2. Replace words with second-person aspect in the result of processing the contents of the - /// person2 element with words with the grammatically-corresponding first-person aspect. - /// - /// The definition of "grammatically-corresponding" is left up to the implementation. - /// - /// The definition of "grammatically-corresponding" is left up to the implementation. - /// Historically, implementations of person2 have dealt with pronouns, likely due to the fact that most code is written in English. However, the decision about whether to transform the person aspect of other words is left up to the implementation. - /// - public class Person2 : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Person2(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "person2") - { - if (TemplateNode.InnerText.Length > 0) - { - // Non-atomic version of the node. - return ApplySubstitutions.Substitute(ThisAeon, ThisAeon.PersonSubstitutions, TemplateNode.InnerText); - } - // Atomic version of the node. - XmlNode starNode = GetNode(""); - Star recursiveStar = new Star(ThisAeon, ThisUser, Query, UserRequest, UserResult, starNode); - TemplateNode.InnerText = recursiveStar.Transform(); - if (!string.IsNullOrEmpty(TemplateNode.InnerText)) - { - return ProcessChange(); - } - return string.Empty; - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Piglatin.cs b/core/AeonTagHandlers/Piglatin.cs deleted file mode 100644 index e6bd526..0000000 --- a/core/AeonTagHandlers/Piglatin.cs +++ /dev/null @@ -1,139 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Cartheur.Animals.Utilities; -using System.Globalization; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// Ranslatestay Englishway ordsway intoway Igpay Atinlay - /// - /// Translates English words into Pig Latin - [CustomTag] - public class Piglatin : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - public Piglatin() - { - InputString = "piglatin"; - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "piglatin") - { - if (TemplateNode.InnerText.Length > 0) - { - StringBuilder result = new StringBuilder(); - string[] words = TemplateNode.InnerText.ToLower().Split(" ".ToCharArray()); - - foreach (string word in words) - { - char[] letters = word.ToCharArray(); - - const string consonantEnd = "ay"; - const string vowelEnd = "way"; - string[] doubleConsonants = { "ph", "th", "ch", "pn", "sh", "st", "sp" }; - string[] punctuation = { "\"", ".", "!", ";", "?", ")" }; - Regex vowels = new Regex("[aeiou]", RegexOptions.IgnoreCase); - Regex validChars = new Regex("[a-z]", RegexOptions.IgnoreCase); - int locationOfFirstLetter = 0; - bool isVowelEnding = false; - string firstChar = ""; - foreach (char character in letters) - { - if (vowels.IsMatch(character.ToString(CultureInfo.InvariantCulture))) - { - isVowelEnding = true; - firstChar = character.ToString(CultureInfo.InvariantCulture); - break; - } - if (validChars.IsMatch(character.ToString(CultureInfo.InvariantCulture))) - { - isVowelEnding = false; - string firstCharPair = word.Substring(locationOfFirstLetter, 2); - foreach (string doubleCheck in doubleConsonants) - { - if (firstCharPair == doubleCheck) - { - firstChar = firstCharPair; - } - } - if (firstChar.Length == 0) - { - firstChar = character.ToString(CultureInfo.InvariantCulture); - } - break; - } - locationOfFirstLetter++; - } - // stitch together - if (locationOfFirstLetter > 0) - { - // start the word with any non-character chars (e.g. open brackets) - result.Append(word.Substring(0, locationOfFirstLetter)); - } - int newStart; - if (isVowelEnding) - { - newStart = locationOfFirstLetter; - } - else - { - newStart = locationOfFirstLetter + firstChar.Length; - } - string tail; - if (isVowelEnding) - { - tail = vowelEnd; - } - else - { - tail = consonantEnd; - } - - for (int i = newStart; i < letters.Length; i++) - { - string letter = letters[i].ToString(CultureInfo.InvariantCulture); - bool isCharacter = true; - foreach (string puntuationEnd in punctuation) - { - if (letter == puntuationEnd) - { - tail += letter; - isCharacter = false; - } - } - - if (isCharacter) - { - result.Append(letter); - } - } - if (!isVowelEnding) - { - result.Append(firstChar); - } - result.Append(tail + " "); - } - XmlNode dummySentence = GetNode("" + result.ToString().Trim() + ""); - Sentence sentenceMaker = new Sentence(ThisAeon, ThisUser, Query, UserRequest, UserResult, dummySentence); - - return sentenceMaker.Transform(); - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Random.cs b/core/AeonTagHandlers/Random.cs deleted file mode 100644 index 34df6ac..0000000 --- a/core/AeonTagHandlers/Random.cs +++ /dev/null @@ -1,68 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The random element instructs the interpreter to return exactly one of its contained li elements randomly. The random element must contain one or more li elements of type defaultListItem, and cannot contain any other elements. - /// - public class RandomTag : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public RandomTag(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - IsRecursive = false; - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "random") - { - if (TemplateNode.HasChildNodes) - { - // Only grab
  • nodes. - List listNodes = new List(); - foreach (XmlNode childNode in TemplateNode.ChildNodes) - { - if (childNode.Name == "li") - { - listNodes.Add(childNode); - } - } - if (listNodes.Count > 0) - { - var r = new Random(); - XmlNode chosenNode = listNodes[r.Next(listNodes.Count)]; - return chosenNode.InnerXml; - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Script.cs b/core/AeonTagHandlers/Script.cs deleted file mode 100644 index 1fc7cb9..0000000 --- a/core/AeonTagHandlers/Script.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// Facilitates the execution of a script from within the runtime. - /// - public class Script : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Script(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - Logging.WriteLog("The script tag is not yet implemented. Perhaps in a later version it will.", Logging.LogType.Error, Logging.LogCaller.Script); - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Sentence.cs b/core/AeonTagHandlers/Sentence.cs deleted file mode 100644 index 1ae6898..0000000 --- a/core/AeonTagHandlers/Sentence.cs +++ /dev/null @@ -1,94 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The sentence element tells the interpreter to render the contents of the element such that the first letter of each sentence is in uppercase, as defined (if defined) by the locale indicated by the specified language (if specified). Sentences are interpreted as strings whose last character is the period or full-stop character .. If the string does not contain a ., then the entire string is treated as a sentence. If no character in this string has a different uppercase version, based on the Unicode standard, then the original string is returned. - /// - public class Sentence : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Sentence(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if(TemplateNode.Name.ToLower()=="sentence") - { - if (TemplateNode.InnerText.Length > 0) - { - StringBuilder result = new StringBuilder(); - char[] letters = TemplateNode.InnerText.Trim().ToCharArray(); - bool doChange = true; - for (int i = 0; i < letters.Length; i++) - { - string letterAsString = Convert.ToString(letters[i]); - if (ThisAeon.Splitters.Contains(letterAsString)) - { - doChange = true; - } - - Regex lowercaseLetter = new Regex("[a-zA-Z]"); - - if (lowercaseLetter.IsMatch(letterAsString)) - { - if (doChange) - { - result.Append(letterAsString.ToUpper(ThisAeon.Locale)); - doChange = false; - } - else - { - result.Append(letterAsString.ToLower(ThisAeon.Locale)); - } - } - else - { - result.Append(letterAsString); - } - } - return result.ToString(); - } - // Atomic version of the node. - XmlNode starNode = GetNode(""); - Star recursiveStar = new Star(ThisAeon, ThisUser, Query, UserRequest, UserResult, starNode); - TemplateNode.InnerText = recursiveStar.Transform(); - if (!string.IsNullOrEmpty(TemplateNode.InnerText)) - { - return ProcessChange(); - } - return string.Empty; - } - - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Set.cs b/core/AeonTagHandlers/Set.cs deleted file mode 100644 index ebcb79f..0000000 --- a/core/AeonTagHandlers/Set.cs +++ /dev/null @@ -1,70 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The set element instructs the interpreter to set the value of a predicate to the result of processing the contents of the set element. The set element has a required attribute name, which must be a valid predicate name. If the predicate has not yet been defined, the interpreter should define it in memory. - /// - /// The interpreter should, generically, return the result of processing the contents of the set element. The set element must not perform any text formatting or other "normalization" on the predicate contents when returning them. - /// - /// The interpreter implementation may optionally provide a mechanism that allows the author to designate certain predicates as "return-name-when-set", which means that a set operation using such a predicate will return the name of the predicate, rather than its captured value. (See [9.2].) - /// - /// A set element may contain any template elements. - /// - public class Set : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Set(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "set") - { - if (ThisAeon.GlobalSettings.Count > 0) - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "name") - { - if (TemplateNode.InnerText.Length > 0) - { - ThisUser.Predicates.AddSetting(TemplateNode.Attributes[0].Value, TemplateNode.InnerText); - return ThisUser.Predicates.GrabSetting(TemplateNode.Attributes[0].Value); - } - // Remove the predicate. - ThisUser.Predicates.RemoveSetting(TemplateNode.Attributes[0].Value); - return string.Empty; - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Size.cs b/core/AeonTagHandlers/Size.cs deleted file mode 100644 index 94c76b2..0000000 --- a/core/AeonTagHandlers/Size.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The size element tells the interpreter that it should substitute the number of categories currently loaded. The size element does not have any content. - /// - public class Size : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Size(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "size") - { - return Convert.ToString(ThisAeon.Size); - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Sr.cs b/core/AeonTagHandlers/Sr.cs deleted file mode 100644 index 031a007..0000000 --- a/core/AeonTagHandlers/Sr.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The sr element is a shortcut for: - /// - /// - /// - /// The atomic sr does not have any content. - /// - public class Sr : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Sr(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "sr") - { - XmlNode starNode = GetNode(""); - Star recursiveStar = new Star(ThisAeon, ThisUser, Query, UserRequest, UserResult, starNode); - string starContent = recursiveStar.Transform(); - - XmlNode sraiNode = GetNode(""+starContent+""); - Srai sraiHandler = new Srai(ThisAeon, ThisUser, Query, UserRequest, UserResult, sraiNode); - return sraiHandler.Transform(); - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Srai.cs b/core/AeonTagHandlers/Srai.cs deleted file mode 100644 index fff9a8e..0000000 --- a/core/AeonTagHandlers/Srai.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The srai element instructs the interpreter to pass the result of processing the contents of the srai element to the matching loop, as if the input had been produced by the user (this includes stepping through the entire input normalization process). The srai element does not have any attributes. It may contain any template elements. - /// - /// As with all elements, nested forms should be parsed from inside out, so embedded srais are perfectly acceptable. - /// - public class Srai : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Srai(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "srai") - { - if (TemplateNode.InnerText.Length > 0) - { - Request subRequest = new Request(TemplateNode.InnerText, ThisUser, ThisAeon); - // Make sure time is not added to the request. - subRequest.StartedOn = UserRequest.StartedOn; - Result subQuery = ThisAeon.Chat(subRequest); - UserRequest.HasTimedOut = subRequest.HasTimedOut; - return subQuery.Output; - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Star.cs b/core/AeonTagHandlers/Star.cs deleted file mode 100644 index 1d15c8d..0000000 --- a/core/AeonTagHandlers/Star.cs +++ /dev/null @@ -1,86 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The star element indicates that an interpreter should substitute the value "captured" by a particular wildcard from the pattern-specified portion of the match path when returning the template. - /// - /// The star element has an optional integer index attribute that indicates which wildcard to use. The minimum acceptable value for the index is "1" (the first wildcard), and the maximum acceptable value is equal to the number of wildcards in the pattern. - /// - /// An interpreter should raise an error if the index attribute of a star specifies a wildcard that does not exist in the category element's pattern. Not specifying the index is the same as specifying an index of "1". - /// - /// The star element does not have any content. - /// - public class Star : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Star(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "star") - { - if (Query.InputStar.Count > 0) - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 0) - { - // Return the first (latest) star in the List<>. - return Query.InputStar[0]; - } - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "index") - { - try - { - int index = Convert.ToInt32(TemplateNode.Attributes[0].Value); - index--; - if ((index >= 0) & (index < Query.InputStar.Count)) - { - return Query.InputStar[index]; - } - Logging.WriteLog("InputStar out of bounds reference caused by input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.Star); - } - catch - { - Logging.WriteLog("Index set to non-integer value while processing star tag in response to the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.Star); - } - } - } - } - else - { - Logging.WriteLog("A star tag tried to reference an empty InputStar collection when processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.Star); - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/System.cs b/core/AeonTagHandlers/System.cs deleted file mode 100644 index 1c4e85d..0000000 --- a/core/AeonTagHandlers/System.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - [CustomTag] - public class System : AeonTagHandler - { - public System() - { - InputString = "testtag"; - } - - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "system") - { - return "Override default tag implementation works correctly"; - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Test.cs b/core/AeonTagHandlers/Test.cs deleted file mode 100644 index e172faa..0000000 --- a/core/AeonTagHandlers/Test.cs +++ /dev/null @@ -1,66 +0,0 @@ -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// A simple example to provide a template for a custom tag handler. - /// - /// The recipe is as follows: - /// - /// 1. Create a new library project to contain your custom tag classes. DONE - /// 2. Add the dll as a reference to your project. DONE - /// 3. Create a public class with the same name as the tag you wish to handle. DONE - /// 4. Reference System.Xml and Animals.Utilities. DONE - /// 5. Add the [CustomTag] attribute to the class. DONE - /// 6. Create a default constructor that puts something in the "this.inputString" attribute. (This is - /// because AeonTagHandler inherits from the TextTransformer class and because of limitations with - /// instantiating late bound classes cannot call the "regular" AeonTagHandler constructor that would - /// put the XML node's InnerText into inputString). In any case this.inputString is not used by - /// AeonTagHandlers as they have direct access to the node to be processed (among other things - see below). - /// 7. Override the ProcessChange() method. This is where the work happens. Nota Bene: It is good - /// practice to check the name of the node being processed and return string.Empty if it doesn't match. - /// 8. By default the inner XML of the tag is recursively processed before the tag itself is processed. If - /// you want the result of the tag to be processed first and then the resulting inner XML then set the - /// this.isRecursive boolean flag to false (useful when working with tags similar to random or condition). - /// - /// When working within ProcessChange you have access to the following useful objects: - /// - /// this.templateNode - An XmlNode object that represents the tag you're processing - /// this.bot - An instance of Bot that represents the bot that is currently processing the input - /// this.user - An instance of User that represents the user who originated the current input - /// this.query - An instance of SubQuery that represents an individual query against the - /// graphmaster. Contains the various wildcard match collections - /// this.request - An instance of Request that encapsulates all sorts of useful information about - /// the input from the user - /// this.result - An instance of Result that encapsulates all sorts of useful information about - /// the output generated by the bot. - /// - /// Finally to load the dll into your bot call the loadCustomTagHandlers(string pathToDLL) method of the - /// Bot object that is your bot. An exception will be raised if you attempt to duplicate tag handling. - /// - [CustomTag] - public class Test : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - public Test() - { - InputString = "test"; - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "test") - { - return "The test tag handler works: " + TemplateNode.InnerText; - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/That.cs b/core/AeonTagHandlers/That.cs deleted file mode 100644 index ac0da8e..0000000 --- a/core/AeonTagHandlers/That.cs +++ /dev/null @@ -1,97 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The template-side that element indicates that an interpreter should substitute the contents of a previous bot output. - /// - /// The template-side that has an optional index attribute that may contain either a single integer or a comma-separated pair of integers. The minimum value for either of the integers in the index is "1". The index tells the interpreter which previous bot output should be returned (first dimension), and optionally which "sentence" (see [8.3.2.]) of the previous bot output (second dimension). - /// - /// The interpreter should raise an error if either of the specified index dimensions is invalid at run-time. - /// - /// An unspecified index is the equivalent of "1,1". An unspecified second dimension of the index is the equivalent of specifying a "1" for the second dimension. - /// - /// The template-side that element does not have any content. - /// - public class That : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public That(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "that") - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 0) - { - return ThisUser.GetThat(); - } - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "index") - { - if (TemplateNode.Attributes[0].Value.Length > 0) - { - try - { - // See if there is a split. - string[] dimensions = TemplateNode.Attributes[0].Value.Split(",".ToCharArray()); - if (dimensions.Length == 2) - { - int localResult = Convert.ToInt32(dimensions[0].Trim()); - int sentence = Convert.ToInt32(dimensions[1].Trim()); - if ((localResult > 0) & (sentence > 0)) - { - return ThisUser.GetThat(localResult - 1, sentence - 1); - } - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.That); - } - else - { - int localResult = Convert.ToInt32(TemplateNode.Attributes[0].Value.Trim()); - if (localResult > 0) - { - return ThisUser.GetThat(localResult - 1); - } - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.That); - } - } - catch - { - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.That); - } - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/ThatStar.cs b/core/AeonTagHandlers/ThatStar.cs deleted file mode 100644 index 1bc95c1..0000000 --- a/core/AeonTagHandlers/ThatStar.cs +++ /dev/null @@ -1,91 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The thatstar element tells the interpreter that it should substitute the contents of a wildcard from a pattern-side that element. - /// - /// The thatstar element has an optional integer index attribute that indicates which wildcard to use; the minimum acceptable value for the index is "1" (the first wildcard). - /// - /// An interpreter should raise an error if the index attribute of a star specifies a wildcard that does not exist in the that element's pattern content. Not specifying the index is the same as specifying an index of "1". - /// - /// The thatstar element does not have any content. - /// - public class ThatStar : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public ThatStar(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "thatstar") - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 0) - { - if (Query.ThatStar.Count > 0) - { - return Query.ThatStar[0]; - } - Logging.WriteLog("An out-of-bounds index to thatstar was encountered when processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.ThatStar); - } - else if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "index") - { - if (TemplateNode.Attributes[0].Value.Length > 0) - { - try - { - int result = Convert.ToInt32(TemplateNode.Attributes[0].Value.Trim()); - if (Query.ThatStar.Count > 0) - { - if (result > 0) - { - return Query.ThatStar[result - 1]; - } - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.ThatStar); - } - else - { - Logging.WriteLog("An out-of-bounds index to thatstar was encountered when processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.ThatStar); - } - } - catch - { - Logging.WriteLog("A thatstar tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.ThatStar); - } - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Think.cs b/core/AeonTagHandlers/Think.cs deleted file mode 100644 index a110674..0000000 --- a/core/AeonTagHandlers/Think.cs +++ /dev/null @@ -1,45 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The think element instructs the interpreter to perform all usual processing of its contents, but to not return any value, - /// regardless of whether the contents produce output. The think element has no attributes. It may contain any template elements. - /// - public class Think : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Think(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/TopicStar.cs b/core/AeonTagHandlers/TopicStar.cs deleted file mode 100644 index 7ba039c..0000000 --- a/core/AeonTagHandlers/TopicStar.cs +++ /dev/null @@ -1,89 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The topicstar element tells the interpreter that it should substitute the contents of a wildcard from the current topic (if the topic contains any wildcards). - /// - /// The topicstar element has an optional integer index attribute that indicates which wildcard to use; the minimum acceptable value for the index is "1" (the first wildcard). Not specifying the index is the same as specifying an index of "1". - /// - /// The topicstar element does not have any content. - /// - public class TopicStar : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public TopicStar(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "topicstar") - { - if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 0) - { - if (Query.TopicStar.Count > 0) - { - return Query.TopicStar[0]; - } - Logging.WriteLog("An out-of-bounds index to topicstar was encountered when processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.TopicStar); - } - else if (TemplateNode.Attributes != null && TemplateNode.Attributes.Count == 1) - { - if (TemplateNode.Attributes[0].Name.ToLower() == "index") - { - if (TemplateNode.Attributes[0].Value.Length > 0) - { - try - { - int result = Convert.ToInt32(TemplateNode.Attributes[0].Value.Trim()); - if (Query.TopicStar.Count > 0) - { - if (result > 0) - { - return Query.TopicStar[result - 1]; - } - Logging.WriteLog("An input tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.TopicStar); - } - else - { - Logging.WriteLog("An out-of-bounds index to topicstar was encountered when processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.TopicStar); - } - } - catch - { - Logging.WriteLog("A thatstar tag with a badly formed index (" + TemplateNode.Attributes[0].Value + ") was encountered processing the input: " + UserRequest.RawInput, Logging.LogType.Error, Logging.LogCaller.TopicStar); - } - } - } - } - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Uppercase.cs b/core/AeonTagHandlers/Uppercase.cs deleted file mode 100644 index 8460aa0..0000000 --- a/core/AeonTagHandlers/Uppercase.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The uppercase element tells the interpreter to render the contents of the element in uppercase, as defined (if defined) by the locale indicated by the specified language if specified). - /// - /// If no character in this string has a different uppercase version, based on the Unicode standard, then the original string is returned. - /// - public class Uppercase : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Uppercase(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "uppercase") - { - return TemplateNode.InnerText.ToUpper(ThisAeon.Locale); - } - return string.Empty; - } - } -} diff --git a/core/AeonTagHandlers/Version.cs b/core/AeonTagHandlers/Version.cs deleted file mode 100644 index 9a843f4..0000000 --- a/core/AeonTagHandlers/Version.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.AeonTagHandlers -{ - /// - /// The version element tells the interpreter that it should substitute the version number of the interpreter. The version element does not have any content. - /// - public class Version : AeonTagHandler - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - public Version(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, thisUser, query, userRequest, userResult, templateNode) - { - } - /// - /// The method that does the actual processing of the text. - /// - /// - /// The resulting processed text. - /// - protected override string ProcessChange() - { - if (TemplateNode.Name.ToLower() == "version") - { - return ThisAeon.GlobalSettings.GrabSetting("version"); - } - return string.Empty; - } - } -} diff --git a/core/Boagaphish/ActivationFunctions/BipolarSigmoidFunction.cs b/core/Boagaphish/ActivationFunctions/BipolarSigmoidFunction.cs deleted file mode 100644 index 9124331..0000000 --- a/core/Boagaphish/ActivationFunctions/BipolarSigmoidFunction.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.ActivationFunctions -{ - /// - /// The class represents bipolar sigmoid activation function with the next expression:
    - /// - /// 2 - /// f(x) = ------------------ - 1 - /// 1 + exp(-alpha * x) - /// - /// 2 * alpha * exp(-alpha * x ) - /// f'(x) = -------------------------------- = alpha * (1 - f(x)^2) / 2 - /// (1 + exp(-alpha * x))^2 - /// - /// Output range of the function is [-1, 1]. - ///
    - public class BipolarSigmoidFunction : IActivationFunction - { - private double _alpha = 2; - /// - /// Sigmoid's alpha value - /// - /// The alpha. - /// The value determines steepness of the function. Default value: 2. - /// - public double Alpha { get { return _alpha; } set { _alpha = value; } } - /// - /// Initializes a new instance of the class. Output range of the function is [-1, 1]. - /// - public BipolarSigmoidFunction() { } - /// - /// Initializes a new instance of the class. Output range of the function is [-1, 1]. - /// - /// The sigmoid alpha value. - public BipolarSigmoidFunction(double alpha) - { - _alpha = alpha; - } - /// - /// Calculates the function's value. The method calculates function value at point x. - /// - /// Function input value - /// Function output value, f(x). - public double Function(double x) - { - return ((2 / (1 + Math.Exp(-_alpha * x))) - 1); - } - /// - /// Calculates the function's derivative. The method calculates function derivative at point x. - /// - /// Function input value - /// Function derivative, f'(x). - public double Derivative(double x) - { - var y = Function(x); - - return (_alpha * (1 - y * y) / 2); - } - /// - /// Calculates the function's derivative. The method calculates the same derivative value as the method, but it takes not the input x value itself, but the function value, which was calculated previously with the help of method. (Some applications require as function value, as derivative value, so they can seve the amount of calculations using this method to calculate derivative). - /// - /// Function output value - the value, which was obtained with the help of method. - /// Function derivative, f'(x). - public double Derivative2(double y) - { - return (_alpha * (1 - y * y) / 2); - } - } -} diff --git a/core/Boagaphish/ActivationFunctions/GaussianFunction.cs b/core/Boagaphish/ActivationFunctions/GaussianFunction.cs deleted file mode 100644 index c820803..0000000 --- a/core/Boagaphish/ActivationFunctions/GaussianFunction.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.ActivationFunctions -{ - // Todo: Integrate the new NN code you spun into these classes. - /// - /// The sigmoid activation function. - /// - /// The class represents sigmoid activation function with the next expression:
    - /// - /// 1 - /// f(x) = ------------------ - /// 1 + exp(-alpha * x) - /// - /// alpha * exp(-alpha * x ) - /// f'(x) = ---------------------------- = alpha * f(x) * (1 - f(x)) - /// (1 + exp(-alpha * x))^2 - /// - /// Output range of the function: [0, 1]

    - /// Functions graph:
    - /// - ///
    - public class GaussianFunction : IActivationFunction - { - // sigmoid's alpha value - private double _alpha = 2; - /// - /// Sigmoid's alpha value - /// - /// The alpha. - /// The value determines steepness of the function. Default value: 2. - /// - public double Alpha { get { return _alpha; } set { _alpha = value; } } - /// - /// Initializes a new instance of the class - /// - public GaussianFunction() { } - /// - /// Initializes a new instance of the class - /// - /// Sigmoid's alpha value - public GaussianFunction(double alpha) - { - _alpha = alpha; - } - /// - /// Calculates function value - /// - /// Function input value - /// Function output value, f(x) - /// The method calculates function value at point x. - public double Function(double x) - { - return (1 / (1 + Math.Exp(-_alpha * x))); - } - /// - /// Calculates the function derivative. The method calculates function derivative at point x. - /// - /// Function input value - /// Function derivative, f'(x) - public double Derivative(double x) - { - double y = Function(x); - - return (_alpha * y * (1 - y)); - } - /// - /// Calculates the derivative of a function. - /// - /// Function output value - the value, which was obtained with the help of method. - /// Function derivative, f'(x) - /// The method calculates the same derivative value as the method, but it takes not the input x value itself, but the function value, which was calculated previously with the help of method. (Some applications require as function value, as derivative value, so they can seve the amount of calculations using this method to calculate derivative) - public double Derivative2(double y) - { - return (_alpha * y * (1 - y)); - } - } -} diff --git a/core/Boagaphish/ActivationFunctions/IActivationFunction.cs b/core/Boagaphish/ActivationFunctions/IActivationFunction.cs deleted file mode 100644 index fcc3202..0000000 --- a/core/Boagaphish/ActivationFunctions/IActivationFunction.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.ActivationFunctions -{ - /// - /// Activation function interface. - /// - /// All activation functions, which are supposed to be used with neurons, which calculate their output as a function of weighted sum of their inputs, should implement this interfaces. - /// - public interface IActivationFunction - { - /// - /// Calculates function value - /// - /// Function input value - /// Function output value, f(x) - /// The method calculates function value at point x. - double Function(double x); - /// - /// Calculates function derivative - /// - /// Function input value - /// Function derivative, f'(x) - /// The method calculates function derivative at point x. - double Derivative(double x); - /// - /// Calculates function derivative - /// - /// Function output value - the value, which was obtained - /// with the help of method - /// Function derivative, f'(x) - /// The method calculates the same derivative value as the - /// method, but it takes not the input x value itself, but the function value, which was calculated previously with the help of method. (Some applications require as function value, as derivative value, so they can seve the amount of calculations using this method to calculate derivative) - double Derivative2(double y); - } -} diff --git a/core/Boagaphish/ActivationFunctions/SigmoidFunction.cs b/core/Boagaphish/ActivationFunctions/SigmoidFunction.cs deleted file mode 100644 index b3db93c..0000000 --- a/core/Boagaphish/ActivationFunctions/SigmoidFunction.cs +++ /dev/null @@ -1,80 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.ActivationFunctions -{ - /// - /// The sigmoid activation function. - /// - /// The class represents sigmoid activation function with the next expression:
    - /// - /// 1 - /// f(x) = ------------------ - /// 1 + exp(-alpha * x) - /// - /// alpha * exp(-alpha * x ) - /// f'(x) = ---------------------------- = alpha * f(x) * (1 - f(x)) - /// (1 + exp(-alpha * x))^2 - /// - /// Output range of the function: [0, 1]

    - /// Functions graph:
    - /// - ///
    - public class SigmoidFunction : IActivationFunction - { - // sigmoid's alpha value - private double _alpha = 2; - /// - /// Sigmoid's alpha value - /// - /// The alpha. - /// The value determines steepness of the function. Default value: 2. - /// - public double Alpha { get { return _alpha; } set { _alpha = value; } } - /// - /// Initializes a new instance of the class - /// - public SigmoidFunction() { } - /// - /// Initializes a new instance of the class - /// - /// Sigmoid's alpha value - public SigmoidFunction(double alpha) - { - _alpha = alpha; - } - /// - /// Calculates function value - /// - /// Function input value - /// Function output value, f(x) - /// The method calculates function value at point x. - public double Function(double x) - { - return (1 / (1 + Math.Exp(-_alpha * x))); - } - /// - /// Calculates the function derivative. The method calculates function derivative at point x. - /// - /// Function input value - /// Function derivative, f'(x) - public double Derivative(double x) - { - double y = Function(x); - - return (_alpha * y * (1 - y)); - } - /// - /// Calculates the derivative of a function. - /// - /// Function output value - the value, which was obtained with the help of method. - /// Function derivative, f'(x) - /// The method calculates the same derivative value as the method, but it takes not the input x value itself, but the function value, which was calculated previously with the help of method. (Some applications require as function value, as derivative value, so they can seve the amount of calculations using this method to calculate derivative) - public double Derivative2(double y) - { - return (_alpha * y * (1 - y)); - } - } -} diff --git a/core/Boagaphish/ActivationFunctions/ThresholdFunction.cs b/core/Boagaphish/ActivationFunctions/ThresholdFunction.cs deleted file mode 100644 index 3f9cb4c..0000000 --- a/core/Boagaphish/ActivationFunctions/ThresholdFunction.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.ActivationFunctions -{ - /// - /// The threshold activation function. - /// - /// The class represents threshold activation function with the next expression:
    - /// - /// f(x) = 1, if x >= 0, otherwise 0 - /// - /// Output range of the function: [0, 1]

    - /// Functions graph:
    - /// - ///
    - public class ThresholdFunction : IActivationFunction - { - /// - /// Calculates the function value. The method calculates function value at point x - /// - /// Function input value - /// Function output value, f(x) - public double Function(double x) - { - return (x >= 0) ? 1 : 0; - } - /// - /// Not supported. (Why not?) - /// - /// Input value - /// Always returns 0 - /// The method is not supported, because it is not possible to - /// calculate derivative of the function. - public double Derivative(double x) - { - double y = Function(x); - - return 0; - } - /// - /// Not supported. (Why not?) - /// - /// Input value - /// Always returns 0 - /// The method is not supported, because it is not possible to - /// calculate derivative of the function. - public double Derivative2(double y) - { - return 0; - } - } -} diff --git a/core/Boagaphish/ActivationFunctions/VanderPolFunction.cs b/core/Boagaphish/ActivationFunctions/VanderPolFunction.cs deleted file mode 100644 index 894252e..0000000 --- a/core/Boagaphish/ActivationFunctions/VanderPolFunction.cs +++ /dev/null @@ -1,80 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.ActivationFunctions -{ - /// - /// Todo: Needs to be implemented. - /// - /// The class represents sigmoid activation function with the next expression:
    - /// - /// 1 - /// f(x) = ------------------ - /// 1 + exp(-alpha * x) - /// - /// alpha * exp(-alpha * x ) - /// f'(x) = ---------------------------- = alpha * f(x) * (1 - f(x)) - /// (1 + exp(-alpha * x))^2 - /// - /// Output range of the function: [0, 1]

    - /// Functions graph:
    - /// - ///
    - public class VanderPolFunction : IActivationFunction - { - // sigmoid's alpha value - private double _mu = 0.1; - /// - /// Sigmoid's alpha value - /// - /// The alpha. - /// The value determines steepness of the function. Default value: 2. - /// - public double Mu { get { return _mu; } set { _mu = value; } } - /// - /// Initializes a new instance of the class - /// - public VanderPolFunction() { } - /// - /// Initializes a new instance of the class - /// - /// Sigmoid's alpha value - public VanderPolFunction(double mu) - { - _mu = mu; - } - /// - /// Calculates function value - /// - /// Function input value - /// Function output value, f(x) - /// The method calculates function value at point x. - public double Function(double x) - { - return (1 / (1 + Math.Exp(-_mu * x))); - } - /// - /// Calculates the function derivative. The method calculates function derivative at point x. - /// - /// Function input value - /// Function derivative, f'(x) - public double Derivative(double x) - { - double y = Function(x); - - return (_mu * y * (1 - y)); - } - /// - /// Calculates the second derivative of a function. - /// - /// Function output value - the value, which was obtained with the help of method. - /// Function derivative, f''(x) - /// The method calculates the same derivative value as the method, but it takes not the input x value itself, but the function value, which was calculated previously with the help of method. (Some applications require as function value, as derivative value, so they can seve the amount of calculations using this method to calculate derivative) - public double Derivative2(double y) - { - return (_mu * y * (1 - y)); - } - } -} diff --git a/core/Boagaphish/Core/Animals/BackPropagation.cs b/core/Boagaphish/Core/Animals/BackPropagation.cs deleted file mode 100644 index 782b55e..0000000 --- a/core/Boagaphish/Core/Animals/BackPropagation.cs +++ /dev/null @@ -1,196 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using Boagaphish.ActivationFunctions; -using Boagaphish.Core.Layers; -using Boagaphish.Core.Learning; -using Boagaphish.Core.Networks; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Animals -{ - public class BackPropagation : ISupervised - { - private readonly ActivationNetwork _network; - private double _learningRate; - private double _momentum; - private readonly double[][] _neuronErrors; - private readonly double[][][] _weightsUpdates; - private readonly double[][] _thresholdUpdates; - - public double LearningRate - { - get - { - return _learningRate; - } - set - { - _learningRate = Math.Max(0.0, Math.Min(1.0, value)); - } - } - - public double Momentum - { - get - { - return _momentum; - } - set - { - _momentum = Math.Max(0.0, Math.Min(1.0, value)); - } - } - /// - /// Initializes a new instance of the class. - /// - /// The network. - /// The learning rate. - public BackPropagation(ActivationNetwork network, double learningRate = 0.1) - { - _learningRate = learningRate; - _network = network; - _neuronErrors = new double[network.LayersCount][]; - _weightsUpdates = new double[network.LayersCount][][]; - _thresholdUpdates = new double[network.LayersCount][]; - int i = 0; - for (int layersCount = network.LayersCount; i < layersCount; i++) - { - Layer layer = network[i]; - _neuronErrors[i] = new double[layer.NeuronsCount]; - _weightsUpdates[i] = new double[layer.NeuronsCount][]; - _thresholdUpdates[i] = new double[layer.NeuronsCount]; - for (int j = 0; j < layer.NeuronsCount; j++) - { - _weightsUpdates[i][j] = new double[layer.InputsCount]; - } - } - } - - public double Run(double[] input, double[] desired) - { - _network.Compute(input); - double result = CalculateError(desired); - CalculateUpdates(input); - UpdateNetwork(); - return result; - } - - public double RunEpoch(double[][] input, double[][] desired) - { - double num = 0.0; - int i = 0; - for (int num2 = input.Length; i < num2; i++) - { - num += Run(input[i], desired[i]); - } - return num; - } - - private double CalculateError(IList desired) - { - double num = 0.0; - int layersCount = _network.LayersCount; - IActivationFunction activationFunction = _network[0][0].ActivationFunction; - ActivationLayer activationLayer = _network[layersCount - 1]; - double[] array = _neuronErrors[layersCount - 1]; - int i = 0; - for (int neuronsCount = activationLayer.NeuronsCount; i < neuronsCount; i++) - { - double output = activationLayer[i].Output; - double num2 = desired[i] - output; - array[i] = num2 * activationFunction.Derivative2(output); - num += num2 * num2; - } - for (int num3 = layersCount - 2; num3 >= 0; num3--) - { - activationLayer = _network[num3]; - ActivationLayer activationLayer2 = _network[num3 + 1]; - array = _neuronErrors[num3]; - double[] array2 = _neuronErrors[num3 + 1]; - int j = 0; - for (int neuronsCount2 = activationLayer.NeuronsCount; j < neuronsCount2; j++) - { - double num4 = 0.0; - int k = 0; - for (int neuronsCount3 = activationLayer2.NeuronsCount; k < neuronsCount3; k++) - { - num4 += array2[k] * ((Neuron)activationLayer2[k])[j]; - } - array[j] = num4 * activationFunction.Derivative2(activationLayer[j].Output); - } - } - return num / 2.0; - } - - private void CalculateUpdates(double[] input) - { - ActivationLayer activationLayer = _network[0]; - double[] array = _neuronErrors[0]; - double[][] array2 = _weightsUpdates[0]; - double[] array3 = _thresholdUpdates[0]; - int i = 0; - for (int neuronsCount = activationLayer.NeuronsCount; i < neuronsCount; i++) - { - ActivationNeuron activationNeuron = activationLayer[i]; - double num = array[i]; - double[] array4 = array2[i]; - int j = 0; - for (int inputsCount = activationNeuron.InputsCount; j < inputsCount; j++) - { - array4[j] = _learningRate * (_momentum * array4[j] + (1.0 - _momentum) * num * input[j]); - } - array3[i] = _learningRate * (_momentum * array3[i] + (1.0 - _momentum) * num); - } - int k = 1; - for (int layersCount = _network.LayersCount; k < layersCount; k++) - { - ActivationLayer activationLayer2 = _network[k - 1]; - activationLayer = _network[k]; - array = _neuronErrors[k]; - array2 = _weightsUpdates[k]; - array3 = _thresholdUpdates[k]; - int l = 0; - for (int neuronsCount2 = activationLayer.NeuronsCount; l < neuronsCount2; l++) - { - ActivationNeuron activationNeuron = activationLayer[l]; - double num = array[l]; - double[] array4 = array2[l]; - int m = 0; - for (int inputsCount2 = activationNeuron.InputsCount; m < inputsCount2; m++) - { - array4[m] = _learningRate * (_momentum * array4[m] + (1.0 - _momentum) * num * activationLayer2[m].Output); - } - array3[l] = _learningRate * (_momentum * array3[l] + (1.0 - _momentum) * num); - } - } - } - - private void UpdateNetwork() - { - int i = 0; - for (int layersCount = _network.LayersCount; i < layersCount; i++) - { - ActivationLayer activationLayer = _network[i]; - double[][] array = _weightsUpdates[i]; - double[] array2 = _thresholdUpdates[i]; - int j = 0; - for (int neuronsCount = activationLayer.NeuronsCount; j < neuronsCount; j++) - { - ActivationNeuron activationNeuron = activationLayer[j]; - double[] array3 = array[j]; - int k = 0; - for (int inputsCount = activationNeuron.InputsCount; k < inputsCount; k++) - { - ActivationNeuron activationNeuron2 = activationNeuron; - int index = k; - ((Neuron)activationNeuron2)[index] += array3[k]; - } - activationNeuron.Threshold += array2[j]; - } - } - } - } -} diff --git a/core/Boagaphish/Core/Animals/BackPropagationNetwork.cs b/core/Boagaphish/Core/Animals/BackPropagationNetwork.cs deleted file mode 100644 index 5b30eca..0000000 --- a/core/Boagaphish/Core/Animals/BackPropagationNetwork.cs +++ /dev/null @@ -1,408 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Xml; -using Boagaphish.Numeric; - -namespace Boagaphish.Core.Animals -{ - public class BackPropagationNetwork - { - private int _layerCount; - - private int _inputSize; - - private int[] _layerSize; - - private double[][] _layerOutput; - - private double[][] _layerInput; - - private double[][] _delta; - - private double[][] _previousBiasDelta; - - private double[][][] _previousWeightDelta; - - private XmlDocument _document; - - public TransferFunction[] TransferFunction; - - public double[][] Bias; - - public double[][][] Weight; - - public double[] ZerothSum; - - public double[] FirstSum; - - public double FirstToSecondLayerResult; - - public double NextToOutputLayerResult; - - public string Name - { - get; - set; - } - - public BackPropagationNetwork(IList layerSizes, IList transferFunctions, string name = "Candles") - { - Name = name; - if (transferFunctions.Count != layerSizes.Count || transferFunctions[0] != 0) - { - throw new ArgumentException("Cannot initiate on those parameters."); - } - _layerCount = layerSizes.Count - 1; - _inputSize = layerSizes[0]; - _layerSize = new int[_layerCount]; - for (int i = 0; i < _layerCount; i++) - { - _layerSize[i] = layerSizes[i + 1]; - } - TransferFunction = new TransferFunction[_layerCount]; - for (int j = 0; j < _layerCount; j++) - { - TransferFunction[j] = transferFunctions[j + 1]; - } - Bias = new double[_layerCount][]; - _previousBiasDelta = new double[_layerCount][]; - _delta = new double[_layerCount][]; - _layerOutput = new double[_layerCount][]; - _layerInput = new double[_layerCount][]; - Weight = new double[_layerCount][][]; - _previousWeightDelta = new double[_layerCount][][]; - for (int k = 0; k < _layerCount; k++) - { - Bias[k] = new double[_layerSize[k]]; - _previousBiasDelta[k] = new double[_layerSize[k]]; - _delta[k] = new double[_layerSize[k]]; - _layerOutput[k] = new double[_layerSize[k]]; - _layerInput[k] = new double[_layerSize[k]]; - Weight[k] = new double[(k == 0) ? _inputSize : _layerSize[k - 1]][]; - _previousWeightDelta[k] = new double[(k == 0) ? _inputSize : _layerSize[k - 1]][]; - for (int l = 0; l < ((k == 0) ? _inputSize : _layerSize[k - 1]); l++) - { - Weight[k][l] = new double[_layerSize[k]]; - _previousWeightDelta[k][l] = new double[_layerSize[k]]; - } - } - for (int m = 0; m < _layerCount; m++) - { - for (int n = 0; n < _layerSize[m]; n++) - { - Bias[m][n] = Gaussian.RandomGaussian(); - _previousBiasDelta[m][n] = 0.0; - _layerOutput[m][n] = 0.0; - _layerInput[m][n] = 0.0; - _delta[m][n] = 0.0; - } - for (int num = 0; num < ((m == 0) ? _inputSize : _layerSize[m - 1]); num++) - { - for (int num2 = 0; num2 < _layerSize[m]; num2++) - { - Weight[m][num][num2] = Gaussian.RandomGaussian(); - _previousWeightDelta[m][num][num2] = 0.0; - } - } - } - } - - public BackPropagationNetwork(string filePath) - { - LoadNetworkXml(filePath); - } - - protected BackPropagationNetwork() - { - } - - public void RunEvaluation(ref double[] input, out double[] output) - { - if (input.Length != _inputSize) - { - throw new ArgumentException("Input data is not of the correct dimension."); - } - output = new double[_layerSize[_layerCount - 1]]; - for (int i = 0; i < _layerCount; i++) - { - for (int j = 0; j < _layerSize[i]; j++) - { - double num = 0.0; - for (int k = 0; k < ((i == 0) ? _inputSize : _layerSize[i - 1]); k++) - { - num += Weight[i][k][j] * ((i == 0) ? input[k] : _layerOutput[i - 1][k]); - } - num += Bias[i][j]; - _layerInput[i][j] = num; - _layerOutput[i][j] = TransferFunctions.Evaluate(TransferFunction[i], num, 0.5); - } - } - for (int l = 0; l < _layerSize[_layerCount - 1]; l++) - { - output[l] = _layerOutput[_layerCount - 1][l]; - } - } - - public double ComputeSoftmax(double[] input, string layer) - { - double result = 0.0; - for (int i = 0; i < _layerCount; i++) - { - ZerothSum[i] += input[i] * Weight[0][0][i] + input[i] * Weight[i][0][0]; - ZerothSum[i] += Bias[0][i]; - FirstSum[i] += input[i] * Weight[0][i][0] + input[i] * Weight[i][i][0]; - FirstSum[i] += Bias[i][0]; - FirstToSecondLayerResult = Softmax(ZerothSum[i], "ih"); - NextToOutputLayerResult = Softmax(FirstSum[i], "ho"); - result = 0.5 * Math.Pow(FirstToSecondLayerResult * NextToOutputLayerResult, 2.0); - } - return result; - } - - protected double Softmax(double x, string layer) - { - double num = -1.7976931348623157E+308; - if (layer == "ih") - { - num = ((ZerothSum[0] > ZerothSum[1]) ? ZerothSum[0] : ZerothSum[1]); - } - else if (layer == "ho") - { - num = ((FirstSum[0] > FirstSum[1]) ? FirstSum[0] : FirstSum[1]); - } - double num2 = 0.0; - if (layer == "ih") - { - num2 = Math.Exp(ZerothSum[0] - num) + Math.Exp(ZerothSum[1] - num); - } - else if (layer == "ho") - { - num2 = Math.Exp(FirstSum[0] - num) + Math.Exp(FirstSum[1] - num); - } - return Math.Exp(x - num) / num2; - } - - public double Train(ref double[] input, ref double[] desired, double trainingRate, double momentum) - { - if (input.Length != _inputSize) - { - throw new ArgumentException("Invalid input parameter", "input"); - } - if (desired.Length != _layerSize[_layerCount - 1]) - { - throw new ArgumentException("Invalid input parameter", "desired"); - } - double num = 0.0; - double[] array = new double[_layerSize[_layerCount - 1]]; - RunEvaluation(ref input, out array); - for (int num2 = _layerCount - 1; num2 >= 0; num2--) - { - if (num2 == _layerCount - 1) - { - for (int i = 0; i < _layerSize[num2]; i++) - { - _delta[num2][i] = array[i] - desired[i]; - num += Math.Pow(_delta[num2][i], 2.0); - _delta[num2][i] *= TransferFunctions.EvaluateDerivative(TransferFunction[num2], _layerInput[num2][i], 0.5); - } - } - else - { - for (int j = 0; j < _layerSize[num2]; j++) - { - double num3 = 0.0; - for (int k = 0; k < _layerSize[num2 + 1]; k++) - { - num3 += Weight[num2 + 1][j][k] * _delta[num2 + 1][k]; - } - num3 *= TransferFunctions.EvaluateDerivative(TransferFunction[num2], _layerInput[num2][j], 0.5); - _delta[num2][j] = num3; - } - } - } - for (int l = 0; l < _layerCount; l++) - { - for (int m = 0; m < ((l == 0) ? _inputSize : _layerSize[l - 1]); m++) - { - for (int n = 0; n < _layerSize[l]; n++) - { - double num4 = trainingRate * _delta[l][n] * ((l == 0) ? input[m] : _layerOutput[l - 1][m]) + momentum * _previousWeightDelta[l][m][n]; - Weight[l][m][n] -= num4; - _previousWeightDelta[l][m][n] = num4; - } - } - } - for (int num5 = 0; num5 < _layerCount; num5++) - { - for (int num6 = 0; num6 < _layerSize[num5]; num6++) - { - double num7 = trainingRate * _delta[num5][num6]; - Bias[num5][num6] -= num7 + momentum * _previousBiasDelta[num5][num6]; - _previousBiasDelta[num5][num6] = num7; - } - } - return num; - } - - public void SaveNetworkXml(string filePath) - { - if (filePath != null) - { - XmlWriter xmlWriter = XmlWriter.Create(filePath); - xmlWriter.WriteStartElement("NeuralNetwork"); - xmlWriter.WriteAttributeString("Type", "BackPropagation"); - xmlWriter.WriteStartElement("Parameters"); - xmlWriter.WriteElementString("Name", Name); - xmlWriter.WriteElementString("inputSize", _inputSize.ToString(CultureInfo.InvariantCulture)); - xmlWriter.WriteElementString("layerCount", _layerCount.ToString(CultureInfo.InvariantCulture)); - xmlWriter.WriteStartElement("Layers"); - for (int i = 0; i < _layerCount; i++) - { - xmlWriter.WriteStartElement("Layer"); - xmlWriter.WriteAttributeString("Index", i.ToString(CultureInfo.InvariantCulture)); - xmlWriter.WriteAttributeString("Size", _layerSize[i].ToString(CultureInfo.InvariantCulture)); - xmlWriter.WriteAttributeString("Type", TransferFunction[i].ToString()); - xmlWriter.WriteEndElement(); - } - xmlWriter.WriteEndElement(); - xmlWriter.WriteEndElement(); - xmlWriter.WriteStartElement("Weights"); - for (int j = 0; j < _layerCount; j++) - { - xmlWriter.WriteStartElement("Layer"); - xmlWriter.WriteAttributeString("Index", j.ToString(CultureInfo.InvariantCulture)); - for (int k = 0; k < _layerSize[j]; k++) - { - xmlWriter.WriteStartElement("Node"); - xmlWriter.WriteAttributeString("Index", k.ToString(CultureInfo.InvariantCulture)); - xmlWriter.WriteAttributeString("Bias", Bias[j][k].ToString(CultureInfo.InvariantCulture)); - for (int l = 0; l < ((j == 0) ? _inputSize : _layerSize[j - 1]); l++) - { - xmlWriter.WriteStartElement("Axion"); - xmlWriter.WriteAttributeString("Index", l.ToString(CultureInfo.InvariantCulture)); - xmlWriter.WriteString(Weight[j][l][k].ToString(CultureInfo.InvariantCulture)); - xmlWriter.WriteEndElement(); - } - xmlWriter.WriteEndElement(); - } - xmlWriter.WriteEndElement(); - } - xmlWriter.WriteEndElement(); - xmlWriter.WriteEndElement(); - xmlWriter.Flush(); - xmlWriter.Close(); - } - } - - public void LoadNetworkXml(string filePath) - { - if (filePath != null) - { - _document = new XmlDocument(); - _document.Load(filePath); - string str = "NeuralNetwork/Parameters/"; - if (!(XPathValue("NeuralNetwork/@Type") != "BackPropagation")) - { - Name = XPathValue(str + "Name"); - int.TryParse(XPathValue(str + "inputSize"), out _inputSize); - int.TryParse(XPathValue(str + "layerCount"), out _layerCount); - _layerSize = new int[_layerCount]; - TransferFunction = new TransferFunction[_layerCount]; - str = "NeuralNetwork/Parameters/Layers/Layer"; - for (int i = 0; i < _layerCount; i++) - { - int.TryParse(XPathValue(str + "[@Index='" + i.ToString(CultureInfo.InvariantCulture) + "']/@Size"), out _layerSize[i]); - Enum.TryParse(XPathValue(str + "[@Index='" + i.ToString(CultureInfo.InvariantCulture) + "']/@Type"), out TransferFunction[i]); - } - Bias = new double[_layerCount][]; - _previousBiasDelta = new double[_layerCount][]; - _delta = new double[_layerCount][]; - _layerOutput = new double[_layerCount][]; - _layerInput = new double[_layerCount][]; - Weight = new double[_layerCount][][]; - _previousWeightDelta = new double[_layerCount][][]; - for (int j = 0; j < _layerCount; j++) - { - Bias[j] = new double[_layerSize[j]]; - _previousBiasDelta[j] = new double[_layerSize[j]]; - _delta[j] = new double[_layerSize[j]]; - _layerOutput[j] = new double[_layerSize[j]]; - _layerInput[j] = new double[_layerSize[j]]; - Weight[j] = new double[(j == 0) ? _inputSize : _layerSize[j - 1]][]; - _previousWeightDelta[j] = new double[(j == 0) ? _inputSize : _layerSize[j - 1]][]; - for (int k = 0; k < ((j == 0) ? _inputSize : _layerSize[j - 1]); k++) - { - Weight[j][k] = new double[_layerSize[j]]; - _previousWeightDelta[j][k] = new double[_layerSize[j]]; - } - } - for (int l = 0; l < _layerCount; l++) - { - str = "NeuralNetwork/Weights/Layer[@Index='" + l.ToString(CultureInfo.InvariantCulture) + "']/"; - double num; - for (int m = 0; m < _layerSize[l]; m++) - { - string str2 = "Node[@Index='" + m.ToString(CultureInfo.InvariantCulture) + "']/@Bias"; - double.TryParse(XPathValue(str + str2), out num); - Bias[l][m] = num; - _previousBiasDelta[l][m] = 0.0; - _layerOutput[l][m] = 0.0; - _layerInput[l][m] = 0.0; - _delta[l][m] = 0.0; - } - for (int n = 0; n < ((l == 0) ? _inputSize : _layerSize[l - 1]); n++) - { - for (int num2 = 0; num2 < _layerSize[l]; num2++) - { - string str2 = "Node[@Index='" + num2.ToString(CultureInfo.InvariantCulture) + "']/Axion[@Index='" + n.ToString(CultureInfo.InvariantCulture) + "']"; - double.TryParse(XPathValue(str + str2), out num); - Weight[l][n][num2] = num; - _previousWeightDelta[l][n][num2] = 0.0; - } - } - } - _document = null; - } - } - } - - private string XPathValue(string xPath) - { - XmlNode xmlNode = _document.SelectSingleNode(xPath); - if (xmlNode == null) - { - throw new ArgumentException("Cannot find specified node.", xPath); - } - return xmlNode.InnerText; - } - - public double[] Compute(double[] input) - { - if (input.Length != _inputSize) - { - throw new ArgumentException("Input data is not of the correct dimension."); - } - double[] array = new double[_layerSize[_layerCount - 1]]; - for (int i = 0; i < _layerCount; i++) - { - for (int j = 0; j < _layerSize[i]; j++) - { - double num = 0.0; - for (int k = 0; k < ((i == 0) ? _inputSize : _layerSize[i - 1]); k++) - { - num += Weight[i][k][j] * ((i == 0) ? input[k] : _layerOutput[i - 1][k]); - } - num += Bias[i][j]; - _layerInput[i][j] = num; - _layerOutput[i][j] = TransferFunctions.Evaluate(TransferFunction[i], num, 0.5); - } - } - for (int l = 0; l < _layerSize[_layerCount - 1]; l++) - { - array[l] = _layerOutput[_layerCount - 1][l]; - } - return array; - } - } -} diff --git a/core/Boagaphish/Core/Animals/Cell.cs b/core/Boagaphish/Core/Animals/Cell.cs deleted file mode 100644 index eb5724a..0000000 --- a/core/Boagaphish/Core/Animals/Cell.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Runtime.InteropServices; - -namespace Boagaphish.Core.Animals -{ - [StructLayout(LayoutKind.Sequential, Size = 1)] - public struct Cell - { - [StructLayout(LayoutKind.Sequential, Size = 1)] - public struct Coordinate - { - public static int X0 - { - get; - set; - } - - public static int Y0 - { - get; - set; - } - - public static int X1 - { - get; - set; - } - - public static int Y1 - { - get; - set; - } - - public static int T1 - { - get; - set; - } - - public static int T2 - { - get; - set; - } - } - } -} diff --git a/core/Boagaphish/Core/Animals/Gaussian.cs b/core/Boagaphish/Core/Animals/Gaussian.cs deleted file mode 100644 index 35283c9..0000000 --- a/core/Boagaphish/Core/Animals/Gaussian.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.Format; - -namespace Boagaphish.Core.Animals -{ - public static class Gaussian - { - private static readonly StaticRandom Generator = new StaticRandom(); - private const double Epsilon = 1E-06; - - public static double RandomGaussian() - { - return RandomGaussian(0.0, 1.0); - } - - public static double RandomGaussian(double mean, double standardDeviation) - { - double result; - double num; - RandomGaussian(mean, standardDeviation, out result, out num); - return result; - } - - public static void RandomGaussian(double mean, double standardDeviation, out double valueOne, out double valueTwo) - { - double num; - double num2; - do - { - num = 2.0 * Generator.NextDouble() - 1.0; - num2 = 2.0 * Generator.NextDouble() - 1.0; - } - while (num * num + num2 * num2 > 1.0 || (Math.Abs(num) < Epsilon && Math.Abs(num2) < Epsilon)); - var num3 = num * num + num2 * num2; - var num4 = Math.Sqrt(-2.0 * Math.Log(num3) / num3); - valueOne = standardDeviation * num * num4 + mean; - valueTwo = standardDeviation * num2 * num4 + mean; - } - } -} diff --git a/core/Boagaphish/Core/Decision/Decider.cs b/core/Boagaphish/Core/Decision/Decider.cs deleted file mode 100644 index c27ab1c..0000000 --- a/core/Boagaphish/Core/Decision/Decider.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Core.Decision -{ - /// - /// Collect all data before sending to the area where a decision is contemplated. - /// - public class Decider - { - public Decider(bool analyze) - { - if (analyze) - { - - } - } - public static bool DecideNegative { get; set; } - public static bool DecidePositive { get; set; } - - public static void MakeDecisionBasedOnTrend(double[,] inputs) - { - // Does the solution suggest an upward or downward trend? - if (inputs[0,0] > 1) - { - DecideNegative = false; - DecidePositive = true; - } - if (inputs[0,0] < 1) - { - DecideNegative = true; - DecidePositive = false; - } - } - } -} diff --git a/core/Boagaphish/Core/Dendrites/Dendrite.cs b/core/Boagaphish/Core/Dendrites/Dendrite.cs deleted file mode 100644 index eb50c3a..0000000 --- a/core/Boagaphish/Core/Dendrites/Dendrite.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Core.Dendrites -{ - public abstract class Dendrite - { - } -} diff --git a/core/Boagaphish/Core/Extensions.cs b/core/Boagaphish/Core/Extensions.cs deleted file mode 100644 index e71d1d7..0000000 --- a/core/Boagaphish/Core/Extensions.cs +++ /dev/null @@ -1,161 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; -using System.Collections.Generic; -using Boagaphish.Core.Networks; -using Boagaphish.Numeric; -using BackPropagationNetwork = Boagaphish.Core.Animals.BackPropagationNetwork; - -namespace Boagaphish.Core -{ - public static class Extensions - { - static ArrayList Input { get; set; } - static ArrayList FirstInputWeights { get; set; } - static double FirstSum { get; set; } - static double FirstResult { get; set; } - static ArrayList SecondInputWeights { get; set; } - static double SecondSum { get; set; } - static double SecondResult { get; set; } - static double ThirdSum { get; set; } - static double Summy { get; set; } - static double AverageSummy { get; set; } - static double X { get; set; } - static double Softmax { get; set; } - - public static double ComputeSoftmax(this BackPropagationNetwork network, Network.CrossLayer crossLayer, double[] input) - { - //var output = 0.0; - - Input = new ArrayList(); - FirstInputWeights = new ArrayList(); - SecondInputWeights = new ArrayList(); - // Create the array list. - for (int i = 0; i < input.Length; i++) - { - Input.Add(input[i]); - } - // Process the inputs and sums for the first set. - for (int i = 0; i < input.Length; i++) - { - if (i != i % 2) - { - for (int j = 0; j < network.Weight[0][i].Length; j++) - { - FirstInputWeights.Add(network.Weight[0][i][j]); - } - FirstSum += Convert.ToDouble(Input[i]) * Convert.ToDouble(FirstInputWeights[i]); - FirstSum += Convert.ToDouble(network.Bias[0][i]); - FirstInputWeights = new ArrayList(); - } - if (i == i % 2) - { - for (int j = 0; j < network.Weight[0][i].Length; j++) - { - SecondInputWeights.Add(network.Weight[0][i][j]); - } - SecondSum += Convert.ToDouble(Input[i]) * Convert.ToDouble(SecondInputWeights[i]); - SecondSum += Convert.ToDouble(network.Bias[0][i]); - SecondInputWeights = new ArrayList(); - } - } - // Run an evaluation on the sums based on the chosen governing ODE. - FirstResult = FirstSum.Evaluate(network.TransferFunction[0]); - SecondResult = SecondSum.Evaluate(network.TransferFunction[0]); - // Process the next set of sums. - for (int k = 0; k < network.Weight[0][1].Length; k++) - { - Summy += Convert.ToDouble(network.Weight[1][k][0]); - AverageSummy = Summy / network.Weight[0][1].Length; - ThirdSum += Convert.ToDouble(network.Bias[0][k]); - } - ThirdSum += (FirstResult * AverageSummy) + (SecondResult * AverageSummy); - // Finally, compute the softmax result. Determine the maximum value. - double max = Double.MinValue; - if (crossLayer == Network.CrossLayer.InputHidden) - max = (FirstSum > SecondSum) ? FirstSum : SecondSum; - else if (crossLayer == Network.CrossLayer.HiddenOutput) - max = (ThirdSum > ThirdSum) ? ThirdSum : ThirdSum; - // Compute the scale. - double scale = 0.0; - if (crossLayer == Network.CrossLayer.InputHidden) - scale = Math.Exp(FirstSum - max) + Math.Exp(SecondSum - max); - else if (crossLayer == Network.CrossLayer.HiddenOutput) - scale = Math.Exp(ThirdSum - max) + Math.Exp(ThirdSum - max); - X = 0.5 * (FirstResult + SecondResult); - // Return to Softmax. - Softmax = Math.Exp(X - max) / scale; - - return Softmax; - } - public static double Evaluate(this double value, TransferFunction transferFunction) - { - return TransferFunctions.Evaluate(transferFunction, value); - } - - public static bool IsGreaterThan(this double value, double comparisonValue) - { - if (value > comparisonValue) - return true; - return false; - } - public static bool IsLessThan(this double value, double comparisonValue) - { - if (value < comparisonValue) - return true; - return false; - } - public static bool IsGreaterThanPrevious(this double[] input) - { - var previousValue = 0.0; - var value = 0.0; - for (var i = 0; i < 1; i++) - { - value = input[0]; - previousValue = input[1]; - } - if (value > previousValue) - return true; - return false; - } - public static bool IsLessThanPrevious(this double[] input) - { - var previousValue = 0.0; - var value = 0.0; - for (var i = 0; i < 1; i++) - { - value = input[0]; - previousValue = input[1]; - } - if (value < previousValue) - return true; - return false; - } - /// - /// Determines whether the specified value is between a minimum-maximum range (inclusive). - /// - /// The value. - /// The minimum. - /// The maximum. - /// - public static bool IsBetween(this int value, int minimum, int maximum) - { - return value >= minimum && value <= maximum; - } - public static bool IsLessThanPrevious(this List input) - { - var previousValue = 0.0; - var value = 0.0; - for (var i = 0; i < 1; i++) - { - value = input[0]; - previousValue = input[1]; - } - if (value < previousValue) - return true; - return false; - } - } -} diff --git a/core/Boagaphish/Core/Layers/ActivationLayer.cs b/core/Boagaphish/Core/Layers/ActivationLayer.cs deleted file mode 100644 index f8e3b3f..0000000 --- a/core/Boagaphish/Core/Layers/ActivationLayer.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Boagaphish.ActivationFunctions; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Layers -{ - /// - /// The activation layer. Activation layer is a layer of activation neurons. The layer is usually used in multi-layer neural networks. - /// - /// - public class ActivationLayer : Layer - { - /// - /// The layer's neurons accessor. Allows to access layer's neurons. - /// - public new ActivationNeuron this[int index] - { - get { return (ActivationNeuron)Neurons[index]; } - } - /// - /// Initializes a new instance of the class. The new layer will be randomized (see method) after it is created. - /// - /// The neurons count of the layer. - /// The inputs count of the layer. - /// The activation function of neurons of the layer. - public ActivationLayer(int neuronsCount, int inputsCount, IActivationFunction function) - : base(neuronsCount, inputsCount) - { - // Create each neuron. - for (int i = 0; i < neuronsCount; i++) - Neurons[i] = new ActivationNeuron(inputsCount, function); - } - } -} diff --git a/core/Boagaphish/Core/Layers/DistanceLayer.cs b/core/Boagaphish/Core/Layers/DistanceLayer.cs deleted file mode 100644 index 307e872..0000000 --- a/core/Boagaphish/Core/Layers/DistanceLayer.cs +++ /dev/null @@ -1,34 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Layers -{ - /// - /// The distance layer. Distance layer is a layer of distance neurons. The layer is usually a single layer of such networks as Kohonen Self Organizing Map, Elastic Net, Hamming Memory Net, etc. - /// - public class DistanceLayer : Layer - { - /// - /// The neurons accessor for the layer. Allows to access layer's neurons. - /// - public new DistanceNeuron this[int index] - { - get { return (DistanceNeuron)Neurons[index]; } - } - /// - /// Initializes a new instance of the class. The new layer will be randomized (see - /// method) after it is created. - /// - /// The neurons count of the layer. - /// The inputs count of the layer. - public DistanceLayer(int neuronsCount, int inputsCount) - : base(neuronsCount, inputsCount) - { - // Create each neuron. - for (int i = 0; i < neuronsCount; i++) - Neurons[i] = new DistanceNeuron(inputsCount); - } - } -} diff --git a/core/Boagaphish/Core/Layers/Layer.cs b/core/Boagaphish/Core/Layers/Layer.cs deleted file mode 100644 index f710bcf..0000000 --- a/core/Boagaphish/Core/Layers/Layer.cs +++ /dev/null @@ -1,98 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Layers -{ - /// - /// This is a base neural layer class, which represents a collection of neurons. - /// - public abstract class Layer - { - /// - /// Initializes a new instance of the class - /// - /// Layer's neurons count - /// Layer's inputs count - /// Protected contructor, which initializes , - /// , and - /// members. - protected Layer(int neuronsCount, int inputsCount) - { - CountInputs = Math.Max(1, inputsCount); - CountNeurons = Math.Max(1, neuronsCount); - // create collection of neurons - Neurons = new Neuron[CountNeurons]; - // allocate output array - OutputVector = new double[CountNeurons]; - } - /// - /// The layer's inputs count. - /// - protected int CountInputs = 0; - /// - /// Layer's neurons count - /// - protected int CountNeurons = 0; - /// - /// Layer's neurons - /// - protected Neuron[] Neurons; - /// - /// The layer's output vector. - /// - protected double[] OutputVector; - /// - /// Layer's inputs count - /// - /// The inputs count. - public int InputsCount - { - get { return CountInputs; } - } - /// - /// The layer's neurons count. - /// - public int NeuronsCount - { - get { return CountNeurons; } - } - /// - /// The layer's output vector. The calculation way of layer's output vector is determined by an inherited class. - /// - public double[] Output - { - get { return OutputVector; } - } - /// - /// The layer's neurons accessor. Allows to access layer's neurons. - /// - public Neuron this[int index] - { - get { return Neurons[index]; } - } - /// - /// Computes the output vector of the layer. The actual layer's output vector is determined by inherited class and it consists of output values of layer's neurons. The output vector is also stored in property. - /// - /// Input vector - /// Returns layer's output vector - public virtual double[] Compute(double[] input) - { - // Compute each neuron. - for (var i = 0; i < CountNeurons; i++) - OutputVector[i] = Neurons[i].Compute(input); - - return OutputVector; - } - /// - /// Randomize the neurons of the layer. Randomizes layer's neurons by calling method of each neuron. - /// - public virtual void Randomize() - { - foreach (var neuron in Neurons) - neuron.Randomize(); - } - } -} diff --git a/core/Boagaphish/Core/Learning/BackPropagation.cs b/core/Boagaphish/Core/Learning/BackPropagation.cs deleted file mode 100644 index 03fe425..0000000 --- a/core/Boagaphish/Core/Learning/BackPropagation.cs +++ /dev/null @@ -1,278 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using Boagaphish.Core.Layers; -using Boagaphish.Core.Networks; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Learning -{ - /// - /// The back propagation learning algorithm, which is widely used for training multi-layer neural networks with continuous activation functions. - /// - public class BackPropagation : ISupervised - { - // The network to teach. - private readonly ActivationNetwork _network; - // The learning rate. - private double _learningRate; - // The momentum. - private double _momentum; - // The neurons' errors. - private readonly double[][] _neuronErrors; - // The weights' updates. - private readonly double[][][] _weightsUpdates; - // The thresholds' updates. - private readonly double[][] _thresholdUpdates; - /// - /// Initializes a new instance of the class, of the original algorithm. - /// - /// The network to teach. - /// The learning rate. - public BackPropagation(ActivationNetwork network, double learningRate = 0.1) - { - _learningRate = learningRate; - _network = network; - // Create error and deltas arrays. - _neuronErrors = new double[network.LayersCount][]; - _weightsUpdates = new double[network.LayersCount][][]; - _thresholdUpdates = new double[network.LayersCount][]; - // Initialize errors and deltas arrays for each layer. - for (int i = 0, n = network.LayersCount; i < n; i++) - { - Layer layer = network[i]; - _neuronErrors[i] = new double[layer.NeuronsCount]; - _weightsUpdates[i] = new double[layer.NeuronsCount][]; - _thresholdUpdates[i] = new double[layer.NeuronsCount]; - // For each neuron. - for (var j = 0; j < layer.NeuronsCount; j++) - { - _weightsUpdates[i][j] = new double[layer.InputsCount]; - } - } - } - /// - /// The learning rate. The value determines speed of learning. Default value equals to 0.1. - /// - public double LearningRate - { - get { return _learningRate; } - set - { - _learningRate = Math.Max(0.0, Math.Min(1.0, value)); - } - } - /// - /// The momentum. The value determines the portion of previous weight's update to use on current iteration. Weight's update values are calculated on each iteration depending on neuron's error. The momentum specifies the amount of update to use from previous iteration and the amount of update to use from current iteration. If the value is equal to 0.1, for example, then 0.1 portion of previous update and 0.9 portion of current update are used to update weight's value.

    Default value equals 0.0. - ///
    - public double Momentum - { - get { return _momentum; } - set - { - _momentum = Math.Max(0.0, Math.Min(1.0, value)); - } - } - /// - /// Runs a learning iteration. Runs one learning iteration and updates neuron's weights. Returns squared error of the last layer divided by two. - /// - /// The input vector. - /// The desired output vector. - /// - /// Returns the learning error. - /// - public double Run(double[] input, double[] desired) - { - // Compute the network's output. - _network.Compute(input); - // Calculate the network error. - var error = CalculateError(desired); - // Calculate weights updates. - CalculateUpdates(input); - // Update the network. - UpdateNetwork(); - - return error; - } - /// - /// Runs a learning epoch. Runs series of learning iterations - one iteration for each input sample. Updates neuron's weights after each sample - /// presented. Returns sum of squared errors of the last layer divided by two. - /// - /// array of input vectors - /// array of output vectors - /// - /// Returns a sum of learning errors. - /// - public double RunEpoch(double[][] input, double[][] desired) - { - var error = 0.0; - // Run learning procedure for all samples. - for (int i = 0, n = input.Length; i < n; i++) - { - error += Run(input[i], desired[i]); - } - // Return summary error. - return error; - } - /// - /// Calculates error values for all neurons of the network. - /// - /// The desired output vector. - /// - /// Returns summary squared error of the last layer divided by two. - /// - private double CalculateError(IList desired) - { - // The initial error value. - double error = 0; - // The layers count. - var layersCount = _network.LayersCount; - // Assume that all neurons of the network have the same activation function. - var function = _network[0][0].ActivationFunction; - // Calculate error values for the last layer first. - var layer = _network[layersCount - 1]; - var errors = _neuronErrors[layersCount - 1]; - - for (int i = 0, n = layer.NeuronsCount; i < n; i++) - { - // The unit�s output value. - var output = layer[i].Output; - // The error of the unit. - var e = desired[i] - output; - // The error multiplied with activation function's derivative. - errors[i] = e * function.Derivative2(output); - // Square the error and sum it. - error += (e * e); - } - // Calculate error values for other layers. - for (var j = layersCount - 2; j >= 0; j--) - { - layer = _network[j]; - var layerNext = _network[j + 1]; - // The current and the next layers. - errors = _neuronErrors[j]; - // The current and the next error arrays. - var errorsNext = _neuronErrors[j + 1]; - // For all units of the layer. - for (int i = 0, n = layer.NeuronsCount; i < n; i++) - { - var sum = 0.0; - // For all units of the next layer. - for (int k = 0, m = layerNext.NeuronsCount; k < m; k++) - { - sum += errorsNext[k] * layerNext[k][i]; - } - errors[i] = sum * function.Derivative2(layer[i].Output); - } - } - // Return the squared error of the last layer divided by 2. - return error / 2.0; - } - /// - /// Calculate weights updates. - /// - /// The network's input vector. - private void CalculateUpdates(double[] input) - { - // The current neuron. - ActivationNeuron neuron; - // The neuron's weights updates. - double[] neuronWeightUpdates; - // The error value. - double error; - // 1 - Calculate the updates for the last layer first. - // The current layer. - ActivationLayer layer = _network[0]; - // The layer's error. - double[] errors = _neuronErrors[0]; - // The layer's weights updates. - double[][] layerWeightsUpdates = _weightsUpdates[0]; - // The layer's thresholds updates. - double[] layerThresholdUpdates = _thresholdUpdates[0]; - // Compute for each neuron of the layer. - for (int i = 0, n = layer.NeuronsCount; i < n; i++) - { - neuron = layer[i]; - error = errors[i]; - neuronWeightUpdates = layerWeightsUpdates[i]; - // Computer for each weight of the neuron. - for (int j = 0, m = neuron.InputsCount; j < m; j++) - { - // Calculate the weight update value. - neuronWeightUpdates[j] = _learningRate * (_momentum * neuronWeightUpdates[j] + (1.0 - _momentum) * error * input[j]); - } - // Calculate the threshold update. - layerThresholdUpdates[i] = _learningRate * (_momentum * layerThresholdUpdates[i] + (1.0 - _momentum) * error); - } - // Post the update. - - // 2 - Calculate the update for all other layers. - for (int k = 1, l = _network.LayersCount; k < l; k++) - { - // The previous layer. - ActivationLayer layerPrev = _network[k - 1]; - layer = _network[k]; - errors = _neuronErrors[k]; - layerWeightsUpdates = _weightsUpdates[k]; - layerThresholdUpdates = _thresholdUpdates[k]; - // Compute for each neuron of the layer. - for (int i = 0, n = layer.NeuronsCount; i < n; i++) - { - neuron = layer[i]; - error = errors[i]; - neuronWeightUpdates = layerWeightsUpdates[i]; - // Compute for each synapse of the neuron. - for (int j = 0, m = neuron.InputsCount; j < m; j++) - { - // Calculate the weight update value. - neuronWeightUpdates[j] = _learningRate * ( - _momentum * neuronWeightUpdates[j] + - (1.0 - _momentum) * error * layerPrev[j].Output - ); - } - // Calculate the threshold update. - layerThresholdUpdates[i] = _learningRate * ( - _momentum * layerThresholdUpdates[i] + - (1.0 - _momentum) * error - ); - } - } - // Post the update. - - } - /// - /// Update the network's weights. - /// - private void UpdateNetwork() - { - // Compute for each layer of the network. - for (int i = 0, n = _network.LayersCount; i < n; i++) - { - // The current layer. - ActivationLayer layer = _network[i]; - // The layer's weights updates. - double[][] layerWeightsUpdates = _weightsUpdates[i]; - // The layer's threshold updates. - double[] layerThresholdUpdates = _thresholdUpdates[i]; - // Compute for each neuron of the layer. - for (int j = 0, m = layer.NeuronsCount; j < m; j++) - { - // The current neuron. - ActivationNeuron neuron = layer[j]; - // The neuron's weights updates. - double[] neuronWeightUpdates = layerWeightsUpdates[j]; - // Compute for each weight of the neuron. - for (int k = 0, s = neuron.InputsCount; k < s; k++) - { - // Update weight value. - neuron[k] += neuronWeightUpdates[k]; - } - // Update threshold value. - neuron.Threshold += layerThresholdUpdates[j]; - } - } - } - } -} diff --git a/core/Boagaphish/Core/Learning/DeltaRule.cs b/core/Boagaphish/Core/Learning/DeltaRule.cs deleted file mode 100644 index df74e72..0000000 --- a/core/Boagaphish/Core/Learning/DeltaRule.cs +++ /dev/null @@ -1,121 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.ActivationFunctions; -using Boagaphish.Core.Layers; -using Boagaphish.Core.Networks; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Learning -{ - /// - /// Delta rule learning algorithm - /// - /// This learning algorithm is used to train one layer neural network of Activation Neurons with continuous activation function, see for example. - public class DeltaRule : ISupervised - { - // network to teach - private readonly ActivationNetwork _network; - // learning rate - private double _learningRate = 0.1; - /// - /// Learning rate - /// - /// The learning rate. - /// The value determines speed of learning in the range of [0, 1]. - /// Default value equals to 0.1. - public double LearningRate - { - get { return _learningRate; } - set - { - _learningRate = Math.Max(0.0, Math.Min(1.0, value)); - } - } - /// - /// Initializes a new instance of the class - /// - /// Network to teach - public DeltaRule(ActivationNetwork network) - { - // check layers count - if (network.LayersCount != 1) - { - throw new ArgumentException("Invalid neural network. It should have one layer only."); - } - - _network = network; - } - /// - /// Runs learning iteration - /// - /// input vector - /// desired output vector - /// Returns squared error divided by 2 - /// Runs one learning iteration and updates neuron's - /// weights. - public double Run(double[] input, double[] desired) - { - // compute output of network - double[] networkOutput = _network.Compute(input); - - // get the only layer of the network - ActivationLayer layer = _network[0]; - // get activation function of the layer - IActivationFunction activationFunction = layer[0].ActivationFunction; - - // summary network absolute error - double error = 0.0; - - // update weights of each neuron - for (int j = 0, k = layer.NeuronsCount; j < k; j++) - { - // get neuron of the layer - ActivationNeuron neuron = layer[j]; - // calculate neuron's error - double e = desired[j] - networkOutput[j]; - // get activation function's derivative - double functionDerivative = activationFunction.Derivative2(networkOutput[j]); - - // update weights - for (int i = 0, n = neuron.InputsCount; i < n; i++) - { - neuron[i] += _learningRate * e * functionDerivative * input[i]; - } - - // update threshold value - neuron.Threshold += _learningRate * e * functionDerivative; - - // sum error - error += (e * e); - } - - return error / 2; - } - /// - /// Runs learning epoch - /// - /// array of input vectors - /// array of output vectors - /// - /// Returns sum of squared errors divided by 2 - /// - /// Runs series of learning iterations - one iteration - /// for each input sample. Updates neuron's weights after each sample - /// presented. - public double RunEpoch(double[][] input, double[][] desired) - { - double error = 0.0; - - // run learning procedure for all samples - for (int i = 0, n = input.Length; i < n; i++) - { - error += Run(input[i], desired[i]); - } - - // return summary error - return error; - } - } -} diff --git a/core/Boagaphish/Core/Learning/ElasticNetwork.cs b/core/Boagaphish/Core/Learning/ElasticNetwork.cs deleted file mode 100644 index ade7b83..0000000 --- a/core/Boagaphish/Core/Learning/ElasticNetwork.cs +++ /dev/null @@ -1,148 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.Core.Layers; -using Boagaphish.Core.Networks; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Learning -{ - /// - /// The elastic network learning algorithm. - /// - /// This class implements elastic network's learning algorithm and allows to train Distance Networks. - public class ElasticNetwork : IUnsupervised - { - // neural network to train - private readonly DistanceNetwork _network; - // array of distances between neurons - private readonly double[] _distance; - // learning rate - private double _learningRate = 0.1; - // learning radius - private double _learningRadius = 0.5; - // squared learning radius multiplied by 2 (precalculated value to speed up computations) - private double _squaredRadius2 = 2 * 7 * 7; - /// - /// Learning rate - /// - /// The learning rate. - /// Determines speed of learning. Value range is [0, 1]. - /// Default value equals to 0.1. - public double LearningRate - { - get { return _learningRate; } - set - { - _learningRate = Math.Max(0.0, Math.Min(1.0, value)); - } - } - /// - /// Learning radius - /// - /// The learning radius. - /// Determines the amount of neurons to be updated around - /// winner neuron. Neurons, which are in the circle of specified radius, - /// are updated during the learning procedure. Neurons, which are closer - /// to the winner neuron, get more update.

    - /// Default value equals to 0.5.
    - public double LearningRadius - { - get { return _learningRadius; } - set - { - _learningRadius = Math.Max(0, Math.Min(1.0, value)); - _squaredRadius2 = 2 * _learningRadius * _learningRadius; - } - } - /// - /// Initializes a new instance of the class - /// - /// Neural network to train - public ElasticNetwork(DistanceNetwork network) - { - _network = network; - - // precalculate distances array - int neurons = network[0].NeuronsCount; - double deltaAlpha = Math.PI * 2.0 / neurons; - double alpha = deltaAlpha; - - _distance = new double[neurons]; - _distance[0] = 0.0; - - // calculate all distance values - for (int i = 1; i < neurons; i++) - { - double dx = 0.5 * Math.Cos(alpha) - 0.5; - double dy = 0.5 * Math.Sin(alpha); - - _distance[i] = dx * dx + dy * dy; - - alpha += deltaAlpha; - } - } - /// - /// Runs learning iteration - /// - /// input vector - /// - /// Returns learning error - summary absolute difference between updated - /// weights and according inputs. The difference is measured according to the neurons - /// distance to the winner neuron. - /// - public double Run(double[] input) - { - double error = 0.0; - - // compute the network - _network.Compute(input); - int winner = _network.GetWinner(); - - // get layer of the network - Layer layer = _network[0]; - - // walk through all neurons of the layer - for (int j = 0, m = layer.NeuronsCount; j < m; j++) - { - Neuron neuron = layer[j]; - - // update factor - double factor = Math.Exp(-_distance[Math.Abs(j - winner)] / _squaredRadius2); - - // update weight of the neuron - for (int i = 0, n = neuron.InputsCount; i < n; i++) - { - // calculate the error - double e = (input[i] - neuron[i]) * factor; - error += Math.Abs(e); - // update weight - neuron[i] += e * _learningRate; - } - } - return error; - } - /// - /// Runs learning epoch - /// - /// array of input vectors - /// - /// Returns summary learning error for the epoch. See - /// method for details about learning error calculation. - /// - public double RunEpoch(double[][] input) - { - double error = 0.0; - - // walk through all training samples - foreach (double[] sample in input) - { - error += Run(sample); - } - - // return summary error - return error; - } - } -} diff --git a/core/Boagaphish/Core/Learning/ISupervised.cs b/core/Boagaphish/Core/Learning/ISupervised.cs deleted file mode 100644 index 603448f..0000000 --- a/core/Boagaphish/Core/Learning/ISupervised.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Core.Learning -{ - /// - /// The supervised learning interface. The interface describes methods, which should be implemented by all supervised learning algorithms. Supervised learning is such a type of learning algorithms, where system's desired output is known at the learning stage. Given a sample of input values and desired outputs, the system should adopt its internal variables to produce a correct (or close to correct) result after the learning step is completed. - /// - public interface ISupervised - { - /// - /// Runs a learning iteration. - /// - /// The input vector. - /// The desired output vector. - /// - /// Returns the learning error. - /// - double Run(double[] input, double[] desired); - /// - /// Runs a learning epoch. - /// - /// An array of input vectors. - /// Anarray of output vectors. - /// - /// Returns a sum of learning errors. - /// - double RunEpoch(double[][] input, double[][] desired); - } -} diff --git a/core/Boagaphish/Core/Learning/IUnsupervised.cs b/core/Boagaphish/Core/Learning/IUnsupervised.cs deleted file mode 100644 index 8fd3f2f..0000000 --- a/core/Boagaphish/Core/Learning/IUnsupervised.cs +++ /dev/null @@ -1,25 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Core.Learning -{ - /// - /// The unsupervised learning interface. - /// - /// The interface describes methods, which should be implemented by all unsupervised learning algorithms. Unsupervised learning is such a type of learning algorithms, where system's desired output is not known on the learning stage. Given sample input values, it is expected, that system will organize itself in the way to find similarities betweed provided samples. - public interface IUnsupervised - { - /// - /// Runs learning iteration - /// - /// input vector - /// Returns learning error - double Run( double[] input ); - /// - /// Runs learning epoch - /// - /// array of input vectors - /// Returns sum of learning errors - double RunEpoch( double[][] input ); - } -} diff --git a/core/Boagaphish/Core/Learning/Perceptron.cs b/core/Boagaphish/Core/Learning/Perceptron.cs deleted file mode 100644 index 16cc61d..0000000 --- a/core/Boagaphish/Core/Learning/Perceptron.cs +++ /dev/null @@ -1,125 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.ActivationFunctions; -using Boagaphish.Core.Layers; -using Boagaphish.Core.Networks; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Learning -{ - /// - /// Perceptron learning algorithm - /// - /// This learning algorithm is used to train one layer neural network of Activation Neurons with the Threshold activation function. - public class Perceptron : ISupervised - { - // network to teach - private ActivationNetwork network; - /// - /// The tolerance value for network minimum value comparisions. - /// - public double Epsilon = 1E-6; - // learning rate - private double _learningRate = 0.1; - /// - /// Learning rate - /// - /// The learning rate. - /// The value determines speed of learning in the range of [0, 1]. - /// Default value equals to 0.1. - public double LearningRate - { - get { return _learningRate; } - set - { - _learningRate = Math.Max(0.0, Math.Min(1.0, value)); - } - } - /// - /// Initializes a new instance of the class - /// - /// Network to teach - public Perceptron(ActivationNetwork network) - { - // check layers count - if (network.LayersCount != 1) - { - throw new ArgumentException("Invalid nuaral network. It should have one layer only."); - } - - this.network = network; - } - /// - /// Runs learning iteration - /// - /// input vector - /// desired output vector - /// - /// Returns absolute error - difference between real output and - /// desired output - /// - /// Runs one learning iteration and updates neuron's - /// weights in case if neuron's output does not equal to the - /// desired output. - public double Run(double[] input, double[] desired) - { - // compute output of network - double[] networkOutput = network.Compute(input); - - // get the only layer of the network - ActivationLayer layer = network[0]; - - // summary network absolute error - double error = 0.0; - - // check output of each neuron and update weights - for (int j = 0, k = layer.NeuronsCount; j < k; j++) - { - double e = desired[j] - networkOutput[j]; - - if (Math.Abs(e) > Epsilon) - { - ActivationNeuron perceptron = layer[j]; - - // update weights - for (int i = 0, n = perceptron.InputsCount; i < n; i++) - { - perceptron[i] += _learningRate * e * input[i]; - } - - // update threshold value - perceptron.Threshold += _learningRate * e; - - // make error to be absolute - error += Math.Abs(e); - } - } - - return error; - } - /// - /// Runs learning epoch - /// - /// array of input vectors - /// array of output vectors - /// Returns sum of absolute errors - /// Runs series of learning iterations - one iteration - /// for each input sample. Updates neuron's weights each time, - /// when neuron's output does not equal to the desired output. - public double RunEpoch(double[][] input, double[][] desired) - { - double error = 0.0; - - // run learning procedure for all samples - for (int i = 0, n = input.Length; i < n; i++) - { - error += Run(input[i], desired[i]); - } - - // return summary error - return error; - } - } -} diff --git a/core/Boagaphish/Core/Learning/SelfOrganizingMap.cs b/core/Boagaphish/Core/Learning/SelfOrganizingMap.cs deleted file mode 100644 index 6c3310f..0000000 --- a/core/Boagaphish/Core/Learning/SelfOrganizingMap.cs +++ /dev/null @@ -1,177 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Linq; -using Boagaphish.Core.Layers; -using Boagaphish.Core.Networks; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Learning -{ - /// - /// Kohonen Self-Organizing Map (SOM) learning algorithm - /// - /// This class implements Kohonen's SOM learning algorithm and is widely used in clusterization tasks. The class allows to train Distance Networks. - /// - public class SelfOrganizingMap : IUnsupervised - { - // neural network to train - private readonly DistanceNetwork _network; - // network's dimension - private readonly int _width; - private readonly int _height; - // learning rate - private double _learningRate = 0.1; - // learning radius - private double _learningRadius = 7; - // squared learning radius multiplied by 2 (precalculated value to speed up computations) - private double _squaredRadius2 = 2 * 7 * 7; - /// - /// Learning rate - /// - /// The learning rate. - /// Determines speed of learning. Value range is [0, 1]. Default value equals to 0.1. - public double LearningRate - { - get { return _learningRate; } - set - { - _learningRate = Math.Max(0.0, Math.Min(1.0, value)); - } - } - /// - /// Learning radius - /// - /// The learning radius. - /// Determines the amount of neurons to be updated around - /// winner neuron. Neurons, which are in the circle of specified radius, - /// are updated during the learning procedure. Neurons, which are closer - /// to the winner neuron, get more update.

    - /// Default value equals to 7.
    - public double LearningRadius - { - get { return _learningRadius; } - set - { - _learningRadius = Math.Max(0, value); - _squaredRadius2 = 2 * _learningRadius * _learningRadius; - } - } - /// - /// Initializes a new instance of the class - /// - /// Neural network to train - /// This constructor supposes that a square network will be passed for training - it should be possible to get square root of network's neurons amount. - /// - public SelfOrganizingMap(DistanceNetwork network) - { - // network's dimension was not specified, let's try to guess - var neuronsCount = network[0].NeuronsCount; - _width = (int)Math.Sqrt(neuronsCount); - - if (_width * _width != neuronsCount) - { - throw new ArgumentException("Invalid network size"); - } - - // ok, we got it - _network = network; - } - /// - /// Initializes a new instance of the class - /// - /// Neural network to train - /// Neural network's width - /// Neural network's height - /// The constructor allows to pass network of arbitrary rectangular shape. - /// The amount of neurons in the network should be equal to width * height. - /// - public SelfOrganizingMap(DistanceNetwork network, int width, int height) - { - // check network size - if (network[0].NeuronsCount != width * height) - { - throw new ArgumentException("Invalid network size"); - } - - _network = network; - _width = width; - _height = height; - } - /// - /// Runs learning iteration - /// - /// input vector - /// - /// Returns learning error - summary absolute difference between updated - /// weights and according inputs. The difference is measured according to the neurons - /// distance to the winner neuron. - /// - public double Run(double[] input) - { - double error = 0.0; - - // compute the network - _network.Compute(input); - int winner = _network.GetWinner(); - - // get layer of the network - Layer layer = _network[0]; - - // check learning radius - if (_learningRadius == 0) - { - Neuron neuron = layer[winner]; - - // update weight of the winner only - for (int i = 0, n = neuron.InputsCount; i < n; i++) - { - neuron[i] += (input[i] - neuron[i]) * _learningRate; - } - } - else - { - // winner's X and Y - int wx = winner % _width; - int wy = winner / _width; - - // walk through all neurons of the layer - for (int j = 0, m = layer.NeuronsCount; j < m; j++) - { - Neuron neuron = layer[j]; - - int dx = (j % _width) - wx; - int dy = (j / _width) - wy; - - // update factor ( Gaussian based ) - double factor = Math.Exp(-(double)(dx * dx + dy * dy) / _squaredRadius2); - - // update weight of the neuron - for (int i = 0, n = neuron.InputsCount; i < n; i++) - { - // calculate the error - double e = (input[i] - neuron[i]) * factor; - error += Math.Abs(e); - // update weight - neuron[i] += e * _learningRate; - } - } - } - return error; - } - /// - /// Runs learning epoch - /// - /// array of input vectors - /// - /// Returns summary learning error for the epoch. See - /// method for details about learning error calculation. - /// - public double RunEpoch(double[][] input) - { - // walk through all training samples and return summary error - return input.Sum(sample => Run(sample)); - } - } -} diff --git a/core/Boagaphish/Core/Lobes/LobeGenome.cs b/core/Boagaphish/Core/Lobes/LobeGenome.cs deleted file mode 100644 index e6e601f..0000000 --- a/core/Boagaphish/Core/Lobes/LobeGenome.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Boagaphish.Genetic; - -namespace Boagaphish.Core.Lobes -{ - public class LobeGenome - { - protected int LobeId - { - get; - set; - } - - protected bool On - { - get; - set; - } - - public LobeGenome(int lobid, GeneHeader geneHeader) - { - LobeId = lobid; - if (geneHeader == GeneHeader.Embryo) - { - On = true; - } - } - } -} diff --git a/core/Boagaphish/Core/Lobes/LobeProperties.cs b/core/Boagaphish/Core/Lobes/LobeProperties.cs deleted file mode 100644 index 586c269..0000000 --- a/core/Boagaphish/Core/Lobes/LobeProperties.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Core.Lobes -{ - public class LobeProperties - { - public int X - { - get; - set; - } - - public int Y - { - get; - set; - } - - public double Width - { - get; - set; - } - - public double Height - { - get; - set; - } - - public bool Overlap - { - get; - set; - } - - public LobeProperties() - { - Overlap = false; - } - - public int NeuronsCount() - { - return X * Y; - } - } -} diff --git a/core/Boagaphish/Core/Networks/ActivationNetwork.cs b/core/Boagaphish/Core/Networks/ActivationNetwork.cs deleted file mode 100644 index 331bcad..0000000 --- a/core/Boagaphish/Core/Networks/ActivationNetwork.cs +++ /dev/null @@ -1,52 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Boagaphish.ActivationFunctions; -using Boagaphish.Core.Layers; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Networks -{ - /// - /// The activation network is a base for multi-layer neural network with activation functions. It consists of activation layers. - /// - public class ActivationNetwork : Network - { - /// - /// The accessor for the network's layers. - /// - public new ActivationLayer this[int index] - { - get { return ((ActivationLayer)Layers[index]); } - } - /// - /// Initializes a new instance of the class. The new network will be randomized (see method) after it is created. - /// - /// Activation function of neurons of the network - /// Network's inputs count - /// Array, which specifies the amount of neurons in each layer of the neural network - /// The following sample illustrates the usage of ActivationNetwork class: - /// - /// Create a new activation network: - /// ActivationNetwork network = new ActivationNetwork(new SigmoidFunction( ), // sigmoid activation function - /// 3, // 3 inputs - /// 4, 1 ); // 2 layers: 4 neurons in the first layer, 1 neuron in the second layer. - /// - /// - public ActivationNetwork(IActivationFunction function, int inputsCount, params int[] neuronsCount) - : base(inputsCount, neuronsCount.Length) - { - // Create each layer. - for (var i = 0; i < LayersCount; i++) - { - Layers[i] = new ActivationLayer( - // The neurons count in the layer. - neuronsCount[i], - // The inputs count of the layer. - (i == 0) ? inputsCount : neuronsCount[i - 1], - // The activation function of the layer. - function); - } - } - } -} diff --git a/core/Boagaphish/Core/Networks/DistanceNetwork.cs b/core/Boagaphish/Core/Networks/DistanceNetwork.cs deleted file mode 100644 index baa4902..0000000 --- a/core/Boagaphish/Core/Networks/DistanceNetwork.cs +++ /dev/null @@ -1,55 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Boagaphish.Core.Layers; -using Boagaphish.Core.Neurons; - -namespace Boagaphish.Core.Networks -{ - /// - /// Distance network is a neural network of only one distance layer. The network is a base for such neural networks as SOM, Elastic net, etc. - /// - public class DistanceNetwork : Network - { - /// - /// The accessor to the distance layers. - /// - public new DistanceLayer this[int index] - { - get { return ((DistanceLayer)Layers[index]); } - } - /// - /// Initializes a new instance of the class. The new network will be randomized (see - /// method) after it is created. - /// - /// The inputs count of the network. - /// The neurons count of the network. - public DistanceNetwork(int inputsCount, int neuronsCount) - : base(inputsCount, 1) - { - // Create the layer. - Layers[0] = new DistanceLayer(neuronsCount, inputsCount); - } - /// - /// Get the winner neuron. The method returns index of the neuron, which weights have the minimum distance from network's input. - /// - /// Index of the winner neuron - public int GetWinner() - { - // Find the MIN value. - double min = OutputVector[0]; - int minIndex = 0; - - for (int i = 1, n = OutputVector.Length; i < n; i++) - { - if (OutputVector[i] < min) - { - // Found a new MIN value. - min = OutputVector[i]; - minIndex = i; - } - } - return minIndex; - } - } -} diff --git a/core/Boagaphish/Core/Networks/Network.cs b/core/Boagaphish/Core/Networks/Network.cs deleted file mode 100644 index 80a6b1a..0000000 --- a/core/Boagaphish/Core/Networks/Network.cs +++ /dev/null @@ -1,104 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.Core.Layers; - -namespace Boagaphish.Core.Networks -{ - /// - /// This is a base neural netwok class, which represents a collection of neuron's layers. - /// - public abstract class Network - { - /// - /// Sets the data pointer to between one layer and the other. - /// - public enum CrossLayer - { - InputHidden, HiddenOutput - } - /// - /// The network's inputs count. - /// - protected int CountInputs; - /// - /// The network's layers count. - /// - protected int CountLayers; - /// - /// The layers of the network. - /// - protected Layer[] Layers; - /// - /// The network's output vector. - /// - protected double[] OutputVector; - /// - /// The inputs count for the network. - /// - public int InputsCount - { - get { return CountInputs; } - } - /// - /// The layers count for the network. - /// - public int LayersCount - { - get { return CountLayers; } - } - /// - /// The output vector of the network. The calculation way of network's output vector is determined by an inherited class. - /// - public double[] Output - { - get { return OutputVector; } - } - /// - /// The accessor for the network's layers. - /// - public Layer this[int index] - { - get { return Layers[index]; } - } - /// - /// Initializes a new instance of the class. Protected constructor, which initializes , and members. - /// - /// The network's inputs count. - /// The network's layers count. - protected Network(int inputsCount, int layersCount) - { - CountInputs = Math.Max(1, inputsCount); - CountLayers = Math.Max(1, layersCount); - // Create a collection of layers. - Layers = new Layer[CountLayers]; - } - /// - /// Compute the output vector of the network. The actual network's output vecor is determined by inherited class and it represents an output vector of the last layer of the network. The output vector is also stored in property. - /// - /// Input vector. - /// Returns network's output vector. - public virtual double[] Compute(double[] input) - { - OutputVector = input; - // Compute each layer. - foreach (var layer in Layers) - { - OutputVector = layer.Compute(OutputVector); - } - - return OutputVector; - } - /// - /// Randomize layers of the network. Randomizes network's layers by calling method for each layer. - /// - public virtual void Randomize() - { - foreach (var layer in Layers) - { - layer.Randomize(); - } - } - } -} diff --git a/core/Boagaphish/Core/Neurons/ActivationNeuron.cs b/core/Boagaphish/Core/Neurons/ActivationNeuron.cs deleted file mode 100644 index 847c329..0000000 --- a/core/Boagaphish/Core/Neurons/ActivationNeuron.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.ActivationFunctions; - -namespace Boagaphish.Core.Neurons -{ - /// - /// The activation neuron. The activation neuron computes weighted sum of its inputs, adds threshold value and then applies activation function. The neuron is usually used in multi-layer neural networks. - /// - public class ActivationNeuron : Neuron - { - /// - /// The threshold value. The value is added to inputs weighted sum. - /// - protected double ThresholdValue = 0.0f; - /// - /// The activation function. The function is applied to inputs weighted sum plus the threshold value. - /// - protected IActivationFunction Function = null; - /// - /// The threshold value. The value is added to inputs weighted sum. - /// - public double Threshold - { - get { return ThresholdValue; } - set { ThresholdValue = value; } - } - /// - /// The activation function of the neuron. - /// - public IActivationFunction ActivationFunction - { - get { return Function; } - } - /// - /// Initializes a new instance of the class - /// - /// The inputs count of the neuron. - /// The activation function of the neuron. - public ActivationNeuron(int inputs, IActivationFunction function) - : base(inputs) - { - Function = function; - } - /// - /// Randomize the neuron. Calls base class Randomize method to randomize neuron's weights and then randomize threshold's value. - /// - public override void Randomize() - { - // Randomize the weights. - base.Randomize(); - // Randomize the threshold. - ThresholdValue = StaticRand.NextDouble() * (RandRange.Length) + RandRange.Min; - } - /// - /// Computes the output value of neuron. The output value of activation neuron is equal to value of nueron's activation function, which parameter is weighted sum of its inputs plus threshold value. The output value is also stored in Output property. - /// - /// The input vector. - /// Returns the neuron's output value. - public override double Compute(double[] input) - { - // Check for corrent input vector. - if (input.Length != CountInputs) - throw new ArgumentException(); - // The initial summation value. - double sum = 0.0; - // Compute the weighted sum of inputs. - for (int i = 0; i < CountInputs; i++) - { - sum += Weights[i] * input[i]; - } - sum += ThresholdValue; - - return (OutputValue = Function.Function(sum)); - } - } -} diff --git a/core/Boagaphish/Core/Neurons/DistanceNeuron.cs b/core/Boagaphish/Core/Neurons/DistanceNeuron.cs deleted file mode 100644 index 750aee6..0000000 --- a/core/Boagaphish/Core/Neurons/DistanceNeuron.cs +++ /dev/null @@ -1,34 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.Core.Neurons -{ - /// - /// The distance neuron. Distance neuron computes its output as distance between its weights and inputs. The neuron is usually used in Kohonen Self Organizing Map. - /// - public class DistanceNeuron : Neuron - { - /// - /// Initializes a new instance of the class. The new neuron will be randomized (see method) after it is created. - /// - /// Neuron's inputs count - public DistanceNeuron(int inputs) : base(inputs) { } - /// - /// Computes the output value of neuron. The output value of distance neuron is equal to distance between its weights and inputs - sum of absolute differences. The output value is also stored in Output property. The actual neuron's output value is determined by inherited class. The output value is also stored in property. - /// - /// The input vector. - public override double Compute(double[] input) - { - OutputValue = 0.0; - - // compute distance between inputs and weights - for (int i = 0; i < CountInputs; i++) - { - OutputValue += Math.Abs(Weights[i] - input[i]); - } - return OutputValue; - } - } -} diff --git a/core/Boagaphish/Core/Neurons/Neuron.cs b/core/Boagaphish/Core/Neurons/Neuron.cs deleted file mode 100644 index 61574e0..0000000 --- a/core/Boagaphish/Core/Neurons/Neuron.cs +++ /dev/null @@ -1,124 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.Format; -using Boagaphish.Numeric; - -namespace Boagaphish.Core.Neurons -{ - /// - /// The base neuron class. Encapsulates common properties suchas the neuron's input, output and weights. - /// - public abstract class Neuron - { - /// - /// Neuron's inputs count - /// - protected int CountInputs = 0; - /// - /// Nouron's wieghts - /// - protected double[] Weights = null; - /// - /// Neuron's output value - /// - protected double OutputValue = 0; - /// - /// A random number generator using lock to generate more randomness. The generator is used for neuron's weights randomization. - /// - protected static StaticRandom StaticRand = new StaticRandom((int)DateTime.Now.Ticks); - /// - /// Random generator range - /// - /// Sets the range of random generator. Affects initial values of neuron's weight. - /// Default value is [0, 1]. - protected static DoubleRange RandRange = new DoubleRange(0.0, 1.0); - /// - /// Random number generator. The property allows to initialize random generator with a custom seed. The generator is used for neuron's weights randomization. - /// - public static StaticRandom StaticRandGenerator - { - get { return StaticRand; } - set - { - if (value != null) - { - StaticRand = value; - } - } - } - /// - /// The range of the random generator. - /// - public static DoubleRange RandomRange - { - get { return RandRange; } - set - { - if (value != null) - { - RandRange = value; - } - } - } - /// - /// Neuron's inputs count - /// - /// The inputs count. - public int InputsCount - { - get { return CountInputs; } - } - /// - /// Neuron's output value - /// - /// The output. - /// The calculation way of neuron's output value is determined by its inherited class. - public double Output - { - get { return OutputValue; } - } - /// - /// Neuron's weights accessor - /// - /// - /// Allows to access neuron's weights. - public double this[int index] - { - get { return Weights[index]; } - set { Weights[index] = value; } - } - /// - /// Initializes a new instance of the class - /// - /// Neuron's inputs count - /// The new neuron will be randomized (see method) - /// after it is created. - protected Neuron(int inputs) - { - // Allocate weights. - CountInputs = Math.Max(1, inputs); - Weights = new double[CountInputs]; - // Randomize the neuron's weights. - Randomize(); - } - /// - /// Randomize the neuron. Initialize neuron's weights with random values within the range specified by . - /// - /// - public virtual void Randomize() - { - double d = RandRange.Length; - // Randomize the weights. - for (int i = 0; i < CountInputs; i++) - Weights[i] = StaticRand.NextDouble() * d + RandRange.Min; - } - /// - /// Computes the output value of a neuron. The actual neuron's output value is determined by inherited class. The output value is also stored in property. - /// - /// Input vector. - /// Returns neuron's output value. - public abstract double Compute(double[] input); - } -} diff --git a/core/Boagaphish/Core/Variables/DataPoints.cs b/core/Boagaphish/Core/Variables/DataPoints.cs deleted file mode 100644 index 90016b1..0000000 --- a/core/Boagaphish/Core/Variables/DataPoints.cs +++ /dev/null @@ -1,10 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Core.Variables -{ - public class DataPoints - { - public enum AccountDataPoint { Balance, Unrealized, MarginUsed } - } -} diff --git a/core/Boagaphish/Custom/ActivationNeuralNetworkSkratch.cs b/core/Boagaphish/Custom/ActivationNeuralNetworkSkratch.cs deleted file mode 100644 index 1f176c9..0000000 --- a/core/Boagaphish/Custom/ActivationNeuralNetworkSkratch.cs +++ /dev/null @@ -1,161 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.Custom -{ - public class ActivationNeuralNetworkSkratch - { - public class DummyNeuralNetwork - { - public double[] inputs; - - public double ihWeight00; - public double ihWeight01; - public double ihWeight10; - public double ihWeight11; - public double ihBias0; - public double ihBias1; - - public double ihSum0; - public double ihSum1; - public double ihResult0; - public double ihResult1; - - public double hoWeight00; - public double hoWeight01; - public double hoWeight10; - public double hoWeight11; - public double hoBias0; - public double hoBias1; - - public double hoSum0; - public double hoSum1; - public double hoResult0; - public double hoResult1; - - public double[] outputs; - - public DummyNeuralNetwork() - { - inputs = new double[2]; - outputs = new double[2]; - } - - public void SetInputs(double[] inputs) - { - inputs.CopyTo(this.inputs, 0); - } - - public void SetWeights(double[] weightsAndBiases) - { - int k = 0; - ihWeight00 = weightsAndBiases[k++]; - ihWeight01 = weightsAndBiases[k++]; - ihWeight10 = weightsAndBiases[k++]; - ihWeight11 = weightsAndBiases[k++]; - ihBias0 = weightsAndBiases[k++]; - ihBias1 = weightsAndBiases[k++]; - - hoWeight00 = weightsAndBiases[k++]; - hoWeight01 = weightsAndBiases[k++]; - hoWeight10 = weightsAndBiases[k++]; - hoWeight11 = weightsAndBiases[k++]; - hoBias0 = weightsAndBiases[k++]; - hoBias1 = weightsAndBiases[k++]; - } - - public void ComputeOutputs(string activationType) - { - // assumes this.inputs[] have values - ihSum0 = (inputs[0] * ihWeight00) + (inputs[1] * ihWeight10); - ihSum0 += ihBias0; - ihSum1 = (inputs[0] * ihWeight01) + (inputs[1] * ihWeight11); - ihSum1 += ihBias1; - ihResult0 = Evaluation(ihSum0, activationType, "ih"); - ihResult1 = Evaluation(ihSum1, activationType, "ih"); - - //Console.WriteLine("ihSum0 = " + ihSum0); - //Console.WriteLine("ihResult0 = " + ihResult0); - //Console.WriteLine("ihSum1 = " + ihSum1); - //Console.WriteLine("ihResult1 = " + ihResult1); - - hoSum0 = (ihResult0 * hoWeight00) + (ihResult1 * hoWeight10); - hoSum0 += hoBias0; - hoSum1 = (ihResult0 * hoWeight01) + (ihResult1 * hoWeight11); - hoSum1 += hoBias1; - hoResult0 = Evaluation(hoSum0, activationType, "ho"); - hoResult1 = Evaluation(hoSum1, activationType, "ho"); - - //Console.WriteLine("hoSum0 = " + hoSum0); - //Console.WriteLine("hoResult0 = " + hoResult0); - //Console.WriteLine("hoSum1 = " + hoSum1); - //Console.WriteLine("hoResult1 = " + hoResult1); - - outputs[0] = hoResult0; - outputs[1] = hoResult1; - } - - public double Evaluation(double x, string activationType, string layer) - { - activationType = activationType.ToLower().Trim(); - if (activationType == "logsigmoid") - return LogSigmoid(x); - if (activationType == "hyperbolictangent") - return HyperbolicTangtent(x); - if (activationType == "softmax") - return NormalizedExponential(x, layer); - throw new Exception("Not implemented"); - } - - public double LogSigmoid(double x) - { - if (x < -45.0) return 0.0; - if (x > 45.0) return 1.0; - return 1.0 / (1.0 + Math.Exp(-x)); - } - - public double HyperbolicTangtent(double x) - { - if (x < -45.0) return -1.0; - if (x > 45.0) return 1.0; - return Math.Tanh(x); - } - - public double NormalizedExponential(double x, string layer) - { - // naive version - double scale = 0.0; - if (layer == "ih") - scale = Math.Exp(ihSum0) + Math.Exp(ihSum1); - else if (layer == "ho") - scale = Math.Exp(hoSum0) + Math.Exp(hoSum1); - else - throw new Exception("Unknown layer"); - - return Math.Exp(x) / scale; - } - - public double Softmax(double x, string layer) - { - // Determine the maximum value. - double max = double.MinValue; - if (layer == "ih") - max = (ihSum0 > ihSum1) ? ihSum0 : ihSum1; - else if (layer == "ho") - max = (hoSum0 > hoSum1) ? hoSum0 : hoSum1; - // Compute the scale. - double scale = 0.0; - if (layer == "ih") - scale = Math.Exp(ihSum0 - max) + Math.Exp(ihSum1 - max); - else if (layer == "ho") - scale = Math.Exp(hoSum0 - max) + Math.Exp(hoSum1 - max); - - return Math.Exp(x - max) / scale; - } - - } - - } -} diff --git a/core/Boagaphish/Custom/BackPropagationNetwork.cs b/core/Boagaphish/Custom/BackPropagationNetwork.cs deleted file mode 100644 index 8182b1d..0000000 --- a/core/Boagaphish/Custom/BackPropagationNetwork.cs +++ /dev/null @@ -1,459 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Xml; -using Boagaphish.Numeric; - -namespace Boagaphish.Custom -{ - /// - /// A personalized back-propagation network biased on my ideas. - /// - public class BackPropagationNetwork - { - // Network parameters - private int _layerCount; - private int _inputSize; - private int[] _layerSize; - private double[][] _layerOutput; - private double[][] _layerInput; - private double[][] _delta; - private double[][] _previousBiasDelta; - private double[][][] _previousWeightDelta; - private XmlDocument _document; - // Network variables - public TransferFunction[] TransferFunction; - public double[][] Bias; - public double[][][] Weight; - // Softmax/scale variables - public double[] ZerothSum; - public double[] FirstSum; - public double FirstToSecondLayerResult; - public double NextToOutputLayerResult; - /// - /// The name of the network. - /// - public string Name { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// The layer sizes. - /// The transfer functions. - /// The name of the network. - /// (Cannot initiate on those parameters.) - public BackPropagationNetwork(IList layerSizes, IList transferFunctions, string name = "Candles") - { - // Tag the network. - Name = name; - // Validate the input data. - if (transferFunctions.Count != layerSizes.Count || transferFunctions[0] != Numeric.TransferFunction.None) - throw new ArgumentException(("Cannot initiate on those parameters.")); - - // Initialize layers. - _layerCount = layerSizes.Count - 1; - _inputSize = layerSizes[0]; - _layerSize = new int[_layerCount]; - - for (int i = 0; i < _layerCount; i++) - _layerSize[i] = layerSizes[i + 1]; - - TransferFunction = new TransferFunction[_layerCount]; - for (int i = 0; i < _layerCount; i++) - TransferFunction[i] = transferFunctions[i + 1]; - - // Start dimensioning arrays. - Bias = new double[_layerCount][]; - _previousBiasDelta = new double[_layerCount][]; - _delta = new double[_layerCount][]; - _layerOutput = new double[_layerCount][]; - _layerInput = new double[_layerCount][]; - Weight = new double[_layerCount][][]; - _previousWeightDelta = new double[_layerCount][][]; - // Fill in 2-dimensional arrays. - for (int l = 0; l < _layerCount; l++) - { - Bias[l] = new double[_layerSize[l]]; - _previousBiasDelta[l] = new double[_layerSize[l]]; - _delta[l] = new double[_layerSize[l]]; - _layerOutput[l] = new double[_layerSize[l]]; - _layerInput[l] = new double[_layerSize[l]]; - - Weight[l] = new double[l == 0 ? _inputSize : _layerSize[l - 1]][]; - _previousWeightDelta[l] = new double[l == 0 ? _inputSize : _layerSize[l - 1]][]; - - for (int i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - { - Weight[l][i] = new double[_layerSize[l]]; - _previousWeightDelta[l][i] = new double[_layerSize[l]]; - } - } - // Intiailze the weights. - for (int l = 0; l < _layerCount; l++) - { - for (int j = 0; j < _layerSize[l]; j++) - { - Bias[l][j] = Gaussian.RandomGaussian(); - _previousBiasDelta[l][j] = 0.0; - _layerOutput[l][j] = 0.0; - _layerInput[l][j] = 0.0; - _delta[l][j] = 0.0; - } - - for (int i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - { - for (int j = 0; j < _layerSize[l]; j++) - { - Weight[l][i][j] = Gaussian.RandomGaussian(); - _previousWeightDelta[l][i][j] = 0.0; - } - } - } - } - /// - /// Initializes a new instance of the class. - /// - /// The file path. - public BackPropagationNetwork(string filePath) - { - LoadNetworkXml(filePath); - } - protected BackPropagationNetwork() - { - // Here for the CustomNetwork class. - } - /// - /// Sums weights and biases in the layers for evaluation against the transfer function at the output. - /// - /// The input. - /// The output. - /// Input data is not of the correct dimension. - public void RunEvaluation(ref double[] input, out double[] output) - { - if (input.Length != _inputSize) - throw new ArgumentException("Input data is not of the correct dimension."); - // Dimension. - output = new double[_layerSize[_layerCount - 1]]; - // Run the network. - for (var l = 0; l < _layerCount; l++) - { - for (var j = 0; j < _layerSize[l]; j++) - { - var sum = 0.0; - for (var i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - sum += Weight[l][i][j] * (l == 0 ? input[i] : _layerOutput[l - 1][i]); - - sum += Bias[l][j]; - _layerInput[l][j] = sum; - _layerOutput[l][j] = TransferFunctions.Evaluate(TransferFunction[l], sum); - } - } - // Copy the output to the output array. - for (var i = 0; i < _layerSize[_layerCount - 1]; i++) - output[i] = _layerOutput[_layerCount - 1][i]; - - } - /// - /// Computes the softmax. (Unfinished) - /// - /// The input. - /// The layer. - /// - public double ComputeSoftmax(double[] input, string layer) - { - var result = 0.0; - for (var i = 0; i < _layerCount; i++) - { - ZerothSum[i] += (input[i] * Weight[0][0][i] /*ihWeight00*/) + (input[i] * Weight[i][0][0] /*ihWeight10*/); - ZerothSum[i] += Bias[0][i];// ihBias0; - FirstSum[i] += (input[i] * Weight[0][i][0] /*ihWeight01*/) + (input[i] * Weight[i][i][0] /*ihWeight11*/); - FirstSum[i] += Bias[i][0];// ihBias1; - FirstToSecondLayerResult = Softmax(ZerothSum[i], "ih"); - NextToOutputLayerResult = Softmax(FirstSum[i], "ho"); - result = 0.5 * Math.Pow(FirstToSecondLayerResult * NextToOutputLayerResult, 2); - } - return result; - } - protected double Softmax(double x, string layer) - { - // Determine the maximum value. - double max = double.MinValue; - if (layer == "ih") - max = (ZerothSum[0] > ZerothSum[1]) ? ZerothSum[0] : ZerothSum[1]; - else if (layer == "ho") - max = (FirstSum[0] > FirstSum[1]) ? FirstSum[0] : FirstSum[1]; - // Compute the scale. - double scale = 0.0; - if (layer == "ih") - scale = Math.Exp(ZerothSum[0] - max) + Math.Exp(ZerothSum[1] - max); - else if (layer == "ho") - scale = Math.Exp(FirstSum[0] - max) + Math.Exp(FirstSum[1] - max); - - return Math.Exp(x - max) / scale; - } - /// - /// Trains the network using the specified input. - /// - /// The input data. - /// The desired output. - /// The training rate. - /// The momentum. - /// Training error. - /// - /// Invalid input parameter;input - /// or - /// Invalid input parameter;desired - /// - public double Train(ref double[] input, ref double[] desired, double trainingRate, double momentum) - { - // Parameter validation. - if (input.Length != _inputSize) - throw new ArgumentException("Invalid input parameter", "input"); - if (desired.Length != _layerSize[_layerCount - 1]) - throw new ArgumentException("Invalid input parameter", "desired"); - // Local variables. - var error = 0.0; - var output = new double[_layerSize[_layerCount - 1]]; - // Run the network. - RunEvaluation(ref input, out output); - // Back-propagate the error. - for (var l = _layerCount - 1; l >= 0; l--) - { - // Output layer - if (l == _layerCount - 1) - { - for (var k = 0; k < _layerSize[l]; k++) - { - _delta[l][k] = output[k] - desired[k]; - error += Math.Pow(_delta[l][k], 2); - _delta[l][k] *= TransferFunctions.EvaluateDerivative(TransferFunction[l], _layerInput[l][k]); - } - } - else // Hidden layer - { - for (var i = 0; i < _layerSize[l]; i++) - { - double sum = 0.0; - for (int j = 0; j < _layerSize[l + 1]; j++) - { - sum += Weight[l + 1][i][j] * _delta[l + 1][j]; - } - sum *= TransferFunctions.EvaluateDerivative(TransferFunction[l], _layerInput[l][i]); - _delta[l][i] = sum; - - } - } - } - // Update the weights and biases. - for (int l = 0; l < _layerCount; l++) - for (int i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - for (int j = 0; j < _layerSize[l]; j++) - { - double weightDelta = trainingRate * _delta[l][j] * (l == 0 ? input[i] : _layerOutput[l - 1][i]) - + momentum * _previousWeightDelta[l][i][j]; - Weight[l][i][j] -= weightDelta; - - _previousWeightDelta[l][i][j] = weightDelta; - } - - for (int l = 0; l < _layerCount; l++) - for (int i = 0; i < _layerSize[l]; i++) - { - double biasDelta = trainingRate * _delta[l][i]; - Bias[l][i] -= biasDelta + momentum * _previousBiasDelta[l][i]; - - _previousBiasDelta[l][i] = biasDelta; - } - return error; - } - /// - /// Saves the network as xml file. - /// - /// The file path. - public void SaveNetworkXml(string filePath) - { - if (filePath == null) - return; - XmlWriter writer = XmlWriter.Create(filePath); - // Begin document - writer.WriteStartElement("NeuralNetwork"); - writer.WriteAttributeString("Type", "BackPropagation"); - // Parameters element - writer.WriteStartElement("Parameters"); - writer.WriteElementString("Name", Name); - writer.WriteElementString("inputSize", _inputSize.ToString(CultureInfo.InvariantCulture)); - writer.WriteElementString("layerCount", _layerCount.ToString(CultureInfo.InvariantCulture)); - // Layer sizes - writer.WriteStartElement("Layers"); - for (int l = 0; l < _layerCount; l++) - { - writer.WriteStartElement("Layer"); - writer.WriteAttributeString("Index", l.ToString(CultureInfo.InvariantCulture)); - writer.WriteAttributeString("Size", _layerSize[l].ToString(CultureInfo.InvariantCulture)); - writer.WriteAttributeString("Type", TransferFunction[l].ToString()); - writer.WriteEndElement();// Layer - } - writer.WriteEndElement();//Layers - writer.WriteEndElement();//Parameters - // Weights and biases - writer.WriteStartElement("Weights"); - for (int l = 0; l < _layerCount; l++) - { - writer.WriteStartElement("Layer"); - writer.WriteAttributeString("Index", l.ToString(CultureInfo.InvariantCulture)); - for (int j = 0; j < _layerSize[l]; j++) - { - writer.WriteStartElement("Node"); - writer.WriteAttributeString("Index", j.ToString(CultureInfo.InvariantCulture)); - writer.WriteAttributeString("Bias", Bias[l][j].ToString(CultureInfo.InvariantCulture)); - for (int i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - { - writer.WriteStartElement("Axion"); - writer.WriteAttributeString("Index", i.ToString(CultureInfo.InvariantCulture)); - writer.WriteString(Weight[l][i][j].ToString(CultureInfo.InvariantCulture)); - writer.WriteEndElement();// Axion - } - writer.WriteEndElement();// Node - } - writer.WriteEndElement();// Layer - } - writer.WriteEndElement();// Weights - writer.WriteEndElement();//NeuralNetwork - writer.Flush(); - writer.Close(); - } - /// - /// Loads the network from xml file. - /// - /// The file path. - public void LoadNetworkXml(string filePath) - { - if (filePath == null) - return; - _document = new XmlDocument(); - _document.Load(filePath); - // Load from xml - string basePath = "NeuralNetwork/Parameters/"; - if (XPathValue("NeuralNetwork/@Type") != "BackPropagation") - return; - Name = XPathValue(basePath + "Name"); - int.TryParse(XPathValue(basePath + "inputSize"), out _inputSize); - int.TryParse(XPathValue(basePath + "layerCount"), out _layerCount); - _layerSize = new int[_layerCount]; - TransferFunction = new TransferFunction[_layerCount]; - basePath = "NeuralNetwork/Parameters/Layers/Layer"; - - for (int l = 0; l < _layerCount; l++) - { - int.TryParse(XPathValue(basePath + "[@Index='" + l.ToString(CultureInfo.InvariantCulture) + "']/@Size"), out _layerSize[l]); - Enum.TryParse(XPathValue(basePath + "[@Index='" + l.ToString(CultureInfo.InvariantCulture) + "']/@Type"), out TransferFunction[l]); - } - // Parse the weights element, start dimensioning arrays. - Bias = new double[_layerCount][]; - _previousBiasDelta = new double[_layerCount][]; - _delta = new double[_layerCount][]; - _layerOutput = new double[_layerCount][]; - _layerInput = new double[_layerCount][]; - Weight = new double[_layerCount][][]; - _previousWeightDelta = new double[_layerCount][][]; - // Fill in 2-dimensional arrays. - for (int l = 0; l < _layerCount; l++) - { - Bias[l] = new double[_layerSize[l]]; - _previousBiasDelta[l] = new double[_layerSize[l]]; - _delta[l] = new double[_layerSize[l]]; - _layerOutput[l] = new double[_layerSize[l]]; - _layerInput[l] = new double[_layerSize[l]]; - Weight[l] = new double[l == 0 ? _inputSize : _layerSize[l - 1]][]; - _previousWeightDelta[l] = new double[l == 0 ? _inputSize : _layerSize[l - 1]][]; - - for (int i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - { - Weight[l][i] = new double[_layerSize[l]]; - _previousWeightDelta[l][i] = new double[_layerSize[l]]; - } - } - // Intiailze the weights. - for (int l = 0; l < _layerCount; l++) - { - basePath = "NeuralNetwork/Weights/Layer[@Index='" + l.ToString(CultureInfo.InvariantCulture) + "']/"; - string nodePath; - double value; - for (int j = 0; j < _layerSize[l]; j++) - { - nodePath = "Node[@Index='" + j.ToString(CultureInfo.InvariantCulture) + "']/@Bias"; - double.TryParse(XPathValue(basePath + nodePath), out value); - Bias[l][j] = value; - _previousBiasDelta[l][j] = 0.0; - _layerOutput[l][j] = 0.0; - _layerInput[l][j] = 0.0; - _delta[l][j] = 0.0; - } - for (int i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - { - for (int j = 0; j < _layerSize[l]; j++) - { - nodePath = "Node[@Index='" + j.ToString(CultureInfo.InvariantCulture) + "']/Axion[@Index='" + i.ToString(CultureInfo.InvariantCulture) + "']"; - double.TryParse(XPathValue(basePath + nodePath), out value); - - Weight[l][i][j] = value; - _previousWeightDelta[l][i][j] = 0.0; - } - } - } - // Release - _document = null; - } - /// - /// Returns the Xpath value. - /// - /// The X path. - /// - /// Cannot find specified node - private string XPathValue(string xPath) - { - var node = _document.SelectSingleNode((xPath)); - if (node == null) - throw new ArgumentException("Cannot find specified node.", xPath); - return node.InnerText; - } - - #region Really needed? - /// - /// Computes against the network with the specified input. (This is the same as RunEvaluation) - /// - /// The input. - /// - /// Input data is not of the correct dimension. - public double[] Compute(double[] input) - { - // Make sure enough data. - if (input.Length != _inputSize) - throw new ArgumentException("Input data is not of the correct dimension."); - // Dimension. - var output = new double[_layerSize[_layerCount - 1]]; - // Run the network. - for (int l = 0; l < _layerCount; l++) - { - for (int j = 0; j < _layerSize[l]; j++) - { - double sum = 0.0; - for (int i = 0; i < (l == 0 ? _inputSize : _layerSize[l - 1]); i++) - sum += Weight[l][i][j] * (l == 0 ? input[i] : _layerOutput[l - 1][i]); - - sum += Bias[l][j]; - _layerInput[l][j] = sum; - _layerOutput[l][j] = TransferFunctions.Evaluate(TransferFunction[l], sum); - } - } - // Copy the output to the output array. - for (int i = 0; i < _layerSize[_layerCount - 1]; i++) - output[i] = _layerOutput[_layerCount - 1][i]; - return output; - - } - #endregion - } -} diff --git a/core/Boagaphish/Custom/CustomNetwork.cs b/core/Boagaphish/Custom/CustomNetwork.cs deleted file mode 100644 index 87e7b2f..0000000 --- a/core/Boagaphish/Custom/CustomNetwork.cs +++ /dev/null @@ -1,182 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.Custom -{ - /// - /// My own specific implementation of a back-propagation network. - /// - public class CustomNetwork : BackPropagationNetwork - { - private readonly double[] _inputs; - // Parts for the input-to-hidden. - private double _ihWeight00; - private double _ihWeight01; - private double _ihWeight10; - private double _ihWeight11; - private double _ihBias0; - private double _ihBias1; - private double _ihSum0; - private double _ihSum1; - private double _ihResult0; - private double _ihResult1; - // Parts for the hidden-to-output. - private double _hoWeight00; - private double _hoWeight01; - private double _hoWeight10; - private double _hoWeight11; - private double _hoBias0; - private double _hoBias1; - private double _hoSum0; - private double _hoSum1; - private double _hoResult0; - private double _hoResult1; - /// - /// The output of the network. - /// - public double[] NetworkOutput; - /// - /// Initializes a new instance of the class. - /// - public CustomNetwork() - { - _inputs = new double[2]; - NetworkOutput = new double[2]; - } - /// - /// Sets the inputs. - /// - /// The inputs. - public void SetInputs(double[] inputs) - { - inputs.CopyTo(_inputs, 0); - } - /// - /// Sets the weights. Not good as this should be computed for not simply assigned from the application. - /// - /// The weights and biases. - public void SetWeights(double[] weightsAndBiases) - { - int k = 0; - _ihWeight00 = weightsAndBiases[k++]; - _ihWeight01 = weightsAndBiases[k++]; - _ihWeight10 = weightsAndBiases[k++]; - _ihWeight11 = weightsAndBiases[k++]; - _ihBias0 = weightsAndBiases[k++]; - _ihBias1 = weightsAndBiases[k++]; - - _hoWeight00 = weightsAndBiases[k++]; - _hoWeight01 = weightsAndBiases[k++]; - _hoWeight10 = weightsAndBiases[k++]; - _hoWeight11 = weightsAndBiases[k++]; - _hoBias0 = weightsAndBiases[k++]; - _hoBias1 = weightsAndBiases[k]; - } - /// - /// Computes the outputs. - /// - /// Type of the activation. - public void ComputeOutputs(string activationType) - { - // assumes this.inputs[] have values - _ihSum0 = (_inputs[0] * _ihWeight00) + (_inputs[1] * _ihWeight10); - _ihSum0 += _ihBias0; - _ihSum1 = (_inputs[0] * _ihWeight01) + (_inputs[1] * _ihWeight11); - _ihSum1 += _ihBias1; - _ihResult0 = Evaluation(_ihSum0, activationType, "ih"); - _ihResult1 = Evaluation(_ihSum1, activationType, "ih"); - - //Console.WriteLine("ihSum0 = " + ihSum0); - //Console.WriteLine("ihResult0 = " + ihResult0); - //Console.WriteLine("ihSum1 = " + ihSum1); - //Console.WriteLine("ihResult1 = " + ihResult1); - - _hoSum0 = (_ihResult0 * _hoWeight00) + (_ihResult1 * _hoWeight10); - _hoSum0 += _hoBias0; - _hoSum1 = (_ihResult0 * _hoWeight01) + (_ihResult1 * _hoWeight11); - _hoSum1 += _hoBias1; - // - // - _hoResult0 = Evaluation(_hoSum0, activationType, "ho"); - _hoResult1 = Evaluation(_hoSum1, activationType, "ho"); - - //Console.WriteLine("hoSum0 = " + hoSum0); - //Console.WriteLine("hoResult0 = " + hoResult0); - //Console.WriteLine("hoSum1 = " + hoSum1); - //Console.WriteLine("hoResult1 = " + hoResult1); - - NetworkOutput[0] = _hoResult0; - NetworkOutput[1] = _hoResult1; - } - /// - /// Computes softmax the specified value and layer. - /// - /// The x. - /// The layer. - /// - public double ComputeSoftmax(double x, string layer) - { - // Determine the maximum value. - double max = double.MinValue; - if (layer == "ih") - max = (_ihSum0 > _ihSum1) ? _ihSum0 : _ihSum1; - else if (layer == "ho") - max = (_hoSum0 > _hoSum1) ? _hoSum0 : _hoSum1; - // Compute the scale. - double scale = 0.0; - if (layer == "ih") - scale = Math.Exp(_ihSum0 - max) + Math.Exp(_ihSum1 - max); - else if (layer == "ho") - scale = Math.Exp(_hoSum0 - max) + Math.Exp(_hoSum1 - max); - - return Math.Exp(x - max) / scale; - } - /// - /// An evaluation of a value, an activation type, and a layer. - /// - /// The x. - /// Type of the activation. - /// The layer. - /// - /// Not implemented - public double Evaluation(double x, string activationType, string layer) - { - activationType = activationType.ToLower().Trim(); - if (activationType == "logsigmoid") - return LogSigmoid(x); - if (activationType == "hyperbolictangent") - return HyperbolicTangtent(x); - if (activationType == "softmax") - return NormalizedExponential(x, layer); - throw new Exception("Not implemented"); - } - private static double LogSigmoid(double x) - { - if (x < -45.0) return 0.0; - if (x > 45.0) return 1.0; - return 1.0 / (1.0 + Math.Exp(-x)); - } - private static double HyperbolicTangtent(double x) - { - if (x < -45.0) return -1.0; - if (x > 45.0) return 1.0; - return Math.Tanh(x); - } - private double NormalizedExponential(double x, string layer) - { - // naive version - double scale = 0.0; - if (layer == "ih") - scale = Math.Exp(_ihSum0) + Math.Exp(_ihSum1); - else if (layer == "ho") - scale = Math.Exp(_hoSum0) + Math.Exp(_hoSum1); - else - throw new Exception("Unknown layer"); - - return Math.Exp(x) / scale; - } - - } -} diff --git a/core/Boagaphish/Custom/Gaussian.cs b/core/Boagaphish/Custom/Gaussian.cs deleted file mode 100644 index fc7e963..0000000 --- a/core/Boagaphish/Custom/Gaussian.cs +++ /dev/null @@ -1,57 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Boagaphish.Format; - -namespace Boagaphish.Custom -{ - public static class Gaussian - { - private static readonly StaticRandom Generator = new StaticRandom(); - const double Epsilon = 1E-6; - /// - /// Gets a random gaussian. - /// - /// - public static double RandomGaussian() - { - return RandomGaussian(0.0, 1.0); - } - /// - /// Gets a random gaussian. - /// - /// The mean. - /// The standard deviation. - /// - public static double RandomGaussian(double mean, double standardDeviation) - { - double valueOne, valueTwo; - RandomGaussian(mean, standardDeviation, out valueOne, out valueTwo); - return valueOne; - } - /// - /// Gets a random gaussian. - /// - /// The mean. - /// The standard deviation. - /// The value one. - /// The value two. - public static void RandomGaussian(double mean, double standardDeviation, out double valueOne, - out double valueTwo) - { - double u, v; - do - { - u = 2 * Generator.NextDouble() - 1; - v = 2 * Generator.NextDouble() - 1; - - } while (u * u + v * v > 1 || (Math.Abs(u) < Epsilon && Math.Abs(v) < Epsilon)); - - var s = u * u + v * v; - var t = Math.Sqrt((-2.0 * Math.Log(s)) / s); - valueOne = standardDeviation * u * t + mean; - valueTwo = standardDeviation * v * t + mean; - } - } -} diff --git a/core/Boagaphish/Custom/ODE.png b/core/Boagaphish/Custom/ODE.png deleted file mode 100644 index f02930d..0000000 Binary files a/core/Boagaphish/Custom/ODE.png and /dev/null differ diff --git a/core/Boagaphish/Format/StaticRandom.cs b/core/Boagaphish/Format/StaticRandom.cs deleted file mode 100644 index 5a01588..0000000 --- a/core/Boagaphish/Format/StaticRandom.cs +++ /dev/null @@ -1,96 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.Format -{ - /// - /// Thread-safe equivalent of System.Random using static methods. - /// - public class StaticRandom - { - static readonly Random Random = new Random(); - static readonly Random RandomSeed = new Random(Ticks); - static readonly object RandomLock = new object(); - static int Ticks { get; set; } - /// - /// Initializes a new instance of the class. - /// - public StaticRandom() { } - /// - /// Initializes a new instance of the class. - /// - /// The seed. - public StaticRandom(int seed) - { - Ticks = seed; - } - /// - /// Returns a nonnegative random number. - /// - /// A 32-bit signed integer greater than or equal to zero and less than Int32.MaxValue. - public static int Next() - { - lock (RandomLock) - { - return Random.Next(); - } - } - /// - /// Returns a nonnegative random number less than the specified maximum. - /// - /// - /// A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values includes zero but not maxValue. - /// - /// maxValue is less than zero. - public static int Next(int max) - { - lock (RandomLock) - { - return Random.Next(max); - } - } - /// - /// Returns a random number within a specified range. - /// - /// The inclusive lower bound of the random number returned. - /// - /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. - /// - /// - /// A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned. - /// - /// minValue is greater than maxValue. - public static int Next(int min, int max) - { - lock (RandomLock) - { - return Random.Next(min, max); - } - } - /// - /// Returns a random number between 0.0 and 1.0. - /// - /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0. - public double NextDouble() - { - lock (RandomLock) - { - return RandomSeed.NextDouble(); - } - } - /// - /// Fills the elements of a specified array of bytes with random numbers. - /// - /// An array of bytes to contain random numbers. - /// buffer is a null reference (Nothing in Visual Basic). - public static void NextBytes(byte[] buffer) - { - lock (RandomLock) - { - Random.NextBytes(buffer); - } - } - } -} diff --git a/core/Boagaphish/Format/XDate.cs b/core/Boagaphish/Format/XDate.cs deleted file mode 100644 index 9882bb7..0000000 --- a/core/Boagaphish/Format/XDate.cs +++ /dev/null @@ -1,1560 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.Format -{ - /// - /// This struct encapsulates a date and time value, and handles associated calculations and conversions between various formats. - /// - /// - /// This format stored as a double value representing days since a reference date (XL date 0.0 is December 30, 1899 at 00:00 hrs). Negative values are permissible, and the range of valid dates is from noon on January 1st, 4713 B.C. forward. Internally, the date calculations are done using Astronomical Julian Day numbers. The Astronomical Julian Day number is defined as the number of days since noon on January 1st, 4713 B.C. (also referred to as 12:00 on January 1, -4712). NOTE: MS Excel actually has an error in the Serial Date calculations because it errantly assumes 1900 is a leap year. The XDate calculations do not have this same error. Therefore, XDate and Excel Date Serial values are 1 day different up until the date value of 60 (in Excel, this is February 29th, 1900, and in XDate, this is February 28th, 1900). At a value of 61 (March 1st, 1900) or greater, they agree with eachother. - /// - public struct XDate : IComparable, ICloneable - { - #region Internal variables - /// - /// The actual date value in MS Excel format. This is the only data field in - /// the struct. - /// - private double _xlDate; - /// - /// The Astronomical Julian Day number that corresponds to XL Date 0.0 - /// - public const double XlDay1 = 2415018.5; - /// - /// The minimum valid Julian Day, which corresponds to January 1st, 4713 B.C. - /// - public const double JulDayMin = 0.0; - /// - /// The maximum valid Julian Day, which corresponds to December 31st, 9999 A.D. - /// - public const double JulDayMax = 5373483.5; - /// - /// The minimum valid Excel Day, which corresponds to January 1st, 4713 B.C. - /// - public const double XlDayMin = JulDayMin - XlDay1; - /// - /// The maximum valid Excel Day, which corresponds to December 31st, 9999 A.D. - /// - public const double XlDayMax = JulDayMax - XlDay1; - /// - /// The number of months in a year - /// - public const double MonthsPerYear = 12.0; - /// - /// The number of hours in a day - /// - public const double HoursPerDay = 24.0; - /// - /// The number of minutes in an hour - /// - public const double MinutesPerHour = 60.0; - /// - /// The number of seconds in a minute - /// - public const double SecondsPerMinute = 60.0; - /// - /// The number of minutes in a day - /// - public const double MinutesPerDay = 1440.0; - /// - /// The number of seconds in a day - /// - public const double SecondsPerDay = 86400.0; - /// - /// The number of milliseconds in a second - /// - public const double MillisecondsPerSecond = 1000.0; - /// - /// The number of milliseconds in a day - /// - public const double MillisecondsPerDay = 86400000.0; - /// - /// The default format string to be used in when - /// no format is provided - /// - // public const string DefaultFormatStr = "&d-&mmm-&yy &hh:&nn"; - public const string DefaultFormatStr = "g"; - #endregion - - /// - /// Construct a date class from an XL date value. - /// - /// - /// An XL Date value in floating point double format - /// - public XDate(double xlDate) - { - _xlDate = xlDate; - } - /// - /// Construct a date class from a struct. - /// - /// - /// A struct containing the initial date information. - /// - public XDate(DateTime dateTime) - { - _xlDate = CalendarDateToXlDate(dateTime.Year, dateTime.Month, - dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second, - dateTime.Millisecond); - } - /// - /// Construct a date class from a calendar date (year, month, day). Assumes the time of day is 00:00 hrs - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. It is permissible to have day numbers outside of the 1-31 range, which will rollover to the previous or next month and year. - /// An integer value for the month of the year, e.g., 8 for August. It is permissible to have months outside of the 1-12 range, which will rollover to the previous or next year. - public XDate(int year, int month, int day) - { - _xlDate = CalendarDateToXlDate(year, month, day, 0, 0, 0); - } - /// - /// Construct a date class from a calendar date and time (year, month, day, hour, minute, second). - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. It is permissible to have day numbers outside of the 1-31 range, which will rollover to the previous or next month and year. - /// An integer value for the month of the year, e.g., 8 for August. It is permissible to have months outside of the 1-12 range, which will rollover to the previous or next year. - /// An integer value for the hour of the day, e.g. 15. It is permissible to have hour values outside the 0-23 range, which will rollover to the previous or next day. - /// An integer value for the minute, e.g. 45. It is permissible to have hour values outside the 0-59 range, which will rollover to the previous or next hour. - /// An integer value for the second, e.g. 35. It is permissible to have second values outside the 0-59 range, which will rollover to the previous or next minute. - public XDate(int year, int month, int day, int hour, int minute, int second) - { - _xlDate = CalendarDateToXlDate(year, month, day, hour, minute, second); - } - /// - /// Construct a date class from a calendar date and time (year, month, day, hour, minute, second), where seconds is a value (allowing fractional seconds). - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. It is permissible to have day numbers outside of the 1-31 range, which will rollover to the previous or next month and year. - /// An integer value for the month of the year, e.g., 8 for August. It is permissible to have months outside of the 1-12 range, which will rollover to the previous or next year. - /// An integer value for the hour of the day, e.g. 15. It is permissible to have hour values outside the 0-23 range, which will rollover to the previous or next day. - /// An integer value for the minute, e.g. 45. It is permissible to have hour values outside the 0-59 range, which will rollover to the previous or next hour. - /// A double value for the second, e.g. 35.75. It is permissible to have second values outside the 0-59 range, which will rollover to the previous or next minute. - public XDate(int year, int month, int day, int hour, int minute, double second) - { - _xlDate = CalendarDateToXlDate(year, month, day, hour, minute, second); - } - /// - /// Construct a date class from a calendar date and time (year, month, day, hour, minute, second, millisecond). - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. It is permissible to have day numbers outside of the 1-31 range, which will rollover to the previous or next month and year. - /// An integer value for the month of the year, e.g., 8 for August. It is permissible to have months outside of the 1-12 range, which will rollover to the previous or next year. - /// An integer value for the hour of the day, e.g. 15. It is permissible to have hour values outside the 0-23 range, which will rollover to the previous or next day. - /// An integer value for the minute, e.g. 45. It is permissible to have hour values outside the 0-59 range, which will rollover to the previous or next hour. - /// An integer value for the second, e.g. 35. It is permissible to have second values outside the 0-59 range, which will rollover to the previous or next minute. - /// An integer value for the millisecond, e.g. 632. It is permissible to have millisecond values outside the 0-999 range, which will rollover to the previous or next second. - public XDate(int year, int month, int day, int hour, int minute, int second, int millisecond) - { - _xlDate = CalendarDateToXlDate(year, month, day, hour, minute, second, millisecond); - } - /// - /// The Copy Constructor - /// - /// The GraphPane object from which to copy - public XDate(XDate rhs) - { - _xlDate = rhs._xlDate; - } - /// - /// Implement the interface in a typesafe manner by just - /// calling the typed version of - /// - /// A deep copy of this object - object ICloneable.Clone() - { - return Clone(); - } - /// - /// Typesafe, deep-copy clone method. - /// - /// A new, independent copy of this class - public XDate Clone() - { - return new XDate(this); - } - - /// - /// Gets or sets the date value for this item in MS Excel format. - /// - public double XlDate - { - get { return _xlDate; } - set { _xlDate = value; } - } - /// - /// Returns true if this struct is in the valid date range - /// - public bool IsValidDate - { - get { return _xlDate >= XlDayMin && _xlDate <= XlDayMax; } - } - /// - /// Gets or sets the date value for this item in .Net DateTime format. - /// - public DateTime DateTime - { - get { return XlDateToDateTime(_xlDate); } - set { _xlDate = DateTimeToXlDate(value); } - } - /// - /// Gets or sets the date value for this item in Julain day format. This is the - /// Astronomical Julian Day number, so a value of 0.0 corresponds to noon GMT on - /// January 1st, -4712. Thus, Julian Day number 2,400,000.0 corresponds to - /// noon GMT on November 16, 1858. - /// - public double JulianDay - { - get { return XlDateToJulianDay(_xlDate); } - set { _xlDate = JulianDayToXlDate(value); } - } - /// - /// Gets or sets the decimal year number (i.e., 1997.345) corresponding to this item. - /// - public double DecimalYear - { - get { return XlDateToDecimalYear(_xlDate); } - set { _xlDate = DecimalYearToXlDate(value); } - } - - #region Get/Set Date Methods - - /// - /// Returns true if the specified date value is in the valid range - /// - /// The XL date value to be verified for validity - /// true for a valid date, false otherwise - private static bool CheckValidDate(double xlDate) - { - return xlDate >= XlDayMin && xlDate <= XlDayMax; - } - /// - /// Take the specified date, and bound it to the valid date range for the XDate struct. - /// - /// The date to be bounded - /// An XLDate value that lies between the minimum and maximum valid date ranges - /// (see and ) - public static double MakeValidDate(double xlDate) - { - if (xlDate < XlDayMin) - xlDate = XlDayMin; - if (xlDate > XlDayMax) - xlDate = XlDayMax; - return xlDate; - } - /// - /// Get the calendar date (year, month, day) corresponding to this instance. - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. - /// An integer value for the month of the year, e.g., - /// 8 for August. - public void GetDate(out int year, out int month, out int day) - { - int hour, minute, second; - - XlDateToCalendarDate(_xlDate, out year, out month, out day, out hour, out minute, out second); - } - /// - /// Set the calendar date (year, month, day) of this instance. - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. - /// An integer value for the month of the year, e.g., - /// 8 for August. - public void SetDate(int year, int month, int day) - { - _xlDate = CalendarDateToXlDate(year, month, day, 0, 0, 0); - } - /// - /// Get the calendar date (year, month, day, hour, minute, second) corresponding - /// to this instance. - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. - /// An integer value for the month of the year, e.g., - /// 8 for August. - /// An integer value for the hour of the day, e.g. 15. - /// An integer value for the minute, e.g. 45. - /// An integer value for the second, e.g. 35. - public void GetDate(out int year, out int month, out int day, - out int hour, out int minute, out int second) - { - XlDateToCalendarDate(_xlDate, out year, out month, out day, out hour, out minute, out second); - } - /// - /// Set the calendar date (year, month, day, hour, minute, second) of this instance. - /// - /// An integer value for the year, e.g., 1995. - /// An integer value for the day of the month, e.g., 23. - /// An integer value for the month of the year, e.g., - /// 8 for August. - /// An integer value for the hour of the day, e.g. 15. - /// An integer value for the minute, e.g. 45. - /// An integer value for the second, e.g. 35. - public void SetDate(int year, int month, int day, int hour, int minute, int second) - { - _xlDate = CalendarDateToXlDate(year, month, day, hour, minute, second); - } - /// - /// Get the day of year value (241.345 means the 241st day of the year) - /// corresponding to this instance. - /// - /// The day of the year in floating point double format. - public double GetDayOfYear() - { - return XlDateToDayOfYear(_xlDate); - } - #endregion - - #region Date Conversion Methods - /// - /// Calculate an XL Date from the specified Calendar date (year, month, day, hour, minute, second), - /// first normalizing all input data values. - /// - /// - /// The Calendar date is always based on the Gregorian Calendar. Note that the Gregorian calendar is really - /// only valid from October 15, 1582 forward. The countries that adopted the Gregorian calendar - /// first did so on October 4, 1582, so that the next day was October 15, 1582. Prior to that time - /// the Julian Calendar was used. However, Prior to March 1, 4 AD the treatment of leap years was - /// inconsistent, and prior to 45 BC the Julian Calendar did not exist. The - /// struct projects only Gregorian dates backwards and does not deal with Julian calendar dates at all. The - /// method will just append a "(BC)" notation to the end of any dates - /// prior to 1 AD, since the struct throws an exception when formatting earlier dates. - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// - /// The integer millisecond value (e.g., 374 for 374 milliseconds past the second). - /// - /// The corresponding XL date, expressed in double floating point format - public static double CalendarDateToXlDate(int year, int month, int day, - int hour, int minute, int second, int millisecond) - { - // Normalize the data to allow for negative and out of range values - // In this way, setting month to zero would be December of the previous year, - // setting hour to 24 would be the first hour of the next day, etc. - //double dsec = second + (double) millisecond / MillisecondsPerSecond; - double ms = millisecond; - NormalizeCalendarDate(ref year, ref month, ref day, ref hour, ref minute, ref second, - ref ms); - - return _CalendarDateToXLDate(year, month, day, hour, minute, second, ms); - } - /// - /// Calculate an XL Date from the specified Calendar date (year, month, day, hour, minute, second), - /// first normalizing all input data values. - /// - /// - /// The Calendar date is always based on the Gregorian Calendar. Note that the Gregorian calendar is really - /// only valid from October 15, 1582 forward. The countries that adopted the Gregorian calendar - /// first did so on October 4, 1582, so that the next day was October 15, 1582. Prior to that time - /// the Julian Calendar was used. However, Prior to March 1, 4 AD the treatment of leap years was - /// inconsistent, and prior to 45 BC the Julian Calendar did not exist. The - /// struct projects only Gregorian dates backwards and does not deal with Julian calendar dates at all. The - /// method will just append a "(BC)" notation to the end of any dates - /// prior to 1 AD, since the struct throws an exception when formatting earlier dates. - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// The corresponding XL date, expressed in double floating point format - public static double CalendarDateToXlDate(int year, int month, int day, - int hour, int minute, int second) - { - // Normalize the data to allow for negative and out of range values - // In this way, setting month to zero would be December of the previous year, - // setting hour to 24 would be the first hour of the next day, etc. - double ms = 0; - NormalizeCalendarDate(ref year, ref month, ref day, ref hour, ref minute, - ref second, ref ms); - - return _CalendarDateToXLDate(year, month, day, hour, minute, second, ms); - } - /// - /// Calculate an XL Date from the specified Calendar date (year, month, day, hour, minute, second), - /// first normalizing all input data values. The seconds value is a double type, allowing fractional - /// seconds. - /// - /// - /// The Calendar date is always based on the Gregorian Calendar. Note that the Gregorian calendar is really - /// only valid from October 15, 1582 forward. The countries that adopted the Gregorian calendar - /// first did so on October 4, 1582, so that the next day was October 15, 1582. Prior to that time - /// the Julian Calendar was used. However, Prior to March 1, 4 AD the treatment of leap years was - /// inconsistent, and prior to 45 BC the Julian Calendar did not exist. The - /// struct projects only Gregorian dates backwards and does not deal with Julian calendar dates at all. The - /// method will just append a "(BC)" notation to the end of any dates - /// prior to 1 AD, since the struct throws an exception when formatting earlier dates. - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The double second value (e.g., 42.3 for 42.3 seconds past the minute). - /// - /// The corresponding XL date, expressed in double floating point format - public static double CalendarDateToXlDate(int year, int month, int day, - int hour, int minute, double second) - { - // Normalize the data to allow for negative and out of range values - // In this way, setting month to zero would be December of the previous year, - // setting hour to 24 would be the first hour of the next day, etc. - int sec = (int)second; - double ms = (second - sec) * MillisecondsPerSecond; - NormalizeCalendarDate(ref year, ref month, ref day, ref hour, ref minute, ref sec, - ref ms); - - return _CalendarDateToXLDate(year, month, day, hour, minute, sec, ms); - } - /// - /// Calculate an Astronomical Julian Day number from the specified Calendar date - /// (year, month, day, hour, minute, second), first normalizing all input data values - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// The corresponding Astronomical Julian Day number, expressed in double - /// floating point format - public static double CalendarDateToJulianDay(int year, int month, int day, - int hour, int minute, int second) - { - // Normalize the data to allow for negative and out of range values - // In this way, setting month to zero would be December of the previous year, - // setting hour to 24 would be the first hour of the next day, etc. - double ms = 0; - NormalizeCalendarDate(ref year, ref month, ref day, ref hour, ref minute, - ref second, ref ms); - - return _CalendarDateToJulianDay(year, month, day, hour, minute, second, ms); - } - /// - /// Calculate an Astronomical Julian Day number from the specified Calendar date - /// (year, month, day, hour, minute, second), first normalizing all input data values - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// - /// The integer second value (e.g., 325 for 325 milliseconds past the minute). - /// - /// The corresponding Astronomical Julian Day number, expressed in double - /// floating point format - public static double CalendarDateToJulianDay(int year, int month, int day, - int hour, int minute, int second, int millisecond) - { - // Normalize the data to allow for negative and out of range values - // In this way, setting month to zero would be December of the previous year, - // setting hour to 24 would be the first hour of the next day, etc. - double ms = millisecond; - - NormalizeCalendarDate(ref year, ref month, ref day, ref hour, ref minute, - ref second, ref ms); - - return _CalendarDateToJulianDay(year, month, day, hour, minute, second, ms); - } - /// - /// Normalize a set of Calendar date values (year, month, day, hour, minute, second) to make sure - /// that month is between 1 and 12, hour is between 0 and 23, etc. - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// - /// The double millisecond value (e.g., 325.3 for 325.3 milliseconds past the second). - /// - private static void NormalizeCalendarDate(ref int year, ref int month, ref int day, - ref int hour, ref int minute, ref int second, - ref double millisecond) - { - // Normalize the data to allow for negative and out of range values - // In this way, setting month to zero would be December of the previous year, - // setting hour to 24 would be the first hour of the next day, etc. - - // Normalize the milliseconds and carry over to seconds - int carry = (int)Math.Floor(millisecond / MillisecondsPerSecond); - millisecond -= carry * (int)MillisecondsPerSecond; - second += carry; - - // Normalize the seconds and carry over to minutes - carry = (int)Math.Floor(second / SecondsPerMinute); - second -= carry * (int)SecondsPerMinute; - minute += carry; - - // Normalize the minutes and carry over to hours - carry = (int)Math.Floor(minute / MinutesPerHour); - minute -= carry * (int)MinutesPerHour; - hour += carry; - - // Normalize the hours and carry over to days - carry = (int)Math.Floor(hour / HoursPerDay); - hour -= carry * (int)HoursPerDay; - day += carry; - - // Normalize the months and carry over to years - carry = (int)Math.Floor(month / MonthsPerYear); - month -= carry * (int)MonthsPerYear; - year += carry; - } - /// - /// Calculate an XL date from the specified Calendar date (year, month, day, hour, minute, second). - /// This is the internal trusted version, where all values are assumed to be legitimate - /// ( month is between 1 and 12, minute is between 0 and 59, etc. ) - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// - /// The double millisecond value (e.g., 325.3 for 325.3 milliseconds past the second). - /// - /// The corresponding XL date, expressed in double floating point format - private static double _CalendarDateToXLDate(int year, int month, int day, int hour, - int minute, int second, double millisecond) - { - return JulianDayToXlDate(_CalendarDateToJulianDay(year, month, day, hour, minute, - second, millisecond)); - } - /// - /// Calculate an Astronomical Julian Day Number from the specified Calendar date - /// (year, month, day, hour, minute, second). - /// This is the internal trusted version, where all values are assumed to be legitimate - /// ( month is between 1 and 12, minute is between 0 and 59, etc. ) - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// - /// The double millisecond value (e.g., 325.3 for 325.3 milliseconds past the second). - /// - /// The corresponding Astronomical Julian Day number, expressed in double - /// floating point format - private static double _CalendarDateToJulianDay(int year, int month, int day, int hour, - int minute, int second, double millisecond) - { - // Taken from http://www.srrb.noaa.gov/highlights/sunrise/program.txt - // routine calcJD() - - if (month <= 2) - { - year -= 1; - month += 12; - } - - double A = Math.Floor(year / 100.0); - double B = 2 - A + Math.Floor(A / 4.0); - - return Math.Floor(365.25 * (year + 4716.0)) + - Math.Floor(30.6001 * (month + 1)) + - day + B - 1524.5 + - hour / HoursPerDay + minute / MinutesPerDay + second / SecondsPerDay + - millisecond / MillisecondsPerDay; - - } - /// - /// Calculate a Calendar date (year, month, day, hour, minute, second) corresponding to - /// the specified XL date - /// - /// - /// The XL date value in floating point double format. - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - public static void XlDateToCalendarDate(double xlDate, out int year, out int month, - out int day, out int hour, out int minute, out int second) - { - double jDay = XlDateToJulianDay(xlDate); - - JulianDayToCalendarDate(jDay, out year, out month, out day, out hour, - out minute, out second); - } - /// - /// Calculate a Calendar date (year, month, day, hour, minute, second) corresponding to - /// the specified XL date - /// - /// - /// The XL date value in floating point double format. - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// - /// The integer millisecond value (e.g., 325 for 325 milliseconds past the second). - /// - public static void XlDateToCalendarDate(double xlDate, out int year, out int month, - out int day, out int hour, out int minute, out int second, out int millisecond) - { - double jDay = XlDateToJulianDay(xlDate); - - double ms; - JulianDayToCalendarDate(jDay, out year, out month, out day, out hour, - out minute, out second, out ms); - millisecond = (int)ms; - } - /// - /// Calculate a Calendar date (year, month, day, hour, minute, second) corresponding to - /// the specified XL date - /// - /// - /// The XL date value in floating point double format. - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The double second value (e.g., 42.3 for 42.3 seconds past the minute). - /// - public static void XlDateToCalendarDate(double xlDate, out int year, out int month, - out int day, out int hour, out int minute, out double second) - { - double jDay = XlDateToJulianDay(xlDate); - - JulianDayToCalendarDate(jDay, out year, out month, out day, out hour, - out minute, out second); - } - /// - /// Calculate a Calendar date (year, month, day, hour, minute, second) corresponding to - /// the Astronomical Julian Day number - /// - /// - /// The Astronomical Julian Day number to be converted - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - public static void JulianDayToCalendarDate(double jDay, out int year, out int month, - out int day, out int hour, out int minute, out int second) - { - double ms; - - JulianDayToCalendarDate(jDay, out year, out month, - out day, out hour, out minute, out second, out ms); - } - /// - /// Calculate a Calendar date (year, month, day, hour, minute, second) corresponding to - /// the Astronomical Julian Day number - /// - /// - /// The Astronomical Julian Day number to be converted - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The double second value (e.g., 42.3 for 42.3 seconds past the minute). - /// - public static void JulianDayToCalendarDate(double jDay, out int year, out int month, - out int day, out int hour, out int minute, out double second) - { - int sec; - double ms; - - JulianDayToCalendarDate(jDay, out year, out month, - out day, out hour, out minute, out sec, out ms); - - second = sec + ms / MillisecondsPerSecond; - } - /// - /// Calculate a Calendar date (year, month, day, hour, minute, second) corresponding to - /// the Astronomical Julian Day number - /// - /// - /// The Astronomical Julian Day number to be converted - /// - /// - /// The integer year value (e.g., 1994). - /// - /// - /// The integer month value (e.g., 7 for July). - /// - /// - /// The integer day value (e.g., 19 for the 19th day of the month). - /// - /// - /// The integer hour value (e.g., 14 for 2:00 pm). - /// - /// - /// The integer minute value (e.g., 35 for 35 minutes past the hour). - /// - /// - /// The integer second value (e.g., 42 for 42 seconds past the minute). - /// - /// - /// The millisecond value (e.g., 342.5 for 342.5 milliseconds past - /// the second). - /// - public static void JulianDayToCalendarDate(double jDay, out int year, out int month, - out int day, out int hour, out int minute, out int second, out double millisecond) - { - // add 5 ten-thousandths of a second to the day fraction to avoid roundoff errors - jDay += 0.0005 / SecondsPerDay; - - double z = Math.Floor(jDay + 0.5); - double f = jDay + 0.5 - z; - - double alpha = Math.Floor((z - 1867216.25) / 36524.25); - double a = z + 1.0 + alpha - Math.Floor(alpha / 4); - double b = a + 1524.0; - double c = Math.Floor((b - 122.1) / 365.25); - double d = Math.Floor(365.25 * c); - double e = Math.Floor((b - d) / 30.6001); - - day = (int)Math.Floor(b - d - Math.Floor(30.6001 * e) + f); - month = (int)((e < 14.0) ? e - 1.0 : e - 13.0); - year = (int)((month > 2) ? c - 4716 : c - 4715); - - double fday = (jDay - 0.5) - Math.Floor(jDay - 0.5); - - fday = (fday - (long)fday) * HoursPerDay; - hour = (int)fday; - fday = (fday - (long)fday) * MinutesPerHour; - minute = (int)fday; - fday = (fday - (long)fday) * SecondsPerMinute; - second = (int)fday; - fday = (fday - (long)fday) * MillisecondsPerSecond; - millisecond = fday; - } - /// - /// Calculate an Astronomical Julian Day number corresponding to the specified XL date - /// - /// - /// The XL date value in floating point double format. - /// - /// The corresponding Astronomical Julian Day number, expressed in double - /// floating point format - public static double XlDateToJulianDay(double xlDate) - { - return xlDate + XlDay1; - } - /// - /// Calculate an XL Date corresponding to the specified Astronomical Julian Day number - /// - /// - /// The Astronomical Julian Day number in floating point double format. - /// - /// The corresponding XL Date, expressed in double - /// floating point format - public static double JulianDayToXlDate(double jDay) - { - return jDay - XlDay1; - } - /// - /// Calculate a decimal year value (e.g., 1994.6523) corresponding to the specified XL date - /// - /// - /// The XL date value in floating point double format. - /// - /// The corresponding decimal year value, expressed in double - /// floating point format - public static double XlDateToDecimalYear(double xlDate) - { - int year, month, day, hour, minute, second; - - XlDateToCalendarDate(xlDate, out year, out month, out day, out hour, out minute, out second); - - double jDay1 = CalendarDateToJulianDay(year, 1, 1, 0, 0, 0); - double jDay2 = CalendarDateToJulianDay(year + 1, 1, 1, 0, 0, 0); - double jDayMid = CalendarDateToJulianDay(year, month, day, hour, minute, second); - - - return year + (jDayMid - jDay1) / (jDay2 - jDay1); - } - /// - /// Calculate a decimal year value (e.g., 1994.6523) corresponding to the specified XL date - /// - /// - /// The decimal year value in floating point double format. - /// - /// The corresponding XL Date, expressed in double - /// floating point format - public static double DecimalYearToXlDate(double yearDec) - { - int year = (int)yearDec; - - double jDay1 = CalendarDateToJulianDay(year, 1, 1, 0, 0, 0); - double jDay2 = CalendarDateToJulianDay(year + 1, 1, 1, 0, 0, 0); - - return JulianDayToXlDate((yearDec - year) * (jDay2 - jDay1) + jDay1); - } - /// - /// Calculate a day-of-year value (e.g., 241.543 corresponds to the 241st day of the year) - /// corresponding to the specified XL date - /// - /// - /// The XL date value in floating point double format. - /// - /// The corresponding day-of-year (DoY) value, expressed in double - /// floating point format - public static double XlDateToDayOfYear(double xlDate) - { - int year, month, day, hour, minute, second; - XlDateToCalendarDate(xlDate, out year, out month, out day, - out hour, out minute, out second); - return XlDateToJulianDay(xlDate) - CalendarDateToJulianDay(year, 1, 1, 0, 0, 0) + 1.0; - } - /// - /// Calculate a day-of-week value (e.g., Sun=0, Mon=1, Tue=2, etc.) corresponding to the specified XL date - /// - /// - /// The XL date value in floating point double format. - /// - /// The corresponding day-of-week (DoW) value, expressed in integer format - public static int XlDateToDayOfWeek(double xlDate) - { - return (int)(XlDateToJulianDay(xlDate) + 1.5) % 7; - } - /// - /// Convert an XL date format to a .Net DateTime struct - /// - /// - /// The XL date value in floating point double format. - /// - /// The corresponding XL Date, expressed in double - /// floating point format - /// The corresponding date in the form of a .Net DateTime struct - public static DateTime XlDateToDateTime(double xlDate) - { - int year, month, day, hour, minute, second, millisecond; - XlDateToCalendarDate(xlDate, out year, out month, out day, - out hour, out minute, out second, out millisecond); - return new DateTime(year, month, day, hour, minute, second, millisecond); - } - /// - /// Convert a .Net DateTime struct to an XL Format date - /// - /// - /// The date value in the form of a .Net DateTime struct - /// - /// The corresponding XL Date, expressed in double - /// floating point format - public static double DateTimeToXlDate(DateTime dt) - { - return CalendarDateToXlDate(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, - dt.Millisecond); - } - #endregion - - #region Date Math Methods - /// - /// Add the specified number of milliseconds (can be fractional) to the current XDate instance. - /// - /// - /// The incremental number of milliseconds (negative or positive) in floating point double format. - /// - public void AddMilliseconds(double dMilliseconds) - { - _xlDate += dMilliseconds / MillisecondsPerDay; - } - /// - /// Add the specified number of seconds (can be fractional) to the current XDate instance. - /// - /// - /// The incremental number of seconds (negative or positive) in floating point double format. - /// - public void AddSeconds(double dSeconds) - { - _xlDate += dSeconds / SecondsPerDay; - } - /// - /// Add the specified number of minutes (can be fractional) to the current XDate instance. - /// - /// - /// The incremental number of minutes (negative or positive) in floating point double format. - /// - public void AddMinutes(double dMinutes) - { - _xlDate += dMinutes / MinutesPerDay; - } - /// - /// Add the specified number of hours (can be fractional) to the current XDate instance. - /// - /// - /// The incremental number of hours (negative or positive) in floating point double format. - /// - public void AddHours(double dHours) - { - _xlDate += dHours / HoursPerDay; - } - /// - /// Add the specified number of days (can be fractional) to the current XDate instance. - /// - /// - /// The incremental number of days (negative or positive) in floating point double format. - /// - public void AddDays(double dDays) - { - _xlDate += dDays; - } - /// - /// Add the specified number of Months (can be fractional) to the current XDate instance. - /// - /// - /// The incremental number of months (negative or positive) in floating point double format. - /// - public void AddMonths(double dMonths) - { - int iMon = (int)dMonths; - double monFrac = Math.Abs(dMonths - iMon); - int sMon = Math.Sign(dMonths); - - int year, month, day, hour, minute, second; - - XlDateToCalendarDate(_xlDate, out year, out month, out day, out hour, out minute, out second); - if (iMon != 0) - { - month += iMon; - _xlDate = CalendarDateToXlDate(year, month, day, hour, minute, second); - } - - if (sMon != 0) - { - double xlDate2 = CalendarDateToXlDate(year, month + sMon, day, hour, minute, second); - _xlDate += (xlDate2 - _xlDate) * monFrac; - } - } - /// - /// Add the specified number of years (can be fractional) to the current XDate instance. - /// - /// - /// The incremental number of years (negative or positive) in floating point double format. - /// - public void AddYears(double dYears) - { - int iYear = (int)dYears; - double yearFrac = Math.Abs(dYears - iYear); - int sYear = Math.Sign(dYears); - - int year, month, day, hour, minute, second; - - XlDateToCalendarDate(_xlDate, out year, out month, out day, out hour, out minute, out second); - if (iYear != 0) - { - year += iYear; - _xlDate = CalendarDateToXlDate(year, month, day, hour, minute, second); - } - - if (sYear != 0) - { - double xlDate2 = CalendarDateToXlDate(year + sYear, month, day, hour, minute, second); - _xlDate += (xlDate2 - _xlDate) * yearFrac; - } - } - #endregion - - #region Operator Overloads - /// - /// '-' operator overload. When two XDates are subtracted, the number of days between dates - /// is returned. - /// - /// The left-hand-side of the '-' operator (an XDate class) - /// The right-hand-side of the '-' operator (an XDate class) - /// The days between dates, expressed as a floating point double - public static double operator -(XDate lhs, XDate rhs) - { - return lhs.XlDate - rhs.XlDate; - } - /// - /// '-' operator overload. When a double value is subtracted from an XDate, the result is a - /// new XDate with the number of days subtracted. - /// - /// The left-hand-side of the '-' operator (an XDate class) - /// The right-hand-side of the '-' operator (a double value) - /// An XDate with the rhs number of days subtracted - public static XDate operator -(XDate lhs, double rhs) - { - lhs._xlDate -= rhs; - return lhs; - } - /// - /// '+' operator overload. When a double value is added to an XDate, the result is a - /// new XDate with the number of days added. - /// - /// The left-hand-side of the '-' operator (an XDate class) - /// The right-hand-side of the '+' operator (a double value) - /// An XDate with the rhs number of days added - public static XDate operator +(XDate lhs, double rhs) - { - lhs._xlDate += rhs; - return lhs; - } - /// - /// '++' operator overload. Increment the date by one day. - /// - /// The XDate struct on which to operate - /// An XDate one day later than the specified date - public static XDate operator ++(XDate xDate) - { - xDate._xlDate += 1.0; - return xDate; - } - /// - /// '--' operator overload. Decrement the date by one day. - /// - /// The XDate struct on which to operate - /// An XDate one day prior to the specified date - public static XDate operator --(XDate xDate) - { - xDate._xlDate -= 1.0; - return xDate; - } - /// - /// Implicit conversion from XDate to double (an XL Date). - /// - /// The XDate struct on which to operate - /// A double floating point value representing the XL Date - public static implicit operator double(XDate xDate) - { - return xDate._xlDate; - } - /// - /// Implicit conversion from XDate to float (an XL Date). - /// - /// The XDate struct on which to operate - /// A double floating point value representing the XL Date - public static implicit operator float(XDate xDate) - { - return (float)xDate._xlDate; - } - /// - /// Implicit conversion from double (an XL Date) to XDate. - /// - /// The XDate struct on which to operate - /// An XDate struct representing the specified xlDate value. - public static implicit operator XDate(double xlDate) - { - return new XDate(xlDate); - } - /// - /// Implicit conversion from XDate to . - /// - /// The XDate struct on which to operate - /// A struct representing the specified xDate value. - public static implicit operator DateTime(XDate xDate) - { - - return XlDateToDateTime(xDate); - } - /// - /// Implicit conversion from to . - /// - /// The struct on which to operate - /// An struct representing the specified DateTime value. - public static implicit operator XDate(DateTime dt) - { - - return new XDate(DateTimeToXlDate(dt)); - } - #endregion - - #region General Overrides - /// - /// Tests whether obj is either an structure or - /// a double floating point value that is equal to the same date as this XDate - /// struct instance. - /// - /// The object to compare for equality with this XDate instance. - /// This object should be either a type XDate or type double. - /// Returns true if obj is the same date as this - /// instance; otherwise, false - public override bool Equals(object obj) - { - if (obj is XDate) - { - return ((XDate)obj)._xlDate == _xlDate; - } - else if (obj is double) - { - return ((double)obj) == _xlDate; - } - else - return false; - } - /// - /// Returns the hash code for this structure. In this case, the - /// hash code is simply the equivalent hash code for the floating point double date value. - /// - /// An integer representing the hash code for this XDate value - public override int GetHashCode() - { - return _xlDate.GetHashCode(); - } - /// - /// Compares one object to another. - /// - /// - /// This method will throw an exception if is not an - /// object. - /// - /// The second object to be compared. - /// zero if is equal to the current instance, - /// -1 if is less than the current instance, and - /// 1 if is greater than the current instance. - public int CompareTo(object target) - { - if (!(target is XDate)) - throw new ArgumentException(); - - return (XlDate).CompareTo(((XDate)target).XlDate); - } - - #endregion - - #region String Format Conversion Methods - - /// - /// Format this XDate value using the default format string (). - /// - /// - /// The formatting is done using the - /// method in order to provide full localization capability. The DateTime struct is limited to - /// dates from 1 AD onward. However, all calendar dates in and - /// are projected Gregorian calendar dates. Since the Gregorian calendar was not implemented - /// until October 4, 1582 (or later in some countries), Gregorian dates prior to that time are - /// really dates that would have been, had the Gregorian calendar existed. In order to avoid - /// throwing an exception, for dates prior to 1 AD, the year will be converted to a positive - /// year and the text "(BC)" is appended to the end of the formatted string. Under this mode, the - /// year sequence is 2BC, 1BC, 1AD, 2AD, etc. There is no year zero. - /// - /// - /// The XL date value to be formatted in floating point double format. - /// - /// A string representation of the date - public string ToString(double xlDate) - { - return ToString(xlDate, DefaultFormatStr); - } - /// - /// Format this XDate value using the default format string (see cref="DefaultFormatStr"/>). - /// - /// - /// The formatting is done using the - /// - /// method in order to provide full localization capability. The DateTime struct is limited to - /// dates from 1 AD onward. However, all calendar dates in and - /// - /// are projected Gregorian calendar dates. Since the Gregorian calendar was not implemented - /// until October 4, 1582 (or later in some countries), Gregorian dates prior to that time are - /// really dates that would have been, had the Gregorian calendar existed. In order to avoid - /// throwing an exception, for dates prior to 1 AD, the year will be converted to a positive - /// year and the text "(BC)" is appended to the end of the formatted string. Under this mode, the - /// year sequence is 2BC, 1BC, 1AD, 2AD, etc. There is no year zero. - /// - /// A string representation of the date - public override string ToString() - { - return ToString(_xlDate, DefaultFormatStr); - } - /// - /// Format this XL Date value using the specified format string. The format - /// string is specified according to the class. - /// - /// - /// The formatting is done using the - /// - /// method in order to provide full localization capability. The DateTime struct is limited to - /// dates from 1 AD onward. However, all calendar dates in and - /// - /// are projected Gregorian calendar dates. Since the Gregorian calendar was not implemented - /// until October 4, 1582 (or later in some countries), Gregorian dates prior to that time are - /// really dates that would have been, had the Gregorian calendar existed. In order to avoid - /// throwing an exception, for dates prior to 1 AD, the year will be converted to a positive - /// year and the text "(BC)" is appended to the end of the formatted string. Under this mode, the - /// year sequence is 2BC, 1BC, 1AD, 2AD, etc. There is no year zero. - /// - /// - /// The formatting string to be used for the date. See - /// - /// class for a list of the format types available. - /// A string representation of the date - public string ToString(string fmtStr) - { - return ToString(XlDate, fmtStr); - } - /// - /// Format the specified XL Date value using the specified format string. The format - /// string is specified according to the class. - /// - /// - /// The formatting is done using the - /// - /// method in order to provide full localization capability. The DateTime struct is limited to - /// dates from 1 AD onward. However, all calendar dates in and - /// - /// are projected Gregorian calendar dates. Since the Gregorian calendar was not implemented - /// until October 4, 1582 (or later in some countries), Gregorian dates prior to that time are - /// really dates that would have been, had the Gregorian calendar existed. In order to avoid - /// throwing an exception, for dates prior to 1 AD, the year will be converted to a positive - /// year and the text "(BC)" is appended to the end of the formatted string. Under this mode, the - /// year sequence is 2BC, 1BC, 1AD, 2AD, etc. There is no year zero. - /// - /// - /// The XL date value to be formatted in floating point double format. - /// - /// - /// The formatting string to be used for the date. See - /// - /// for a list of the format types available. - /// A string representation of the date - public static string ToString(double xlDate, string fmtStr) - { - int year, month, day, hour, minute, second, millisecond; - - if (!CheckValidDate(xlDate)) - return "Date Error"; - - XlDateToCalendarDate(xlDate, out year, out month, out day, out hour, out minute, - out second, out millisecond); - if (year <= 0) - { - year = 1 - year; - fmtStr = fmtStr + " (BC)"; - } - - if (fmtStr.IndexOf("[d]") >= 0) - { - fmtStr = fmtStr.Replace("[d]", ((int)xlDate).ToString()); - xlDate -= (int)xlDate; - } - if (fmtStr.IndexOf("[h]") >= 0 || fmtStr.IndexOf("[hh]") >= 0) - { - fmtStr = fmtStr.Replace("[h]", ((int)(xlDate * 24)).ToString("d")); - fmtStr = fmtStr.Replace("[hh]", ((int)(xlDate * 24)).ToString("d2")); - xlDate = (xlDate * 24 - (int)(xlDate * 24)) / 24.0; - } - if (fmtStr.IndexOf("[m]") >= 0 || fmtStr.IndexOf("[mm]") >= 0) - { - fmtStr = fmtStr.Replace("[m]", ((int)(xlDate * 1440)).ToString("d")); - fmtStr = fmtStr.Replace("[mm]", ((int)(xlDate * 1440)).ToString("d2")); - xlDate = (xlDate * 1440 - (int)(xlDate * 1440)) / 1440.0; - } - if (fmtStr.IndexOf("[s]") >= 0 || fmtStr.IndexOf("[ss]") >= 0) - { - fmtStr = fmtStr.Replace("[s]", ((int)(xlDate * 86400)).ToString("d")); - fmtStr = fmtStr.Replace("[ss]", ((int)(xlDate * 86400)).ToString("d2")); - xlDate = (xlDate * 86400 - (int)(xlDate * 86400)) / 86400.0; - } - if (fmtStr.IndexOf("[f]") >= 0) - fmtStr = fmtStr.Replace("[f]", ((int)(xlDate * 864000)).ToString("d")); - if (fmtStr.IndexOf("[ff]") >= 0) - fmtStr = fmtStr.Replace("[ff]", ((int)(xlDate * 8640000)).ToString("d")); - if (fmtStr.IndexOf("[fff]") >= 0) - fmtStr = fmtStr.Replace("[fff]", ((int)(xlDate * 86400000)).ToString("d")); - if (fmtStr.IndexOf("[ffff]") >= 0) - fmtStr = fmtStr.Replace("[ffff]", ((int)(xlDate * 864000000)).ToString("d")); - if (fmtStr.IndexOf("[fffff]") >= 0) - fmtStr = fmtStr.Replace("[fffff]", ((int)(xlDate * 8640000000)).ToString("d")); - - //DateTime dt = XLDateToDateTime( xlDate ); - if (year > 9999) - year = 9999; - DateTime dt = new DateTime(year, month, day, hour, minute, second, millisecond); - return dt.ToString(fmtStr); - } - - /* - /// - /// Format this XDate value using the specified format string - /// - /// - /// The formatting string to be used for the date. The following formatting elements - /// will be replaced with the corresponding date values: - /// - /// - /// Variable - /// Description - /// - /// &mmmmmonth name (e.g., January) - /// &mmmmonth abbreviation (e.g., Apr) - /// &mmpadded month number (e.g. 04) - /// &mnon-padded month number (e.g., 4) - /// &ddpadded day number (e.g., 09) - /// &dnon-padded day number (e.g., 9) - /// &yyyy4 digit year number (e.g., 1995) - /// &yytwo digit year number (e.g., 95) - /// &hhpadded 24 hour time value (e.g., 08) - /// &hnon-padded 12 hour time value (e.g., 8) - /// &nnpadded minute value (e.g, 05) - /// &nnon-padded minute value (e.g., 5) - /// &sspadded second value (e.g., 03) - /// &snon-padded second value (e.g., 3) - /// &a"am" or "pm" - /// &wwwwday of week (e.g., Wednesday) - /// &wwwday of week abbreviation (e.g., Wed) - /// - /// - /// - /// "&wwww, &mmmm &dd, &yyyy &h:&nn &a" ==> "Sunday, February 12, 1956 4:23 pm" - /// "&dd-&mmm-&yy" ==> 12-Feb-56 - /// - /// A string representation of the date - public string ToString( string fmtStr ) - { - return ToString( this.xlDate, fmtStr ); - } - - /// - /// Format the specified XL Date value using the specified format string - /// - /// - /// The XL date value to be formatted in floating point double format. - /// - /// - /// The formatting string to be used for the date. The following formatting elements - /// will be replaced with the corresponding date values: - /// - /// - /// Variable - /// Description - /// - /// &mmmmmonth name (e.g., January) - /// &mmmmonth abbreviation (e.g., Apr) - /// &mmpadded month number (e.g. 04) - /// &mnon-padded month number (e.g., 4) - /// &ddpadded day number (e.g., 09) - /// &dnon-padded day number (e.g., 9) - /// &yyyy4 digit year number (e.g., 1995) - /// &yytwo digit year number (e.g., 95) - /// &hhpadded 24 hour time value (e.g., 08) - /// &hnon-padded 12 hour time value (e.g., 8) - /// &nnpadded minute value (e.g, 05) - /// &nnon-padded minute value (e.g., 5) - /// &sspadded second value (e.g., 03) - /// &snon-padded second value (e.g., 3) - /// &a"am" or "pm" - /// &wwwwday of week (e.g., Wednesday) - /// &wwwday of week abbreviation (e.g., Wed) - /// - /// - /// - /// "&wwww, &mmmm &dd, &yyyy &h:&nn &a" ==> "Sunday, February 12, 1956 4:23 pm" - /// "&dd-&mmm-&yy" ==> 12-Feb-56 - /// - /// A string representation of the date - public static string ToString( double xlDate, string fmtStr ) - { - string[] longMonth = { "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December" }; - string[] shortMonth = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; - string[] longDoW = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", - "Friday", "Saturday" }; - string[] shortDoW = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; - - int year, month, day, hour, minute, second; - XLDateToCalendarDate( xlDate, out year, out month, out day, out hour, out minute, out second ); - - string resultStr = fmtStr.Replace( "&mmmm", longMonth[ month - 1 ] ); - resultStr = resultStr.Replace( "&mmm", shortMonth[ month - 1 ] ); - resultStr = resultStr.Replace( "&mm", month.ToString( "d2" ) ); - resultStr = resultStr.Replace( "&m", month.ToString( "d" ) ); - resultStr = resultStr.Replace( "&yyyy", year.ToString( "d" ) ); - resultStr = resultStr.Replace( "&yy", (year%100).ToString( "d2" ) ); - resultStr = resultStr.Replace( "&dd", day.ToString( "d2" ) ); - resultStr = resultStr.Replace( "&d", day.ToString( "d" ) ); - resultStr = resultStr.Replace( "&hh", hour.ToString( "d2" ) ); - resultStr = resultStr.Replace( "&h", (((hour+11)%12)+1).ToString( "d" ) ); - resultStr = resultStr.Replace( "&nn", minute.ToString( "d2" ) ); - resultStr = resultStr.Replace( "&n", minute.ToString( "d" ) ); - resultStr = resultStr.Replace( "&ss", second.ToString( "d2" ) ); - resultStr = resultStr.Replace( "&s", second.ToString( "d" ) ); - resultStr = resultStr.Replace( "&a", (hour>=12) ? "pm" : "am" ); - resultStr = resultStr.Replace( "&wwww", longDoW[ XLDateToDayOfWeek( xlDate ) ] ); - resultStr = resultStr.Replace( "&www", shortDoW[ XLDateToDayOfWeek( xlDate ) ] ); - - - return resultStr; - } - */ - - #endregion - } -} diff --git a/core/Boagaphish/Genetic/GeneHeader.cs b/core/Boagaphish/Genetic/GeneHeader.cs deleted file mode 100644 index 23e9300..0000000 --- a/core/Boagaphish/Genetic/GeneHeader.cs +++ /dev/null @@ -1,14 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Genetic -{ - public enum GeneHeader - { - Embryo, - Duplicated, - Mutations, - Cut, - Gender - } -} diff --git a/core/Boagaphish/Genetic/GeneticAlgorithm.cs b/core/Boagaphish/Genetic/GeneticAlgorithm.cs deleted file mode 100644 index 76f917d..0000000 --- a/core/Boagaphish/Genetic/GeneticAlgorithm.cs +++ /dev/null @@ -1,264 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; -using System.IO; - -namespace Boagaphish.Genetic -{ - public class GeneticAlgorithm - { - private double _totalFitness; - private ArrayList _thisGeneration; - private ArrayList _nextGeneration; - private ArrayList _fitnessTable; - private static readonly Random Random = new Random(); - private static GeneticAlgorithmFunction _getFitness; - - public GeneticAlgorithmFunction FitnessFunction - { - get - { - return _getFitness; - } - set - { - _getFitness = value; - } - } - - public int PopulationSize - { - get; - set; - } - - public int Generations - { - get; - set; - } - - public int GenomeSize - { - get; - set; - } - - public double CrossoverRate - { - get; - set; - } - - public double MutationRate - { - get; - set; - } - - public string FitnessFile - { - get; - set; - } - - public bool Elitism - { - get; - set; - } - - public GeneticAlgorithm() - { - InitialValues(); - MutationRate = 0.05; - CrossoverRate = 0.8; - PopulationSize = 100; - Generations = 2000; - FitnessFile = ""; - } - - public GeneticAlgorithm(double crossoverRate, double mutationRate, int populationSize, int generationSize, int genomeSize) - { - InitialValues(); - MutationRate = mutationRate; - CrossoverRate = crossoverRate; - PopulationSize = populationSize; - Generations = generationSize; - GenomeSize = genomeSize; - FitnessFile = ""; - } - - public GeneticAlgorithm(int genomeSize) - { - InitialValues(); - GenomeSize = genomeSize; - } - - public void InitialValues() - { - Elitism = false; - } - - public void Go() - { - if (_getFitness == null) - { - throw new ArgumentNullException("Need to supply fitness function."); - } - if (GenomeSize == 0) - { - throw new IndexOutOfRangeException("Genome size not set."); - } - _fitnessTable = new ArrayList(); - _thisGeneration = new ArrayList(Generations); - _nextGeneration = new ArrayList(Generations); - Genome.MutationRate = MutationRate; - CreateGenomes(); - RankPopulation(); - StreamWriter streamWriter = null; - bool flag = false; - if (FitnessFile != "") - { - flag = true; - streamWriter = new StreamWriter(FitnessFile); - } - for (int i = 0; i < Generations; i++) - { - CreateNextGeneration(); - RankPopulation(); - if (flag && streamWriter != null) - { - double fitness = ((Genome)_thisGeneration[PopulationSize - 1]).Fitness; - streamWriter.WriteLine("{0},{1}", i, fitness); - } - } - if (streamWriter != null) - { - streamWriter.Close(); - } - } - - private int RouletteSelection() - { - double num = Random.NextDouble() * _totalFitness; - int num2 = -1; - int num3 = 0; - int num4 = PopulationSize - 1; - int num5 = (num4 - num3) / 2; - while (num2 == -1 && num3 <= num4) - { - if (num < (double)_fitnessTable[num5]) - { - num4 = num5; - } - else if (num > (double)_fitnessTable[num5]) - { - num3 = num5; - } - num5 = (num3 + num4) / 2; - if (num4 - num3 == 1) - { - num2 = num4; - } - } - return num2; - } - - private void RankPopulation() - { - _totalFitness = 0.0; - for (int i = 0; i < PopulationSize; i++) - { - Genome genome = (Genome)_thisGeneration[i]; - genome.Fitness = FitnessFunction(genome.Genes()); - _totalFitness += genome.Fitness; - } - _thisGeneration.Sort(new GenomeComparer()); - double num = 0.0; - _fitnessTable.Clear(); - for (int j = 0; j < PopulationSize; j++) - { - num += ((Genome)_thisGeneration[j]).Fitness; - _fitnessTable.Add(num); - } - } - - private void CreateGenomes() - { - for (int i = 0; i < PopulationSize; i++) - { - Genome value = new Genome(GenomeSize); - _thisGeneration.Add(value); - } - } - - private void CreateNextGeneration() - { - _nextGeneration.Clear(); - Genome genome = null; - if (Elitism) - { - genome = (Genome)_thisGeneration[PopulationSize - 1]; - } - for (int i = 0; i < PopulationSize; i += 2) - { - int index = RouletteSelection(); - int index2 = RouletteSelection(); - Genome genome2 = (Genome)_thisGeneration[index]; - Genome genome3 = (Genome)_thisGeneration[index2]; - Genome genome4; - Genome genome5; - if (Random.NextDouble() < CrossoverRate) - { - genome2.Crossover(ref genome3, out genome4, out genome5); - } - else - { - genome4 = genome2; - genome5 = genome3; - } - genome4.Mutate(); - genome5.Mutate(); - _nextGeneration.Add(genome4); - _nextGeneration.Add(genome5); - } - if (Elitism && genome != null) - { - _nextGeneration[0] = genome; - } - _thisGeneration.Clear(); - for (int j = 0; j < PopulationSize; j++) - { - _thisGeneration.Add(_nextGeneration[j]); - } - } - - public void GetBest(out double[] values, out double fitness) - { - Genome genome = (Genome)_thisGeneration[PopulationSize - 1]; - values = new double[genome.Length]; - genome.GetValues(ref values); - fitness = genome.Fitness; - } - - public void GetWorst(out double[] values, out double fitness) - { - GetNthGenome(0, out values, out fitness); - } - - public void GetNthGenome(int n, out double[] values, out double fitness) - { - if (n < 0 || n > PopulationSize - 1) - { - throw new ArgumentOutOfRangeException("n too large, or too small"); - } - Genome genome = (Genome)_thisGeneration[n]; - values = new double[genome.Length]; - genome.GetValues(ref values); - fitness = genome.Fitness; - } - } -} diff --git a/core/Boagaphish/Genetic/GeneticAlgorithmFunction.cs b/core/Boagaphish/Genetic/GeneticAlgorithmFunction.cs deleted file mode 100644 index d65030b..0000000 --- a/core/Boagaphish/Genetic/GeneticAlgorithmFunction.cs +++ /dev/null @@ -1,7 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Genetic -{ - public delegate double GeneticAlgorithmFunction(double[] values); -} diff --git a/core/Boagaphish/Genetic/Genome.cs b/core/Boagaphish/Genetic/Genome.cs deleted file mode 100644 index 04d5877..0000000 --- a/core/Boagaphish/Genetic/Genome.cs +++ /dev/null @@ -1,124 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Globalization; - -namespace Boagaphish.Genetic -{ - public class Genome - { - private static readonly Random Random = new Random(); - private double[] genes; - - public double Fitness - { - get; - set; - } - - public static double MutationRate - { - get; - set; - } - - public int Length - { - get; - private set; - } - - public Genome() - { - } - - public Genome(int length) - { - Length = length; - genes = new double[length]; - CreateGenes(); - } - - public Genome(int length, bool createGenes) - { - Length = length; - genes = new double[length]; - if (createGenes) - { - CreateGenes(); - } - } - - public Genome(ref double[] genes) - { - Length = genes.GetLength(0); - this.genes = new double[Length]; - for (int i = 0; i < Length; i++) - { - this.genes[i] = genes[i]; - } - } - - private void CreateGenes() - { - DateTime utcNow = DateTime.UtcNow; - for (int i = 0; i < Length; i++) - { - genes[i] = Random.NextDouble(); - } - } - - public void Crossover(ref Genome genome2, out Genome child1, out Genome child2) - { - int num = (int)(Random.NextDouble() * (double)Length); - child1 = new Genome(Length, false); - child2 = new Genome(Length, false); - for (int i = 0; i < Length; i++) - { - if (i < num) - { - child1.genes[i] = genes[i]; - child2.genes[i] = genome2.genes[i]; - } - else - { - child1.genes[i] = genome2.genes[i]; - child2.genes[i] = genes[i]; - } - } - } - - public void Mutate() - { - for (int i = 0; i < Length; i++) - { - if (Random.NextDouble() < MutationRate) - { - genes[i] = (genes[i] + Random.NextDouble()) / 2.0; - } - } - } - - public double[] Genes() - { - return genes; - } - - public void Output() - { - for (int i = 0; i < Length; i++) - { - Logging.WriteLog(genes[i].ToString(CultureInfo.InvariantCulture), Logging.LogType.Information, Logging.LogCaller.DeepLearning); - } - } - - public void GetValues(ref double[] values) - { - for (int i = 0; i < Length; i++) - { - values[i] = genes[i]; - } - } - } -} diff --git a/core/Boagaphish/Genetic/GenomeComparer.cs b/core/Boagaphish/Genetic/GenomeComparer.cs deleted file mode 100644 index 2cae1f4..0000000 --- a/core/Boagaphish/Genetic/GenomeComparer.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; - -namespace Boagaphish.Genetic -{ - public sealed class GenomeComparer : IComparer - { - private const double Epsilon = 1E-06; - - public int Compare(object x, object y) - { - if (!(x is Genome) || !(y is Genome)) - { - throw new ArgumentException("Not of type Genome."); - } - if (((Genome)x).Fitness > ((Genome)y).Fitness) - { - return 1; - } - if (Math.Abs(((Genome)x).Fitness - ((Genome)y).Fitness) < Epsilon) - { - return 0; - } - return -1; - } - } -} diff --git a/core/Boagaphish/Logging.cs b/core/Boagaphish/Logging.cs deleted file mode 100644 index c48d6d7..0000000 --- a/core/Boagaphish/Logging.cs +++ /dev/null @@ -1,181 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.IO; -using Boagaphish.Core.Variables; - -namespace Boagaphish -{ - /// - /// The class which performs logging for the library. Originated in MACOS 9.0.4 under CodeWarrior. - /// - public static class Logging - { - /// - /// The file path for executing assemblies. - /// - public static string FilePath = Environment.CurrentDirectory; - /// - /// The type of log to write. - /// - [Flags] - public enum LogType { Information, Error, Statistics, Warning }; - /// - /// The classes within the interpreter calling the log. - /// - public enum LogCaller { Accounts, AgentCore, AgentGui, AgentVoice, AlgorithmicComputation, Automat, DeepLearning, Genome, Orders, OrderInformation, Positions, Rates, TestFramework, Trades, Transactions, TrendGui } - /// - /// The last message passed to logging. - /// - public static string LastMessage = ""; - /// - /// The delegate for returning the last log message to the calling application. - /// - public delegate void LoggingDelegate(); - - /// - /// Occurs when [returned to console] is called. - /// - public static event LoggingDelegate ReturnedToConsole; - /// - /// Records an event relevant to the algorithm. - /// - /// The data point itself. - /// The event data. - /// The interval period. - /// The interval nomen, e.g., s, m, h. - public static void RecordEvent(DataPoints.AccountDataPoint dataPoint, double eventData, int intervalPeriod, string intervalNomen) - { - var stream = new StreamWriter(FilePath + @"\logs\monitor.txt", true); - switch (dataPoint) - { - case DataPoints.AccountDataPoint.Balance: - stream.WriteLine(DateTime.Now + " - Balance datapoint value is: [" + eventData + "] on an interval of " + intervalPeriod + " " + intervalNomen + "."); - break; - case DataPoints.AccountDataPoint.MarginUsed: - stream.WriteLine(DateTime.Now + " - Margin used datapoint value is: [" + eventData + "] on an interval of " + intervalPeriod + " " + intervalNomen + "."); - break; - case DataPoints.AccountDataPoint.Unrealized: - stream.WriteLine(DateTime.Now + " - Unrealized datapoint value is: [" + eventData + "] on an interval of " + intervalPeriod + " " + intervalNomen + "."); - break; - } - stream.Close(); - } - /// - /// Logs a message sent from the calling application to a file. - /// - /// The message to log. Space between the message and log type enumeration provided. - /// Type of the log. - /// The class creating the log entry. - public static void WriteLog(string message, LogType logType, LogCaller caller) - { - LastMessage = message; - StreamWriter stream = new StreamWriter(FilePath + @"\logs\logfile.txt", true); - switch (logType) - { - case LogType.Error: - stream.WriteLine(DateTime.Now + " - " + " ERROR " + " - " + message + " from " + caller + "."); - break; - case LogType.Warning: - stream.WriteLine(DateTime.Now + " - " + " WARNING " + " - " + message + " from " + caller + "."); - break; - case LogType.Information: - stream.WriteLine(DateTime.Now + " - " + " INFO " + message); - break; - case LogType.Statistics: - stream.WriteLine(DateTime.Now + " - " + message + "."); - break; - } - stream.Close(); - if (!Equals(null, ReturnedToConsole)) - { - ReturnedToConsole(); - } - } - /// - /// Writes the log. - /// - /// The message. Space between the message and log type enumeration provided. - /// Type of the log. - /// The class creating the log entry. - /// The method creating the log entry. - public static void WriteLog(string message, LogType logType, LogCaller caller, string method) - { - LastMessage = message; - StreamWriter stream = new StreamWriter(FilePath + @"\logs\logfile.txt", true); - switch (logType) - { - case LogType.Error: - stream.WriteLine(DateTime.Now + " - " + " ERROR " + " - " + message + " from class " + caller + " using method " + method + "."); - break; - case LogType.Warning: - stream.WriteLine(DateTime.Now + " - " + " WARNING " + " - " + message + " from class " + caller + " using method " + method + "."); - break; - case LogType.Information: - stream.WriteLine(DateTime.Now + " - " + message + " called from the class " + caller + " using method " + method + "."); - break; - case LogType.Statistics: - stream.WriteLine(DateTime.Now + " - " + message + "."); - break; - } - stream.Close(); - if (!Equals(null, ReturnedToConsole)) - { - ReturnedToConsole(); - } - } - /// - /// Writes a debug log with object parameters. - /// - /// The objects. - public static void Debug(params object[] objects) - { - StreamWriter stream = new StreamWriter(FilePath + @"\logs\logfile.txt", true); - foreach (object obj in objects) - { - stream.WriteLine(obj); - } - stream.WriteLine("--"); - stream.Close(); - } - - public static class ActiveTime - { - public static string LogTime(double? time, bool read) - { - string path = FilePath + "\\logs\\timelogfile.txt"; - switch (read) - { - case true: - return File.ReadAllText(path); - case false: - { - StreamWriter streamWriter = new StreamWriter(path, false); - streamWriter.WriteLine(time); - streamWriter.Close(); - streamWriter.Dispose(); - return ""; - } - } - } - - public static string LogTime(double? time, string timeLogFilePath, bool read) - { - switch (read) - { - case true: - return File.ReadAllText(timeLogFilePath); - case false: - { - StreamWriter streamWriter = new StreamWriter(timeLogFilePath, false); - streamWriter.WriteLine(time); - streamWriter.Close(); - streamWriter.Dispose(); - return ""; - } - } - } - } - } -} diff --git a/core/Boagaphish/Machines/ReducedBoltzmann.cs b/core/Boagaphish/Machines/ReducedBoltzmann.cs deleted file mode 100644 index ee4658a..0000000 --- a/core/Boagaphish/Machines/ReducedBoltzmann.cs +++ /dev/null @@ -1,306 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.Machines -{ - /// - /// An example of a reduced Boltzmann machine. - /// - public class ReducedBoltzmann - { - private readonly Random _rnd; - - public int NumberVisible { get; set; } - public int NumberHidden { get; set; } - - public int[] VisibleNodeValues { get; set; } // visible node values (0, 1) - public double[] VisualProbs; - public double[] VisualBiases; - - public int[] HiddenValues; - public double[] HiddenProbs; - public double[] HiddenBiases; - - public double[][] VhWeights; - - public ReducedBoltzmann(int numVisible, int numHidden) - { - _rnd = new Random(0); - - NumberVisible = numVisible; - NumberHidden = numHidden; - - // allocate arrays & the weights matrix - VisibleNodeValues = new int[numVisible]; - VisualProbs = new double[numVisible]; - VisualBiases = new double[numVisible]; - - HiddenValues = new int[numHidden]; - HiddenProbs = new double[numHidden]; - HiddenBiases = new double[numHidden]; - - VhWeights = new double[numVisible][]; // visible-to-hidden - for (int i = 0; i < numVisible; ++i) - VhWeights[i] = new double[numHidden]; - - // small random values for initial weights & biases - const double low = -0.40; - const double high = +0.40; - for (int i = 0; i < numVisible; ++i) - for (int j = 0; j < numHidden; ++j) - VhWeights[i][j] = (high - low) * _rnd.NextDouble() + low; - - for (int i = 0; i < numVisible; ++i) - VisualBiases[i] = (high - low) * _rnd.NextDouble() + low; - - for (int i = 0; i < numHidden; ++i) - HiddenBiases[i] = (high - low) * _rnd.NextDouble() + low; - } - - //public void SetWeights(double[] wts) // for debugging - //{ - // // order: weights, vBiases, hBiases - // int idx = 0; - // for (int i = 0; i < numVisible; ++i) - // for (int j = 0; j < numHidden; ++j) - // vhWeights[i][j] = wts[idx++]; - // for (int i = 0; i < numVisible; ++i) - // visBiases[i] = wts[idx++]; - // for (int j = 0; j < numHidden; ++j) - // hidBiases[j] = wts[idx++]; - //} - - //public double[] GetWeights() // for debugging - //{ - // int numWts = numVisible * numHidden + numVisible + numHidden; - // double[] result = new double[numWts]; - // int idx = 0; - // for (int i = 0; i < numVisible; ++i) - // for (int j = 0; j < numHidden; ++j) - // result[idx++] = vhWeights[i][j]; - // for (int i = 0; i < numVisible; ++i) - // result[idx++] = visBiases[i]; - // for (int j = 0; j < numHidden; ++j) - // result[idx++] = hidBiases[j]; - // return result; - //} - - public void Train(int[][] trainData, double learnRate, int maxEpochs) - { - int[] indices = new int[trainData.Length]; - for (int i = 0; i < indices.Length; ++i) - indices[i] = i; - - int epoch = 0; - while (epoch < maxEpochs) - { - Shuffle(indices); - - for (int idx = 0; idx < indices.Length; ++idx) // each data item - { - int i = indices[idx]; // i points to curr train data - - // copy visible values from train data into Machine - for (int j = 0; j < NumberVisible; ++j) - VisibleNodeValues[j] = trainData[i][j]; - - // compute hidden node values ('h' in Wikipedia) - for (int h = 0; h < NumberHidden; ++h) - { - double sum = 0.0; - for (int v = 0; v < NumberVisible; ++v) - sum += VisibleNodeValues[v] * VhWeights[v][h]; - - sum += HiddenBiases[h]; // add the hidden bias - HiddenProbs[h] = LogSign(sum); // compute prob of h activation - double pr = _rnd.NextDouble(); // determine 0/1 h node value - if (HiddenProbs[h] > pr) - HiddenValues[h] = 1; - else - HiddenValues[h] = 0; - } - - // compute positive gradient = outer product of v & h - int[][] posGrad = OuterProduct(VisibleNodeValues, HiddenValues); - - // reconstruct visual Nodes as v' - int[] vPrime = new int[NumberVisible]; // v' in Wikipedia - for (int v = 0; v < NumberVisible; ++v) - { - double sum = 0.0; - for (int h = 0; h < NumberHidden; ++h) - sum += HiddenValues[h] * VhWeights[v][h]; - sum += VisualBiases[v]; // add visible bias - double probActiv = LogSign(sum); - double pr = _rnd.NextDouble(); - if (probActiv > pr) - vPrime[v] = 1; - else - vPrime[v] = 0; - } - - // compute new hidden Nodes as h', using v' - int[] hPrime = new int[NumberHidden]; - for (int h = 0; h < NumberHidden; ++h) - { - double sum = 0.0; - for (int v = 0; v < NumberVisible; ++v) - sum += vPrime[v] * VhWeights[v][h]; - sum += HiddenBiases[h]; // add the hidden bias - double probActiv = LogSign(sum); // apply activation - double pr = _rnd.NextDouble(); // determine 0/1 node value - if (probActiv > pr) - hPrime[h] = 1; - else - hPrime[h] = 0; - } - - // compute negative grad using v' and h' - int[][] negGrad = OuterProduct(vPrime, hPrime); - - // update weights - for (int row = 0; row < NumberVisible; ++row) - for (int col = 0; col < NumberHidden; ++col) - VhWeights[row][col] += learnRate * (posGrad[row][col] - negGrad[row][col]); - - // update visBiases - for (int v = 0; v < NumberVisible; ++v) - VisualBiases[v] += learnRate * (VisibleNodeValues[v] - vPrime[v]); - // update hidBiases - for (int h = 0; h < NumberHidden; ++h) - HiddenBiases[h] += learnRate * (HiddenValues[h] - hPrime[h]); - - } // for-each train data - - ++epoch; - } - } - - public static int[][] OuterProduct(int[] visValues, int[] hidValues) - { - int rows = visValues.Length; - int cols = hidValues.Length; - int[][] result = new int[rows][]; - for (int i = 0; i < rows; ++i) - result[i] = new int[cols]; - - for (int i = 0; i < rows; ++i) - for (int j = 0; j < cols; ++j) - result[i][j] = visValues[i] * hidValues[j]; - - return result; - } - - public double LogSign(double x) - { - if (x < -20.0) return 0.0000000001; - if (x > 20.0) return 0.9999999999; - return 1.0 / (1.0 + Math.Exp(-x)); - } - - public void Shuffle(int[] indices) - { - for (int i = 0; i < indices.Length; ++i) - { - int ri = _rnd.Next(i, indices.Length); - int tmp = indices[i]; - indices[i] = indices[ri]; - indices[ri] = tmp; - } - } - - public int[] HiddenFromVisual(int[] visibles) - { - int[] result = new int[NumberHidden]; - - for (int h = 0; h < NumberHidden; ++h) - { - double sum = 0.0; - for (int v = 0; v < NumberVisible; ++v) - sum += visibles[v] * VhWeights[v][h]; - - sum += HiddenBiases[h]; // add the hidden bias - double probActiv = LogSign(sum); // compute prob of h activation - // Console.WriteLine("Hidden [" + h + "] activation probability = " + probActiv.ToString("F4")); - double pr = _rnd.NextDouble(); // determine 0/1 h node value - if (probActiv > pr) - result[h] = 1; - else - result[h] = 0; - } - return result; - } - - public int[] VisibleFromHidden(int[] hiddens) - { - int[] result = new int[NumberVisible]; - - for (int v = 0; v < NumberVisible; ++v) - { - double sum = 0.0; - for (int h = 0; h < NumberHidden; ++h) - sum += hiddens[h] * VhWeights[v][h]; - sum += VisualBiases[v]; // add visible bias - double probActiv = LogSign(sum); - // Console.WriteLine("Visible [" + v + "] activation probability = " + probActiv.ToString("F4")); - double pr = _rnd.NextDouble(); - if (probActiv > pr) - result[v] = 1; - else - result[v] = 0; - } - return result; - } - - public void Dump(bool showValues, bool showWeights, bool showBiases) - { - if (showValues) - { - for (int i = 0; i < NumberVisible; ++i) - { - Console.Write("visible node [" + i + "] value = " + VisibleNodeValues[i]); - Console.WriteLine(" prob = " + VisualProbs[i].ToString("F4")); - } - Console.WriteLine(""); - - for (int j = 0; j < NumberHidden; ++j) - { - Console.Write("hidden node [" + j + "] value = " + HiddenValues[j]); - Console.WriteLine(" prob = " + HiddenProbs[j].ToString("F4")); - } - Console.WriteLine(""); - } - - if (showWeights) - { - for (int i = 0; i < NumberVisible; ++i) - { - for (int j = 0; j < NumberHidden; ++j) - { - double x = VhWeights[i][j]; - if (x >= 0.0) - Console.Write(" "); - Console.Write(VhWeights[i][j].ToString("F4") + " "); - } - Console.WriteLine(""); - } - Console.WriteLine(""); - } - - if (showBiases) - { - for (int i = 0; i < NumberVisible; ++i) - Console.WriteLine("visible bias [" + i + "] value = " + - VisualBiases[i].ToString("F4")); - Console.WriteLine(""); - - for (int j = 0; j < NumberHidden; ++j) - Console.WriteLine("hidden bias [" + j + "] value = " + - HiddenBiases[j].ToString("F4")); - Console.WriteLine(""); - } - } - } -} diff --git a/core/Boagaphish/Numeric/CellVector.cs b/core/Boagaphish/Numeric/CellVector.cs deleted file mode 100644 index 2c07eed..0000000 --- a/core/Boagaphish/Numeric/CellVector.cs +++ /dev/null @@ -1,12 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Runtime.InteropServices; - -namespace Boagaphish.Numeric -{ - [StructLayout(LayoutKind.Sequential, Size = 1)] - public struct CellVector - { - } -} diff --git a/core/Boagaphish/Numeric/DoubleRange.cs b/core/Boagaphish/Numeric/DoubleRange.cs deleted file mode 100644 index 9204d8c..0000000 --- a/core/Boagaphish/Numeric/DoubleRange.cs +++ /dev/null @@ -1,72 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Numeric -{ - /// - /// Represents a double range with minimum and maximum values. - /// - public class DoubleRange - { - private double _min, _max; - /// - /// Minimum value - /// - public double Min { get { return _min; } set { _min = value; } } - /// - /// Maximum value - /// - public double Max { get { return _max; } set { _max = value; } } - /// - /// Length of the range (deffirence between maximum and minimum values) - /// - /// The length. - public double Length { get { return _max - _min; } } - /// - /// Initializes a new instance of the class - /// - /// Minimum value of the range - /// Maximum value of the range - public DoubleRange(double min, double max) - { - _min = min; - _max = max; - } - /// - /// Check if the specified value is inside this range - /// - /// Value to check - /// - /// True if the specified value is inside this range or - /// false otherwise. - /// - public bool IsInside(double x) - { - return ((x >= _min) && (x <= _min)); - } - /// - /// Check if the specified range is inside this range - /// - /// Range to check - /// - /// True if the specified range is inside this range or - /// false otherwise. - /// - public bool IsInside(DoubleRange range) - { - return ((IsInside(range._min)) && (IsInside(range._max))); - } - /// - /// Check if the specified range overlaps with this range - /// - /// Range to check for overlapping - /// - /// True if the specified range overlaps with this range or - /// false otherwise. - /// - public bool IsOverlapping(DoubleRange range) - { - return ((IsInside(range._min)) || (IsInside(range._max))); - } - } -} diff --git a/core/Boagaphish/Numeric/IntRange.cs b/core/Boagaphish/Numeric/IntRange.cs deleted file mode 100644 index 8ad29d1..0000000 --- a/core/Boagaphish/Numeric/IntRange.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Numeric -{ - /// - /// Represents an integer range with minimum and maximum values. - /// - public class IntRange - { - /// - /// the minimum value of the range. - /// - public int Min { get; set; } - /// - /// The maximum value of the range. - /// - public int Max { get; set; } - /// - /// The length of the range. - /// - public int Length - { - get { return Max - Min; } - } - /// - /// Initializes a new instance of the class - /// - /// The minimum value of the range - /// The maximum value of the range - public IntRange(int min, int max) - { - Min = min; - Max = max; - } - /// - /// Check if the specified value is inside this range - /// - /// Value to check - /// - /// True if the specified value is inside this range or - /// false otherwise. - /// - public bool IsInside(int x) - { - return ((x >= Min) && (x <= Min)); - } - /// - /// Check if the specified range is inside this range - /// - /// Range to check - /// - /// True if the specified range is inside this range or - /// false otherwise. - /// - public bool IsInside(IntRange range) - { - return ((IsInside(range.Min)) && (IsInside(range.Max))); - } - /// - /// Check if the specified range overlaps with this range - /// - /// Range to check for overlapping - /// - /// True if the specified range overlaps with this range or - /// false otherwise. - /// - public bool IsOverlapping(IntRange range) - { - return ((IsInside(range.Min)) || (IsInside(range.Max))); - } - } -} diff --git a/core/Boagaphish/Numeric/PolishExpression.cs b/core/Boagaphish/Numeric/PolishExpression.cs deleted file mode 100644 index 9281c30..0000000 --- a/core/Boagaphish/Numeric/PolishExpression.cs +++ /dev/null @@ -1,131 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; - -namespace Boagaphish.Numeric -{ - /// - /// Evaluator of expressions written in polish notation (Quick and dirty implementation of polish expression evaluator). - /// - /// The class evaluates expressions writen in postfix polish notation. - /// The list of supported functuins is: - /// - /// Arithmetic functions: +, -, *, /; - /// sin - sine; - /// cos - cosine; - /// ln - natural logarithm; - /// exp - exponent; - /// sqrt - square root. - /// - /// Arguments for these functions could be as usual constants, written as numbers, as variables, - /// writen as $<var_number> ($2, for example). The variable number is zero based index - /// of variables array. - /// - /// The following sample illustrates the usage of PolishExpression class: - /// - /// // expression written in polish notation - /// string expression = "2 $0 / 3 $1 * +"; - /// // variables for the expression - /// double[] vars = new double[] { 3, 4 }; - /// // expression evaluation - /// double result = PolishExpression.Evaluate( expression, vars ); - /// - /// - public class PolishExpression - { - /// - /// Constructor (the class should not be instantiated at this moment) - /// - private PolishExpression() { } - /// - /// Evaluates specified expression - /// - /// Expression written in postfix polish notation - /// Variables for the expression - /// Evaluated value of the expression - public static double Evaluate(string expression, double[] variables) - { - // split expression to separate tokens, which represent functions ans variables - string[] tokens = expression.Trim().Split(' '); - // arguments stack - Stack arguments = new Stack(); - - // walk through all tokens - foreach (string token in tokens) - { - // check for token type - if (char.IsDigit(token[0])) - { - // the token in numeric argument - arguments.Push(double.Parse(token)); - } - else if (token[0] == '$') - { - // the token is variable - arguments.Push(variables[int.Parse(token.Substring(1))]); - } - else - { - // each function has at least one argument, so let's get the top one - // argument from stack - double v = (double)arguments.Pop(); - - // check for function - switch (token) - { - case "+": // addition - arguments.Push((double)arguments.Pop() + v); - break; - - case "-": // subtraction - arguments.Push((double)arguments.Pop() - v); - break; - - case "*": // multiplication - arguments.Push((double)arguments.Pop() * v); - break; - - case "/": // division - arguments.Push((double)arguments.Pop() / v); - break; - - case "sin": // sine - arguments.Push(Math.Sin(v)); - break; - - case "cos": // cosine - arguments.Push(Math.Cos(v)); - break; - - case "ln": // natural logarithm - arguments.Push(Math.Log(v)); - break; - - case "exp": // exponent - arguments.Push(Math.Exp(v)); - break; - - case "sqrt": // square root - arguments.Push(Math.Sqrt(v)); - break; - - default: - // throw exception informing about undefined function - throw new ArgumentException("Undefined function: " + token); - } - } - } - - // check stack size - if (arguments.Count != 1) - { - throw new ArgumentException("Incorrect expression"); - } - - // return the only value from stack - return (double)arguments.Pop(); - } - } -} diff --git a/core/Boagaphish/Numeric/TransferFunctions.cs b/core/Boagaphish/Numeric/TransferFunctions.cs deleted file mode 100644 index 31eb33b..0000000 --- a/core/Boagaphish/Numeric/TransferFunctions.cs +++ /dev/null @@ -1,136 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Boagaphish.Numeric -{ - public enum TransferFunction - { - None, - BipolarSigmoid, - Gaussian, - Linear, - NormalizedExponent, - RationalSigmoid, - Sigmoid, - VanderPol - } - public static class TransferFunctions - { - public static double Alpha { get; set; } - public static double Mu { get; set; } - /// - /// Evaluates a specified transfer function. - /// - /// The transfer function. - /// The input. - /// Parameter for use in the van der Pol oscillator function. - /// - public static double Evaluate(TransferFunction tFunc, double input, double mu = 0.5) - { - Mu = mu; - switch (tFunc) - { - case TransferFunction.BipolarSigmoid: - return BipolarSigmoid(input); - case TransferFunction.Gaussian: - return Gaussian(input); - case TransferFunction.Linear: - return Linear(input); - case TransferFunction.RationalSigmoid: - return RationalSigmoid(input); - case TransferFunction.Sigmoid: - return Sigmoid(input); - case TransferFunction.VanderPol: - return VanderPol(input); - default: - return 0.0; - } - } - /// - /// Evaluates the derivative. - /// - /// The transfer function. - /// The input. - /// Parameter for use in the van der Pol oscillator function. - /// - public static double EvaluateDerivative(TransferFunction tFunc, double input, double mu = 0.5) - { - Mu = mu; - switch (tFunc) - { - case TransferFunction.BipolarSigmoid: - return BipolarSigmoidDerivative(input); - case TransferFunction.Gaussian: - return GaussianDerivative(input); - case TransferFunction.Linear: - return LinearDerivative(input); - case TransferFunction.RationalSigmoid: - return RationalSigmoidDerivative(input); - case TransferFunction.Sigmoid: - return SigmoidDerivative(input); - case TransferFunction.VanderPol: - return VanderPolDerivative(input); - default: - return 0.0; - } - } - // Implementation of the different functions. - static double BipolarSigmoid(double x) - { - return ((2 / (1 + Math.Exp(-Alpha * x))) - 1); - } - static double BipolarSigmoidDerivative(double x) - { - var y = BipolarSigmoid(x); - return (Alpha * (1 - y * y) / 2); - } - static double BipolarSigmoidDerivative2(double y) - { - return (Alpha * (1 - y * y) / 2); - } - static double Gaussian(double x) - { - return Math.Exp(-Math.Pow(x, 2)); - } - static double GaussianDerivative(double x) - { - return -2.0 * x * Gaussian(x); - } - static double Linear(double x) - { - return x; - } - static double LinearDerivative(double x) - { - return 1.0; - } - static double RationalSigmoid(double x) - { - return x / (1.0 + Math.Sqrt(1.0 + x * x)); - } - static double RationalSigmoidDerivative(double x) - { - var value = Math.Sqrt(1.0 + x * x); - return 1.0 / (value * (1 + value)); - } - static double Sigmoid(double x) - { - return 1.0 / (1.0 + Math.Exp(-x)); - } - static double SigmoidDerivative(double x) - { - return Sigmoid(x) * (1 - Sigmoid(x)); - } - static double VanderPol(double x) - { - return (1 / Mu) * x; - } - static double VanderPolDerivative(double x) - { - var y = VanderPol(x); - return Math.Abs(Mu * (x - (0.3333 * Math.Pow(x, 3)) - y)); - } - } -} diff --git a/core/Boagaphish/Numeric/Vector.cs b/core/Boagaphish/Numeric/Vector.cs deleted file mode 100644 index 0816485..0000000 --- a/core/Boagaphish/Numeric/Vector.cs +++ /dev/null @@ -1,147 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Drawing; - -namespace Boagaphish.Numeric -{ - public struct Vector - { - private double _x; - private double _y; - - public double X - { - get - { - return _x; - } - set - { - _x = value; - } - } - - public double Y - { - get - { - return _y; - } - set - { - _y = value; - } - } - - public double Magnitude - { - get - { - return Math.Sqrt(X * X + Y * Y); - } - } - - public Vector(double x, double y) - { - _x = x; - _y = y; - } - - public Vector(PointF pt) - { - _x = (double)pt.X; - _y = (double)pt.Y; - } - - public Vector(PointF st, PointF end) - { - _x = (double)(end.X - st.X); - _y = (double)(end.Y - st.Y); - } - - public static Vector operator +(Vector v1, Vector v2) - { - return new Vector(v1.X + v2.X, v1.Y + v2.Y); - } - - public static Vector operator -(Vector v1, Vector v2) - { - return new Vector(v1.X - v2.X, v1.Y - v2.Y); - } - - public static Vector operator -(Vector v) - { - return new Vector(0.0 - v.X, 0.0 - v.Y); - } - - public static Vector operator *(double c, Vector v) - { - return new Vector(c * v.X, c * v.Y); - } - - public static Vector operator *(Vector v, double c) - { - return new Vector(c * v.X, c * v.Y); - } - - public static Vector operator /(Vector v, double c) - { - return new Vector(v.X / c, v.Y / c); - } - - public double CrossProduct(Vector v) - { - return _x * v.Y - v.X * _y; - } - - public static double CrossProduct(Vector vector1, Vector vector2) - { - return vector1._x * vector2._y - vector1._y * vector2._x; - } - - public double DotProduct(Vector v) - { - return _x * v.X + _y * v.Y; - } - - public static bool IsClockwise(PointF pt1, PointF pt2, PointF pt3) - { - Vector vector = new Vector(pt2, pt1); - Vector v = new Vector(pt2, pt3); - return vector.CrossProduct(v) < 0.0; - } - - public static bool IsCcw(PointF pt1, PointF pt2, PointF pt3) - { - Vector vector = new Vector(pt2, pt1); - Vector v = new Vector(pt2, pt3); - return vector.CrossProduct(v) > 0.0; - } - - public static double DistancePointLine(PointF pt, PointF lnA, PointF lnB) - { - Vector v = new Vector(lnA, lnB); - Vector vector = new Vector(lnA, pt); - v /= v.Magnitude; - return Math.Abs(vector.CrossProduct(v)); - } - - public void Rotate(int degree) - { - double num = (double)degree * 3.1415926535897931 / 180.0; - double num2 = Math.Sin(num); - double num3 = Math.Cos(num); - double x = _x * num3 - _y * num2; - double y = _x * num2 + _y * num3; - _x = x; - _y = y; - } - - public PointF ToPointF() - { - return new PointF((float)_x, (float)_y); - } - } -} diff --git a/core/Boagaphish/Schema/BaseSchema.cs b/core/Boagaphish/Schema/BaseSchema.cs deleted file mode 100644 index f61a32c..0000000 --- a/core/Boagaphish/Schema/BaseSchema.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; - -namespace Boagaphish.Schema -{ - public class BaseSchema - { - public virtual List CellNames - { - get; - set; - } - - public virtual object[,] Grid - { - get; - set; - } - - public virtual string SchemaName - { - get; - set; - } - - public virtual int SchemaNumber - { - get; - set; - } - - public BaseSchema(string name, int width, int height, int x, int y, List cellNames) - { - Coordinate.X = x; - Coordinate.Y = y; - SchemaVector schemaVector = new SchemaVector(name, width, height, x, y, cellNames); - Grid = schemaVector.CellGrid; - CellListProperties(); - SchemaNumber = CellNames.Count; - SchemaName = name; - } - - public virtual List CellListProperties() - { - CellNames = new List(); - string[] array = new string[1] - { - "blank" - }; - string[] array2 = array; - foreach (string item in array2) - { - CellNames.Add(item); - } - return CellNames; - } - - public virtual object GetCellDescription(int cell) - { - return CellNames[cell]; - } - - public virtual void ParseCellData() - { - int count = CellNames.Count; - for (int i = 0; i < count; i++) - { - } - } - } -} diff --git a/core/Boagaphish/Schema/Coordinate.cs b/core/Boagaphish/Schema/Coordinate.cs deleted file mode 100644 index 7e73ba1..0000000 --- a/core/Boagaphish/Schema/Coordinate.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Runtime.InteropServices; - -namespace Boagaphish.Schema -{ - [StructLayout(LayoutKind.Sequential, Size = 1)] - public struct Coordinate - { - public static int X - { - get; - set; - } - - public static int Y - { - get; - set; - } - } -} diff --git a/core/Boagaphish/Schema/DriveSchema.cs b/core/Boagaphish/Schema/DriveSchema.cs deleted file mode 100644 index 2ae01f0..0000000 --- a/core/Boagaphish/Schema/DriveSchema.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; - -namespace Boagaphish.Schema -{ - public class DriveSchema : BaseSchema - { - public new List CellNames - { - get; - set; - } - - public override object[,] Grid - { - get; - set; - } - - public new int SchemaNumber - { - get; - set; - } - - public new string SchemaName - { - get; - set; - } - - public DriveSchema(string name, int width, int height, int x, int y, List cellNames) - : base(name, width, height, x, y, cellNames) - { - SchemaVector schemaVector = new SchemaVector(name, width, height, x, y, cellNames); - Grid = schemaVector.CellGrid; - CellListProperties(); - SchemaNumber = CellNames.Count; - SchemaName = name; - } - - public new List CellListProperties() - { - CellNames = new List(); - string[] array = new string[16] - { - "Pain", - "Need for pleasure", - "Hunger", - "Coldness", - "Hotness", - "Tiredness", - "Sleepiness", - "Loneliness", - "Overcrowdedness", - "Fear", - "Boredom", - "Anger", - "Sex drive", - "Not allocated2", - "Not allocated3", - "Not allocated4" - }; - string[] array2 = array; - foreach (string item in array2) - { - CellNames.Add(item); - } - return CellNames; - } - - public new object GetCellDescription(int cell) - { - return CellNames[cell]; - } - - public new void ParseCellData() - { - int count = CellNames.Count; - for (int i = 0; i < count; i++) - { - } - } - } -} diff --git a/core/Boagaphish/Schema/NextSchema.cs b/core/Boagaphish/Schema/NextSchema.cs deleted file mode 100644 index e3d1c46..0000000 --- a/core/Boagaphish/Schema/NextSchema.cs +++ /dev/null @@ -1,152 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; - -namespace Boagaphish.Schema -{ - public class NextSchema : BaseSchema - { - public new List CellNames - { - get; - set; - } - - public override object[,] Grid - { - get; - set; - } - - public new int SchemaNumber - { - get; - set; - } - - public override string SchemaName - { - get; - set; - } - - public NextSchema(string name, int width, int height, int x, int y, List cellNames) - : base(name, width, height, x, y, cellNames) - { - SchemaVector schemaVector = new SchemaVector(name, width, height, x, y, cellNames); - Grid = schemaVector.CellGrid; - CellListProperties(); - SchemaNumber = CellNames.Count; - SchemaName = name; - } - - public new List CellListProperties() - { - CellNames = new List(); - string[] array = new string[81] - { - "Activate 1 it (push)", - "Activate 2 it (pull)", - "Deactivate it (stop)", - "Approach it (come)", - "Retreat from it (run)", - "Get it (get)", - "Drop all (drop)", - "Say what you need (think)", - "Rest (sleep)", - "Travel west (left)", - "Travel east (right)", - "Verb12", - "Verb13", - "Verb14", - "Verb15", - "I've been patted", - "I've been hit", - "I've bumped into a wall", - "I am near a wall", - "I am in a vehicle", - "User has spoken", - "Own kind has spoken", - "Audible event", - "Visible event", - "It is approaching", - "It is retreating", - "It is near me", - "It is active", - "It is an object", - "sense20", - "sense21", - "sense22", - "sense23", - "sense24", - "sense25", - "sense26", - "sense27", - "sense28", - "sense29", - "sense30", - "sense31", - "Myself", - "Hand", - "Call", - "Water", - "Plant", - "Egg", - "Food", - "Drink", - "Vendor", - "Music", - "Animal", - "Fire", - "Shower", - "Toy", - "Bigtoy", - "Weed", - "Word32", - "Word33", - "Word34", - "Word35", - "Word36", - "Word37", - "Word38", - "Word39", - "Word40", - "Word41", - "Mover", - "Lift", - "Computer", - "Fun", - "Bang", - "Word47", - "Word48", - "Word49", - "Word50", - "Word51", - "Me", - "Grendle", - "Word54", - "Word55" - }; - string[] array2 = array; - foreach (string item in array2) - { - CellNames.Add(item); - } - return CellNames; - } - - public new object GetCellDescription(int cell) - { - return CellNames[cell]; - } - - public new void ParseCellData() - { - int count = CellNames.Count; - for (int i = 0; i < count; i++) - { - } - } - } -} diff --git a/core/Boagaphish/Schema/SchemaData.cs b/core/Boagaphish/Schema/SchemaData.cs deleted file mode 100644 index 812fcbb..0000000 --- a/core/Boagaphish/Schema/SchemaData.cs +++ /dev/null @@ -1,9 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Schema -{ - public class SchemaData - { - } -} diff --git a/core/Boagaphish/Schema/SchemaVector.cs b/core/Boagaphish/Schema/SchemaVector.cs deleted file mode 100644 index 86ee1e3..0000000 --- a/core/Boagaphish/Schema/SchemaVector.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; - -namespace Boagaphish.Schema -{ - public class SchemaVector - { - public object[,] CellGrid - { - get; - set; - } - - public SchemaVector(string name, int width, int height, int x, int y, List cellNames) - { - object[,] array = new object[width, height]; - for (int i = 0; i < height; i++) - { - for (int j = 0; j < width; j++) - { - foreach (object cellName in cellNames) - { - array[x + j, y + i] = cellName; - } - } - } - CellGrid = array; - } - - public SchemaVector(BaseSchema baseSchema) - { - } - } -} diff --git a/core/Boagaphish/Schema/TimeSchema.cs b/core/Boagaphish/Schema/TimeSchema.cs deleted file mode 100644 index 52130e3..0000000 --- a/core/Boagaphish/Schema/TimeSchema.cs +++ /dev/null @@ -1,69 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; - -namespace Boagaphish.Schema -{ - public class TimeSchema : BaseSchema - { - public new List CellNames - { - get; - set; - } - - public override object[,] Grid - { - get; - set; - } - - public new int SchemaNumber - { - get; - set; - } - - public override string SchemaName - { - get; - set; - } - - public TimeSchema(string name, int width, int height, int x, int y, List cellNames) - : base(name, width, height, x, y, cellNames) - { - SchemaVector schemaVector = new SchemaVector(name, width, height, x, y, cellNames); - Grid = schemaVector.CellGrid; - CellListProperties(); - SchemaNumber = CellNames.Count; - SchemaName = name; - } - - public new List CellListProperties() - { - CellNames = new List(); - double[] array = new double[1]; - double[] array2 = array; - foreach (double num in array2) - { - CellNames.Add(num); - } - return CellNames; - } - - public new object GetCellDescription(int cell) - { - return CellNames[cell]; - } - - public new void ParseCellData() - { - int count = CellNames.Count; - for (int i = 0; i < count; i++) - { - } - } - } -} diff --git a/core/Boagaphish/Settings/MakeCaseInsensitive.cs b/core/Boagaphish/Settings/MakeCaseInsensitive.cs deleted file mode 100644 index b126c49..0000000 --- a/core/Boagaphish/Settings/MakeCaseInsensitive.cs +++ /dev/null @@ -1,21 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Boagaphish.Settings -{ - /// - /// Normalizes the input text into upper case. - /// - public class MakeCaseInsensitive - { - /// - /// An ease-of-use static method that re-produces the instance transformation methods. - /// - /// The string to transform - /// The resulting string - public static string TransformInput(string input) - { - return input.ToUpper(); - } - } -} diff --git a/core/Boagaphish/Settings/SettingsDictionary.cs b/core/Boagaphish/Settings/SettingsDictionary.cs deleted file mode 100644 index 87b792c..0000000 --- a/core/Boagaphish/Settings/SettingsDictionary.cs +++ /dev/null @@ -1,228 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; -using System.IO; -using System.Xml; - -namespace Boagaphish.Settings -{ - /// - /// A dictionary for loading, adding, checking, removing, and extracting settings. - /// - public class SettingsDictionary - { - /// - /// Holds a dictionary of settings. - /// - private readonly Dictionary _settingsHash = new Dictionary(); - /// - /// Contains an ordered collection of all the keys. - /// - private readonly List _orderedKeys = new List(); - /// - /// The number of items in the dictionary. - /// - public int Count - { - get - { - return _orderedKeys.Count; - } - } - /// - /// An xml representation of the contents of this dictionary. - /// - public XmlDocument DictionaryAsXml - { - get - { - XmlDocument result = new XmlDocument(); - XmlDeclaration dec = result.CreateXmlDeclaration("1.0", "UTF-8", ""); - result.AppendChild(dec); - XmlNode root = result.CreateNode(XmlNodeType.Element, "root", ""); - result.AppendChild(root); - foreach (string key in _orderedKeys) - { - XmlNode item = result.CreateNode(XmlNodeType.Element, "item", ""); - XmlAttribute name = result.CreateAttribute("name"); - name.Value = key; - XmlAttribute value = result.CreateAttribute("value"); - value.Value = _settingsHash[key]; - if (item.Attributes != null) - { - item.Attributes.Append(name); - item.Attributes.Append(value); - } - root.AppendChild(item); - } - return result; - } - } - /// - /// Loads settings into the class from the file referenced in pathToSettings. The xml should have a declaration with a root tag with child nodes of the form: - /// - /// - /// The file containing the settings. - public void LoadSettings(string pathToSettings) - { - if (pathToSettings.Length > 0) - { - FileInfo fi = new FileInfo(pathToSettings); - if (fi.Exists) - { - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(pathToSettings); - LoadSettings(xmlDoc); - } - else - { - throw new FileNotFoundException(); - } - } - else - { - throw new FileNotFoundException(); - } - } - /// - /// Loads settings into the class from the file referenced in pathToSettings. The xml should have a declaration with a root tag with child nodes of the form: - /// - /// - /// The settings as an xml document. - public void LoadSettings(XmlDocument settingsAsXml) - { - // Empty the hash. - ClearSettings(); - - if (settingsAsXml.DocumentElement != null) - { - XmlNodeList rootChildren = settingsAsXml.DocumentElement.ChildNodes; - - foreach (XmlNode myNode in rootChildren) - { - if (myNode.Attributes != null && (myNode.Name == "item") & (myNode.Attributes.Count == 2)) - { - if ((myNode.Attributes[0].Name == "name") & (myNode.Attributes[1].Name == "value")) - { - string name = myNode.Attributes["name"].Value; - string value = myNode.Attributes["value"].Value; - if (name.Length > 0) - { - AddSetting(name, value); - } - } - } - } - } - } - /// - /// Adds a setting to the Settings class (accessed via the grabSettings(string name) method. - /// - /// The name of the new setting. - /// The value associated with this setting. - public void AddSetting(string name, string value) - { - string key = MakeCaseInsensitive.TransformInput(name); - if (key.Length > 0) - { - RemoveSetting(key); - _orderedKeys.Add(key); - _settingsHash.Add(MakeCaseInsensitive.TransformInput(key), value); - } - } - /// - /// Removes a named setting from this class. - /// - /// The name of the setting to remove. - public void RemoveSetting(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - _orderedKeys.Remove(normalizedName); - RemoveFromHash(normalizedName); - } - /// - /// Removes a named setting from the dictionary. - /// - /// The key for the dictionary. - private void RemoveFromHash(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - _settingsHash.Remove(normalizedName); - } - /// - /// Updates the named setting with a new value while retaining the position in the dictionary. - /// - /// The name of the setting. - /// The new value. - public void UpdateSetting(string name, string value) - { - string key = MakeCaseInsensitive.TransformInput(name); - if (_orderedKeys.Contains(key)) - { - RemoveFromHash(key); - _settingsHash.Add(MakeCaseInsensitive.TransformInput(key), value); - } - } - /// - /// Clears the dictionary to an empty state. - /// - public void ClearSettings() - { - _orderedKeys.Clear(); - _settingsHash.Clear(); - } - /// - /// Returns the value of a setting given the name of the setting. - /// - /// The name of the setting whose value is of interest. - /// The value of the setting. - public string GrabSetting(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - if (ContainsSettingCalled(normalizedName)) - { - return _settingsHash[normalizedName]; - } - return string.Empty; - } - /// - /// Checks to see if a setting of a particular name exists. - /// - /// The setting name to check. - /// Existential truth value. - public bool ContainsSettingCalled(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - if (normalizedName.Length > 0) - { - return _orderedKeys.Contains(normalizedName); - } - return false; - } - /// - /// Returns a collection of the names of all the settings defined in the dictionary. - /// - /// A collection of the names of all the settings defined in the dictionary. - public string[] SettingNames - { - get - { - string[] result = new string[_orderedKeys.Count]; - _orderedKeys.CopyTo(result, 0); - return result; - } - } - /// - /// Copies the values in the current object into the SettingsDictionary passed as the target. - /// - /// The target to recieve the values from this SettingsDictionary. - public void Clone(SettingsDictionary target) - { - foreach (string key in _orderedKeys) - { - target.AddSetting(key, GrabSetting(key)); - } - } - } -} diff --git a/core/Boagaphish/literature/1-s2.0-S0315086017300691-main.pdf b/core/Boagaphish/literature/1-s2.0-S0315086017300691-main.pdf deleted file mode 100644 index 6aa8aef..0000000 Binary files a/core/Boagaphish/literature/1-s2.0-S0315086017300691-main.pdf and /dev/null differ diff --git a/core/Control/Gpio.cs b/core/Control/Gpio.cs deleted file mode 100644 index a303c75..0000000 --- a/core/Control/Gpio.cs +++ /dev/null @@ -1,74 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Diagnostics; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.Control -{ - /// - /// Class managing the external GPIO hardware. - /// - public static class Gpio - { - /// - /// Runs a python script. - /// - /// true, if python script was run, false otherwise. - /// The file to run. - /// The runtime configuration. - public static bool RunPythonScript(string file, LoaderPaths configuration) - { - ProcessStartInfo ps = new ProcessStartInfo - { - FileName = "python", - UseShellExecute = false, - RedirectStandardOutput = true, - Arguments = configuration.PathToScripts + @"/" + file - }; - try - { - Process ppy = Process.Start(ps); - ppy.StandardOutput.ReadToEnd(); - ppy.WaitForExit(); - return true; - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.AeonRuntime); - return false; - } - - } - /// - /// Runs a python script. - /// - /// true, if python script was run, false otherwise. - /// The file to run. - /// The parameter to pass. - /// The runtime configuration. - public static bool RunPythonScript(string file, string parameter, LoaderPaths configuration) - { - ProcessStartInfo ps = new ProcessStartInfo - { - FileName = "python", - UseShellExecute = false, - RedirectStandardOutput = true, - Arguments = configuration.PathToScripts + @"/" + file + " " + parameter - }; - try - { - Process ppy = Process.Start(ps); - ppy.StandardOutput.ReadToEnd(); - ppy.WaitForExit(); - return true; - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.AeonRuntime); - return false; - } - } - } -} diff --git a/core/Core/Aeon.cs b/core/Core/Aeon.cs deleted file mode 100644 index cf7686b..0000000 --- a/core/Core/Aeon.cs +++ /dev/null @@ -1,1014 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Text.RegularExpressions; -using System.Timers; -using System.Xml; -using Cartheur.Animals.AeonTagHandlers; -using Cartheur.Animals.Normalize; -using Cartheur.Animals.Personality; -using Cartheur.Animals.Utilities; -using Gender = Cartheur.Animals.AeonTagHandlers.Gender; -using Random = Cartheur.Animals.AeonTagHandlers.RandomTag; -using Version = Cartheur.Animals.AeonTagHandlers.Version; - -namespace Cartheur.Animals.Core -{ - /// - /// The area of the brain responsible for processing the data at hand. - /// - public enum Characteristic - { - /// - /// The attention characteristic. - /// - Attention, - /// - /// The concept characteristic. - /// - Concept, - /// - /// The decision characteristic. - /// - Decision, - /// - /// The drive characteristic. - /// - Drive, - /// - /// The noun characteristic. - /// - Noun, - /// - /// The perception characteristic. - /// - Perception, - /// - /// The predicate characteristic. - /// - Predicate, - /// - /// The sensory characteristic. - /// - Sensory, - /// - /// The stimulus characteristic. - /// - Stimulus, - /// - /// The verb characteristic. - /// - Verb - } - - /// - /// The intuitive presence to which the functions and behavior are attached. - /// - public class Aeon - { - /// - /// The language the aeon speaks and understands. - /// - public enum Language - { - /// - /// The English language. - /// - English, - /// - /// The German language. - /// - German, - /// - /// The French language. - /// - French, - /// - /// The Spanish language. - /// - Spanish, - /// - /// The Italian language. - /// - Italian, - /// - /// A nonsense language. - /// - Sal - } - /// - /// Gets or sets the characteristic equation to govern the aeon's behaviour. - /// - /// - /// The characteristic equation. - /// - public string CharacteristicEquation { get; set; } - /// - /// Holds information about the available custom tag handling classes (if loaded). - /// The class name. - /// Key - /// - /// The TagHandler class that provides information about the class. - /// Value - /// - /// - private Dictionary _customTags; - /// - /// Holds references to the assemblies that hold the custom tag handling code. - /// - private readonly Dictionary _lateBindingAssemblies = new Dictionary(); - /// - /// The message to show if a user tries to use aeon whilst set to not process user input. - /// - private string NotAcceptingUserInputMessage - { - get - { - return GlobalSettings.GrabSetting("notacceptinguserinputmessage"); - } - } - /// - /// Flag to show if aeon is accepting user input. - /// - public bool IsAcceptingUserInput = true; - /// - /// The number of categories aeon has in her brain. - /// - public int Size; - /// - /// If set to false the input from aeon code files will undergo the same normalization process that user input goes through. If true aeon will assume the code structure is correct. Defaults to true. - /// - public bool TrustCodeFiles = true; - /// - /// The maximum number of characters a "that" element of a path is allowed to be. Anything above this length will cause "that" to be "*". This is to avoid having the core process huge "that" elements in the path that might have been caused by aeon reporting third party data. - /// - public int MaxThatSize = 256; - /// - /// The maximum amount of time the aeon should be left alone before prompting the user (in milliseconds). - /// - public double AloneTime - { - get - { - return Convert.ToDouble(GlobalSettings.GrabSetting("alonetime")); - } - } - /// - /// The maximum amount of time a request should take (in milliseconds). - /// - public double TimeOut - { - get - { - return Convert.ToDouble(GlobalSettings.GrabSetting("timeout")); - } - } - /// - /// The message to display in the event of a timeout. - /// - public string TimeOutMessage - { - get - { - return GlobalSettings.GrabSetting("timeoutmessage"); - } - } - /// - /// The locale of aeon as a CultureInfo object. - /// - public CultureInfo Locale - { - get - { - return new CultureInfo(GlobalSettings.GrabSetting("culture")); - } - } - /// - /// Will match all the illegal characters that might be input by the user. - /// - public Regex Strippers - { - get - { - return new Regex(GlobalSettings.GrabSetting("stripperregex"), RegexOptions.IgnorePatternWhitespace); - } - } - /// - /// The email address to correspond with. - /// - public string AdminEmail - { - get - { - return GlobalSettings.GrabSetting("adminemail"); - } - set - { - if (value.Length > 0) - { - // Check that the email adress is in a valid format. - const string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+" - + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@" - + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" - + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" - + @"[a-zA-Z]{2,}))$"; - Regex reStrict = new Regex(patternStrict); - - if (reStrict.IsMatch(value)) - { - // Update settings. - GlobalSettings.AddSetting("adminemail", value); - } - else - { - throw (new Exception("The AdminEmail is not a valid email address")); - } - } - else - { - GlobalSettings.AddSetting("adminemail", ""); - } - } - } - /// - /// Flag to denote if aeon is logging. - /// - public bool IsLogging - { - get - { - string islogging = GlobalSettings.GrabSetting("islogging"); - if (islogging.ToLower() == "true") - { - return true; - } - return false; - } - } - /// - /// The time when this aeon was started. - /// - public DateTime AeonStartedOn; - /// - /// The time when the alone time started. - /// - public DateTime AeonAloneStartedOn { get; set; } - /// - /// The timer responsible for knowing when aeon is alone. - /// - public Timer AeonAloneTimer { get; set; } - /// - /// The last message to be entered into the log (for testing purposes) - /// - public string LastLogMessage = string.Empty; - /// - /// Returns the persistence of the aeon (in milliseconds). - /// - public int Persistence() - { - if (PersonalityLoaded) - return (DateTime.Now - AeonStartedOn).Milliseconds; - return 0; - } - /// - /// Gets or sets a value indicating whether [emotion used]. - /// - /// - /// true if [emotion used]; otherwise, false. - /// - public bool EmotionUsed { get; set; } - /// - /// Flag to indicate if a personality is loaded. - /// - public static bool PersonalityLoaded; - /// - /// Gets or sets the name. - /// - public string Name { get; set; } - /// - /// Gets or sets a value indicating whether [about me]. - /// - /// - /// true if [about me]; otherwise, false. - /// - public bool AboutMe { get; set; } - /// - /// Indicates if the aeon is in an error state. - /// - public bool ErrorState { get; set; } - /// - /// The splitters object. - /// - public List Splitters = new List(); - /// - /// The brain of aeon. - /// - public Node ThisNode; - /// - /// Determines if learning is active or not. - /// - public enum LearningMode - { - /// - /// Learning mode is true. - /// - True, - /// - /// Learning mode is false. - /// - False - }; - /// - /// Particulate for learning. - /// - //public LearningThreads Tidbit { get; set; } - /// - /// Gets the alone threshold. - /// - public TimeSpan AloneThreshold - { - get - { - return new TimeSpan(0, 0, 0, 0, Convert.ToInt32(GlobalSettings.GrabSetting("alonethreshold"))); - } - } - /// - /// Computes the alone time duration. - /// - /// The duration. - public TimeSpan AeonAloneDuration() - { - return (DateTime.Now - AeonAloneStartedOn); - } - /// - /// Determines whether the aeon is alone. - /// - /// If this aeon is feeling alone. - public bool IsAlone() - { - if (AeonAloneDuration() > AloneThreshold) - { - return true; - } - return false; - } - /// - /// The supposed sex of aeon. - /// - public AeonGender Sex - { - get - { - int sex = Convert.ToInt32(GlobalSettings.GrabSetting("gender")); - AeonGender result; - switch (sex) - { - case -1: - result = AeonGender.Unknown; - break; - case 0: - result = AeonGender.Female; - break; - case 1: - result = AeonGender.Male; - break; - default: - result = AeonGender.Unknown; - break; - } - return result; - } - } - /// - /// A dictionary object that looks after all the settings associated with this aeon. - /// - public SettingsDictionary GlobalSettings; - /// - /// A dictionary of first to third-person substitutions. - /// - public SettingsDictionary PersonSubstitutions; - /// - /// Generic substitutions that take place during the normalization process. - /// - public SettingsDictionary Substitutions; - /// - /// The default predicates to set up for a user. - /// - public SettingsDictionary DefaultPredicates; - /// - /// Instantiates the dictionary objects and collections associated with this class. - /// - private void Setup() - { - GlobalSettings = new SettingsDictionary(this); - PersonSubstitutions = new SettingsDictionary(this); - Substitutions = new SettingsDictionary(this); - DefaultPredicates = new SettingsDictionary(this); - _customTags = new Dictionary(); - ThisNode = new Node(); - AeonStartedOn = DateTime.Now; - } - /// - /// Initializes a new instance of the class. - /// - /// The characteristic equation governing the aeon. - public Aeon(string characteristicEquation) - { - CharacteristicEquation = characteristicEquation; - Setup(); - } - - #region Mood settings from config file - /// - /// Gets the emotion engine seed value. - /// - public string MoodEngineSeedValue - { - get - { - return GlobalSettings.GrabSetting("seedmoodengine"); - } - } - #endregion - - #region Delegates & events - /// - /// The log message delegate. - /// - public delegate void LogMessageDelegate(); - #endregion - - #region Settings and load methods - /// - /// Allows aeon to load a new xml version of some aeon xms data. - /// - /// The xml document containing xms. - /// The originator of the xml document. - public void LoadAeonFromXml(XmlDocument xmlCode, string filename) - { - AeonLoader loader = new AeonLoader(this); - loader.LoadAeonFromXml(xmlCode, filename); - } - /// - /// Loads settings and configuration info from various xml files referenced in the settings file passed in the args. Also generates some default values if such values have not been set by the settings file. - /// - /// Path to the xml configuration file. - public void LoadSettings(string configurationPath) - { - GlobalSettings.LoadSettings(configurationPath); - - // Checks for some critical default settings. - if (!GlobalSettings.ContainsSettingCalled("version")) - { - GlobalSettings.AddSetting("version", Environment.Version.ToString()); - } - if (!GlobalSettings.ContainsSettingCalled("name")) - { - GlobalSettings.AddSetting("name", "aeon"); - } - if (!GlobalSettings.ContainsSettingCalled("botmaster")) - { - GlobalSettings.AddSetting("botmaster", "Unknown"); - } - if (!GlobalSettings.ContainsSettingCalled("master")) - { - GlobalSettings.AddSetting("botmaster", "Unknown"); - } - if (!GlobalSettings.ContainsSettingCalled("author")) - { - GlobalSettings.AddSetting("author", "malfactor"); - } - if (!GlobalSettings.ContainsSettingCalled("location")) - { - GlobalSettings.AddSetting("location", "Unknown"); - } - if (!GlobalSettings.ContainsSettingCalled("gender")) - { - GlobalSettings.AddSetting("gender", "-1"); - } - if (!GlobalSettings.ContainsSettingCalled("birthday")) - { - GlobalSettings.AddSetting("birthday", "2015/09/09"); - } - if (!GlobalSettings.ContainsSettingCalled("birthplace")) - { - GlobalSettings.AddSetting("birthplace", "somewhere"); - } - if (!GlobalSettings.ContainsSettingCalled("website")) - { - GlobalSettings.AddSetting("website", "http://emotional.toys"); - } - if (GlobalSettings.ContainsSettingCalled("adminemail")) - { - string emailToCheck = GlobalSettings.GrabSetting("adminemail"); - AdminEmail = emailToCheck; - } - else - { - GlobalSettings.AddSetting("adminemail", ""); - } - if (!GlobalSettings.ContainsSettingCalled("islogging")) - { - GlobalSettings.AddSetting("islogging", "true"); - } - if (!GlobalSettings.ContainsSettingCalled("willcallhome")) - { - GlobalSettings.AddSetting("willcallhome", "False"); - } - if (!GlobalSettings.ContainsSettingCalled("timeout")) - { - GlobalSettings.AddSetting("timeout", "2000"); - } - if (!GlobalSettings.ContainsSettingCalled("timeoutmessage")) - { - GlobalSettings.AddSetting("timeoutmessage", "The request has timed out."); - } - if (!GlobalSettings.ContainsSettingCalled("culture")) - { - GlobalSettings.AddSetting("culture", "en-UK"); - } - if (!GlobalSettings.ContainsSettingCalled("splittersfile")) - { - GlobalSettings.AddSetting("splittersfile", "Splitters.xml"); - } - if (!GlobalSettings.ContainsSettingCalled("personsubstitutionsfile")) - { - GlobalSettings.AddSetting("personsubstitutionsfile", "PersonSubstitutions.xml"); - } - if (!GlobalSettings.ContainsSettingCalled("defaultpredicates")) - { - GlobalSettings.AddSetting("defaultpredicates", "DefaultPredicates.xml"); - } - if (!GlobalSettings.ContainsSettingCalled("substitutionsfile")) - { - GlobalSettings.AddSetting("substitutionsfile", "Substitutions.xml"); - } - if (!GlobalSettings.ContainsSettingCalled("configdirectory")) - { - GlobalSettings.AddSetting("configdirectory", "config"); - } - if (!GlobalSettings.ContainsSettingCalled("logdirectory")) - { - GlobalSettings.AddSetting("logdirectory", "logs"); - } - if (!GlobalSettings.ContainsSettingCalled("maxlogbuffersize")) - { - GlobalSettings.AddSetting("maxlogbuffersize", "64"); - } - if (!GlobalSettings.ContainsSettingCalled("notacceptinguserinputmessage")) - { - GlobalSettings.AddSetting("notacceptinguserinputmessage", "Aeon is not accepting user input."); - } - if (!GlobalSettings.ContainsSettingCalled("stripperregex")) - { - GlobalSettings.AddSetting("stripperregex", "[^0-9a-zA-Z]"); - } - if (!GlobalSettings.ContainsSettingCalled("password")) - { - GlobalSettings.AddSetting("password", "XhUkIjUnYvTqIjUj"); - } - } - /// - /// Updates a settings entry. - /// - /// The key. - /// The value. - public void UpdateSetting(string key, string value) - { - GlobalSettings.UpdateSetting(key, value); - } - /// - /// Adds an entry to settings. - /// - /// The key. - /// The value. - public void AddSetting(string key, string value) - { - GlobalSettings.AddSetting(key, value); - } - /// - /// Loads splitters for this aeon from the supplied config file (or sets up some appropriate defaults). - /// - /// Path to the splitters configuration file. - public void LoadSplitters(string splittersPath) - { - FileInfo splittersFile = new FileInfo(splittersPath); - if (splittersFile.Exists) - { - XmlDocument splittersXmlDoc = new XmlDocument(); - splittersXmlDoc.Load(splittersPath); - // The XML should have an XML declaration like this: - // - // followed by a tag with children of the form: - // - if (splittersXmlDoc.ChildNodes.Count == 2) - { - if (splittersXmlDoc.LastChild.HasChildNodes) - { - foreach (XmlNode myNode in splittersXmlDoc.LastChild.ChildNodes) - { - if (myNode.Attributes != null && (myNode.Name == "item") & (myNode.Attributes.Count == 1)) - { - string value = myNode.Attributes["value"].Value; - Splitters.Add(value); - } - } - } - } - } - if (Splitters.Count == 0) - { - // We don't have any splitters, so lets make do with the following. - Splitters.Add("."); - Splitters.Add("!"); - Splitters.Add("?"); - Splitters.Add(";"); - } - } - #endregion - - #region Conversation methods - /// - /// Given some raw input and a unique ID creates a response for a new user. - /// - /// the raw input. - /// The ID for the user (referenced in the result object). - /// Result to the user. - public Result Chat(string rawInput, string userGuid) - { - Request request = new Request(rawInput, new User(userGuid, this), this); - return Chat(request); - } - /// - /// Given a request containing user input, produces a result from aeon. - /// - /// The request from the user. - /// The result to be output to the user. - public Result Chat(Request request) - { - var result = new Result(request.ThisUser, this, request, CharacteristicEquation); - // Set the emotion, where used. It is now known to the core. - result.ThisUser.Predicates.UpdateSetting("EMOTION", Mood.CurrentMood); - - if (IsAcceptingUserInput) - { - // Normalize the input. - AeonLoader loader = new AeonLoader(this); - SplitIntoSentences splitter = new SplitIntoSentences(this); - string[] rawSentences = splitter.Transform(request.RawInput); - foreach (string sentence in rawSentences) - { - result.InputSentences.Add(sentence); - string trajectoryGenerated; - if (EmotionUsed) - { - trajectoryGenerated = loader.GenerateTrajectory(sentence, request.ThisUser.GetLastAeonOutput(), request.ThisUser.Topic, request.ThisUser.Emotion, true); - result.NormalizedTrajectories.Add(trajectoryGenerated); - } - else - { - trajectoryGenerated = loader.GenerateTrajectory(sentence, request.ThisUser.GetLastAeonOutput(), request.ThisUser.Topic, true); - result.NormalizedTrajectories.Add(trajectoryGenerated); - } - - } - // Grab the templates for the various sentences. - foreach (string trajectory in result.NormalizedTrajectories) - { - SubQuery query = new SubQuery(trajectory); - query.Template = ThisNode.Evaluate(trajectory, query, request, MatchState.UserInput, new StringBuilder()); - result.SubQueries.Add(query); - } - // Influence the type of response based on the value of the mood (if set to true). - if (request.RawInput.Contains("you feeling") && EmotionUsed) - { - AboutMe = true; - Mood.Compliment++; - // Perhaps some emotional variety instead of reformatting the trajectory. - // Get the I am feeling "". - //string newTrajectory = ""; - //foreach (string normalizedTrajectory in result.NormalizedTrajectories) - //{ - // string emotionalOutput = "I am feeling " + Mood.CurrentMood + "."; - // newTrajectory = normalizedTrajectory.Replace(" " + Mood.CurrentMood, " " + emotionalOutput); - //} - //for (int i = 0; i < result.NormalizedTrajectories.Count; i++) - //{ - // result.NormalizedTrajectories[i] = newTrajectory; - //} - result.ThisUser.Predicates.UpdateSetting("EMOTION", Mood.CurrentMood); - } - if (rawSentences.Contains("love you") && EmotionUsed) - { - AboutMe = true; - Mood.Compliment++; - Mood.Love++; - } - // Process the templates into appropriate output. - foreach (SubQuery query in result.SubQueries) - { - if (query.Template.Length > 0) - { - try - { - XmlNode templateNode = AeonTagHandler.GetNode(query.Template); - string outputSentence = ProcessNode(templateNode, query, request, result, request.ThisUser); - // Integrate the learned output with this query response. - if (outputSentence.Length > 0) - { - result.OutputSentences.Add(outputSentence); - } - } - catch (Exception ex) - { - Logging.WriteLog("A problem was encountered when trying to process the input: " + request.RawInput + " with the template: \"" + query.Template + ". The following exception message was noted: " + ex.Message, Logging.LogType.Warning, Logging.LogCaller.Aeon); - } - } - } - } - else - { - result.OutputSentences.Add(NotAcceptingUserInputMessage); - } - // Return the indication from the process. - result.ReturnIndication(); - // Populate the result object and note the performance. - result.Duration = DateTime.Now - request.StartedOn; - request.ThisUser.AddResult(result); - - return result; - } - /// - /// Recursively evaluates the template nodes returned from aeon. - /// - /// The node to evaluate. - /// The query that produced this node. - /// The request from the user. - /// The result to be sent to the user. - /// The user who originated the request. - /// The output string. - protected string ProcessNode(XmlNode node, SubQuery query, Request request, Result result, User user) - { - // Check for timeout (to avoid infinite loops). - if (request.StartedOn.AddMilliseconds(request.ThisAeon.TimeOut) < DateTime.Now) - { - Logging.WriteLog("Request timeout. User: " + request.ThisUser.UserName + " raw input: \"" + request.RawInput + "\" processing template: \"" + query.Template + "\"", Logging.LogType.Warning, Logging.LogCaller.Aeon); - request.HasTimedOut = true; - return string.Empty; - } - - // Process the node. - string tagName = node.Name.ToLower(); - if (tagName == "template") - { - StringBuilder templateResult = new StringBuilder(); - if (node.HasChildNodes) - { - // Recursively check. Stepping in here, how does it get four child nodes after parsing only one? - foreach (XmlNode childNode in node.ChildNodes) - { - templateResult.Append(ProcessNode(childNode, query, request, result, user)); - // Does this really step to the next child node? - } - } - return templateResult.ToString(); - } - AeonTagHandler tagHandler = GetBespokeTags(user, query, request, result, node); - - if (Equals(null, tagHandler)) - { - switch (tagName) - { - case "bot": - tagHandler = new Bot(this, user, query, request, result, node); - break; - case "condition": - tagHandler = new Condition(this, user, query, request, result, node); - break; - case "date": - tagHandler = new Date(this, user, query, request, result, node); - break; - case "formal": - tagHandler = new Formal(this, user, query, request, result, node); - break; - case "gender": - tagHandler = new Gender(this, user, query, request, result, node); - break; - case "get": - tagHandler = new Get(this, user, query, request, result, node); - break; - case "gossip": - tagHandler = new Gossip(this, user, query, request, result, node); - break; - case "id": - tagHandler = new Id(this, user, query, request, result, node); - break; - case "input": - tagHandler = new Input(this, user, query, request, result, node); - break; - case "learn": - tagHandler = new Learn(this, user, query, request, result, node); - break; - case "lowercase": - tagHandler = new Lowercase(this, user, query, request, result, node); - break; - case "person": - tagHandler = new Person(this, user, query, request, result, node); - break; - case "person2": - tagHandler = new Person2(this, user, query, request, result, node); - break; - case "piglatin": - tagHandler = new Piglatin(); - break; - case "random": - tagHandler = new Random(this, user, query, request, result, node); - break; - case "script": - tagHandler = new Script(this, user, query, request, result, node); - // Reserved for on-the-fly script execution. - break; - case "sentence": - tagHandler = new Sentence(this, user, query, request, result, node); - break; - case "set": - tagHandler = new Set(this, user, query, request, result, node); - break; - case "size": - tagHandler = new Size(this, user, query, request, result, node); - break; - case "sr": - tagHandler = new Sr(this, user, query, request, result, node); - break; - case "srai": - tagHandler = new Srai(this, user, query, request, result, node); - break; - case "star": - tagHandler = new Star(this, user, query, request, result, node); - break; - case "test": - tagHandler = new Test(); - break; - case "that": - tagHandler = new That(this, user, query, request, result, node); - break; - case "thatstar": - tagHandler = new ThatStar(this, user, query, request, result, node); - break; - case "think": - tagHandler = new Think(this, user, query, request, result, node); - break; - case "topicstar": - tagHandler = new TopicStar(this, user, query, request, result, node); - break; - case "uppercase": - tagHandler = new Uppercase(this, user, query, request, result, node); - break; - case "version": - tagHandler = new Version(this, user, query, request, result, node); - break; - } - } - if (Equals(null, tagHandler)) - { - return node.InnerText; - } - if (tagHandler.IsRecursive) - { - if (node.HasChildNodes) - { - // Recursively check. - foreach (XmlNode childNode in node.ChildNodes) - { - if (childNode.NodeType != XmlNodeType.Text) - { - childNode.InnerXml = ProcessNode(childNode, query, request, result, user); - } - } - } - return tagHandler.Transform(); - } - string resultNodeInnerXml = tagHandler.Transform(); - XmlNode resultNode = AeonTagHandler.GetNode("" + resultNodeInnerXml + ""); - if (resultNode.HasChildNodes) - { - StringBuilder recursiveResult = new StringBuilder(); - // Recursively check. - foreach (XmlNode childNode in resultNode.ChildNodes) - { - recursiveResult.Append(ProcessNode(childNode, query, request, result, user)); - } - return recursiveResult.ToString(); - } - return resultNode.InnerXml; - } - /// - /// Searches the custom tag collection and processes the aeon files if an appropriate tag handler is found. - /// - /// The user who originated the request. - /// The query that produced this node. - /// The request from the user. - /// The result to be sent to the user. - /// The node to evaluate. - /// The output string. - public AeonTagHandler GetBespokeTags(User user, SubQuery query, Request request, Result result, XmlNode node) - { - if (_customTags.ContainsKey(node.Name.ToLower())) - { - TagHandler customTagHandler = _customTags[node.Name.ToLower()]; - AeonTagHandler newCustomTag = customTagHandler.Instantiate(_lateBindingAssemblies); - if (Equals(null, newCustomTag)) - { - return null; - } - newCustomTag.ThisUser = user; - newCustomTag.Query = query; - newCustomTag.UserRequest = request; - newCustomTag.UserResult = result; - newCustomTag.TemplateNode = node; - newCustomTag.ThisAeon = this; - return newCustomTag; - } - return null; - } - #endregion - - #region Serialization - /// - /// Saves the root node (and children) to a binary file. - /// - /// the path to the file for saving - public void SaveToBinaryFile(string path) - { - // check to delete an existing version of the file - FileInfo fi = new FileInfo(path); - if (fi.Exists) - { - fi.Delete(); - } - - FileStream saveFile = File.Create(path); - //BinaryFormatter bf = new BinaryFormatter(); - //bf.Serialize(saveFile, ThisNode); - saveFile.Close(); - } - /// - /// Loads a dump of the root node (and children) into memory. - /// - /// the path to the dump file - public void LoadFromBinaryFile(string path) - { - FileStream loadFile = File.OpenRead(path); - //BinaryFormatter bf = new BinaryFormatter(); - //ThisNode = (Node)bf.Deserialize(loadFile); - loadFile.Close(); - } - #endregion - - #region Late-binding custom-tag assembly handlers - /// - /// Loads any custom tag handlers found in the library passed in the argument. - /// - /// The path to the library containing the custom tag handling code. - public void LoadCustomTagHandlers(string pathToLibrary) - { - Assembly tagAssembly = Assembly.LoadFrom(pathToLibrary); - Type[] tagDllTypes = tagAssembly.GetTypes(); - for (int i = 0; i < tagDllTypes.Length; i++) - { - object[] typeCustomAttributes = tagDllTypes[i].GetCustomAttributes(false); - for (int j = 0; j < typeCustomAttributes.Length; j++) - { - if (typeCustomAttributes[j] is CustomTagAttribute) - { - // A custom tag has been found so store the data in the Dictionary as a TagHandler class for later usage. - if (!_lateBindingAssemblies.ContainsKey(tagAssembly.FullName)) - { - _lateBindingAssemblies.Add(tagAssembly.FullName, tagAssembly); - } - // Create the TagHandler representation. - TagHandler newTagHandler = new TagHandler - { - AssemblyName = tagAssembly.FullName, - ClassName = tagDllTypes[i].FullName, - TagName = tagDllTypes[i].Name.ToLower() - }; - if (_customTags.ContainsKey(newTagHandler.TagName)) - { - throw new Exception("Unable to add the custom tag: <" + newTagHandler.TagName + ">, found in: " + pathToLibrary + " as a handler for this tag already exists."); - } - _customTags.Add(newTagHandler.TagName, newTagHandler); - } - } - } - } - #endregion - } -} diff --git a/core/Core/AeonGender.cs b/core/Core/AeonGender.cs deleted file mode 100644 index 666902b..0000000 --- a/core/Core/AeonGender.cs +++ /dev/null @@ -1,24 +0,0 @@ - // -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Cartheur.Animals.Core -{ - /// - /// Used to determine the gender of things. - /// - public enum AeonGender - { - /// - /// Indicates an unknown gender to aeon. - /// - Unknown = -1, - /// - /// Indicates a female gender to aeon. - /// - Female = 0, - /// - /// Indicates a male gender to aeon. - /// - Male = 1 - } -} \ No newline at end of file diff --git a/core/Core/AlgorithmicTechnique.cs b/core/Core/AlgorithmicTechnique.cs deleted file mode 100644 index 0da7b73..0000000 --- a/core/Core/AlgorithmicTechnique.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// - -namespace Cartheur.Animals.Core -{ - /// - /// The patented learning algorithmic technique. - /// - /// USPTO-310 - /// Here is where we leverage Boagaphish. - public class AlgorithmicTechnique - { - /// - /// The trajectory indication computed by the algorithmic technique. - /// - /// USPTO-311 - public Indication Trajectory { get; set; } - /// - /// The equation object from the indication. - /// - /// USPTO-704 - public SweetPolynomial.DifferentialOperator Equation { get; set; } - /// - /// The instruction tag. - /// - /// USPTO-701 - public AeonTagHandlers.That Tag { get; set; } - /// - /// The entrypoint for the algorithmic technique. - /// - /// - public AlgorithmicTechnique(Boagaphish.Core.Animals.BackPropagationNetwork technique) - { - // Basic entrypoint logic. - } - // Missing feedback from the technique - USPTO-111. - - // Missing filesystem output from the intension catalog - USPTO-104. But the static class Amend.cs is a good candidate. - } -} \ No newline at end of file diff --git a/core/Core/Amend.cs b/core/Core/Amend.cs deleted file mode 100644 index 733c1ce..0000000 --- a/core/Core/Amend.cs +++ /dev/null @@ -1,55 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Cartheur.Animals.Core -{ - /// - /// Dynamic-amending the composite database and grammar repository. - /// - /// Can be used to leverage USPTO-104. - public static class Amend - { - /// - /// The kind of amend operation to perform. - /// - public enum Operation - { - /// - /// Add something to a field. - /// - Add, - /// - /// Delete the entry. - /// - Delete, - /// - /// Replace a field with a better entry. - /// - Replace - } - /// - /// Amends the conversational database. - /// - /// The incorrect entry. - /// The alteration to replace it. - /// The operation to perform. - /// - public static bool AmendDatabase(string incorrect, string alteration, Operation operation) - { - - return true; - } - /// - /// Amends the grammar repository. - /// - /// The incorrect entry. - /// The alteration to replace it. - /// The operation to perform. - /// - public static bool AmendGrammar(string incorrect, string alteration, Operation operation) - { - - return true; - } - } -} diff --git a/core/Core/Classes-300.cs b/core/Core/Classes-300.cs deleted file mode 100644 index 1a8c074..0000000 --- a/core/Core/Classes-300.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -/// -/// This file contains the classes mentioned in Figure 3 (drawing 300). -/// -namespace Cartheur.Animals.Core -{ - /// - /// The class for the topic. - /// - /// USPTO-308 - public class Topic - { - // Here goes the topic extract from the conversational engine. - } - /// - /// The class for the sentence-groupings. - /// - /// USPTO-305 - public class Sentences - { - // Here goes the n-sentences from the conversational engine. - public enum SentencePart { Subject, Verb, Predicate } - - } - /// - /// The class for the intention catalog. - /// - /// USPTO-306 - public class IntentionCatalog - { - // Here is the intention catalog object from USPTO-306. - //Amend.Operation.Add(/*Output from the catalog*/); - } -} \ No newline at end of file diff --git a/core/Core/Classes-400.cs b/core/Core/Classes-400.cs deleted file mode 100644 index 7c9c017..0000000 --- a/core/Core/Classes-400.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -using Boagaphish.Format; -using Cartheur.Animals.Personality; - -/// -/// This file contains the classes mentioned in Figure 4 (drawing 400). -/// -namespace Cartheur.Animals.Core -{ - /// - /// USPTO-405 - /// - public static class CurrentMood - { - /// - /// USPTO-401 yielding 403 via 402. - /// - /// The mood object - /// This also touches 404 - public static Mood Create(this Mood mood) - { - var val = new StaticRandom(mood.SeedValue); - return new Mood(mood.SeedValue, mood.ThisAeon, mood.ThisUser, mood.EmotiveIndication.ToString(), mood.EmotionBias); - } - /// - /// USPTO-401 yielding 403 via 402. - /// - /// The mood object - /// This also touches 404 and 405 - public static Mood Update(this Mood mood) - { - // Update the object. - return new Mood(mood.SeedValue, mood.ThisAeon, mood.EmotiveIndication.ToString()); - } - - - } - -} \ No newline at end of file diff --git a/core/Core/Extensions.cs b/core/Core/Extensions.cs deleted file mode 100644 index 690fa74..0000000 --- a/core/Core/Extensions.cs +++ /dev/null @@ -1,216 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Xml.Linq; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.Core -{ - /// - /// The class containing the extensions for the application. - /// - public static class Extensions - { - /// - /// Gets a randomized enum for bias. - /// - /// - /// - public static Enum GetRandomEnumValue(this Type t) - { - return Enum.GetValues(t) // get values from Type provided - .OfType() // casts to Enum - .OrderBy(e => Guid.NewGuid()) // mess with order of results - .FirstOrDefault(); // take first item in result - } - /// - /// Retrieve the static type of type. - /// - /// - /// - public static T Of() - { - if (!typeof(T).IsEnum) - throw new InvalidOperationException("Must use Enum type"); - - Array enumValues = Enum.GetValues(typeof(T)); - return (T)enumValues.GetValue(StaticRandom.Next(enumValues.Length)); - } - /// - /// Determines if the specified value has occurred previously. - /// - /// The value. - /// The previous value. - /// - public static bool HasAppearedBefore(this string value, string lastValue) - { - return value.Contains(lastValue); - } - /// - /// Determines if the specified value has occurred previously. - /// - /// The value. - /// The previous value. - /// - public static bool HasAppearedBefore(this int value, int lastValue) - { - return value.Equals(lastValue); - } - /// - /// Determines whether the specified value is between a minimum-maximum range (inclusive). - /// - /// The value. - /// The minimum. - /// The maximum. - /// If the value is between a minimum and maximum threshold. - public static bool IsBetween(this int value, int minimum, int maximum) - { - return value >= minimum && value <= maximum; - } - /// - /// Returns the properties of the given object as XElements. Properties with null values are still returned, but as empty elements. Underscores in property names are replaces with hyphens. - /// - public static IEnumerable AsXElements(this object source) - { - foreach (PropertyInfo prop in source.GetType().GetProperties()) - { - object value = prop.GetValue(source, null); - yield return new XElement(prop.Name.Replace("_", "-"), value); - } - } - /// - /// Returns the properties of the given object as XElements.Properties with null values are returned as empty attributes. Underscores in property names are replaces with hyphens. - /// - public static IEnumerable AsXAttributes(this object source) - { - foreach (PropertyInfo prop in source.GetType().GetProperties()) - { - object value = prop.GetValue(source, null); - yield return new XAttribute(prop.Name.Replace("_", "-"), value ?? ""); - } - } - // /// - // /// Encrypts the file. - // /// - // /// The input file. - // /// The output file. - // /// The password for encryption. - // /// True if encryption is successful. - // public static bool EncryptFile(this string inputFile, string outputFile, string password) - // { - // try - // { - // Cryptography.EncryptFile(inputFile, outputFile, Base64Tool.Encode(password)); - // return true; - // } - // catch (Exception ex) - // { - // Logging.WriteLog(ex.Message, Logging.LogType.Information, Logging.LogCaller.Cryptography); - // return false; - // } - - - // } - // /// - // /// Decrypts the file. - // /// - // /// The input file. - // /// The output file. - // /// The password for decryption. - // /// True if decryption is successful. - // public static bool DecryptFile(this string inputFile, string outputFile, string password) - // { - // try - // { - // Cryptography.DecryptFile(inputFile, outputFile, Base64Tool.Decode(password)); - // return true; - // } - // catch (Exception ex) - // { - // Logging.WriteLog(ex.Message, Logging.LogType.Information, Logging.LogCaller.Cryptography); - // return false; - // } - // } - - #region boneyard - //public static void EncryptFileOld(this string inputFile, string outputFile, string key, int keysize) - //{ - // try - // { - // //string password = @"myKey123"; // Your Key Here - // UnicodeEncoding encoding = new UnicodeEncoding(); - // byte[] keyBytes = encoding.GetBytes(key); - // string cryptFile = outputFile; - // FileStream fileStreamCrypt = new FileStream(cryptFile, FileMode.Create); - // RijndaelManaged rijnManaged = new RijndaelManaged(); - // CryptoStream cryptoStream = new CryptoStream(fileStreamCrypt, rijnManaged.CreateEncryptor(keyBytes, key), CryptoStreamMode.Write); - // FileStream fileStreamInput = new FileStream(inputFile, FileMode.Open); - - // int data; - // while ((data = fileStreamInput.ReadByte()) != -1) - // cryptoStream.WriteByte((byte)data); - - // fileStreamInput.Close(); - // cryptoStream.Close(); - // fileStreamCrypt.Close(); - // } - // catch (Exception ex) - // { - // Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.Cryptography); - // } - //} - //public static void DecryptFileOld(this string inputFile, string outputFile, string key, int keysize) - //{ - // byte[] ivBytes = null; - // key = key.Base64Decode(); - // switch (keysize / 8) - // { - // // Determine which initialization vector to use. - // case 8: - // ivBytes = Cryptography.Iv8; - // break; - // case 16: - // ivBytes = Cryptography.Iv16; - // break; - // case 24: - // ivBytes = Cryptography.Iv24; - // break; - // case 32: - // ivBytes = Cryptography.Iv32; - // break; - - // } - - // try - // { - // //string password = @"myKey123"; // Your Key Here - // UnicodeEncoding encoding = new UnicodeEncoding(); - - // byte[] keyBytes = encoding.GetBytes(key); - // FileStream fileStreamCrypt = new FileStream(inputFile, FileMode.Open); - // RijndaelManaged rijnManaged = new RijndaelManaged(); - // CryptoStream cryptoStream = new CryptoStream(fileStreamCrypt, rijnManaged.CreateDecryptor(keyBytes, ivBytes), CryptoStreamMode.Read); - // FileStream fileStreamOutput = new FileStream(outputFile, FileMode.Create); - - // int data; - // while ((data = cryptoStream.ReadByte()) != -1) - // fileStreamOutput.WriteByte((byte)data); - - // fileStreamOutput.Close(); - // cryptoStream.Close(); - // fileStreamCrypt.Close(); - // } - // catch (Exception ex) - // { - // Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.Cryptography); - // } - - //} - - #endregion - } -} diff --git a/core/Core/Indications.cs b/core/Core/Indications.cs deleted file mode 100644 index 3bc2e0a..0000000 --- a/core/Core/Indications.cs +++ /dev/null @@ -1,319 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using Boagaphish.ActivationFunctions; -using Boagaphish.Core.Animals; -using Boagaphish.Core.Networks; -using Boagaphish.Numeric; -using Cartheur.Animals.Utilities; -using SweetPolynomial; - -namespace Cartheur.Animals.Core -{ - /// - /// The class responsible for engaging the learning algorithm. - /// - /// USPTO-204-syntax parse initializes this process. - /// 204 leverages 302 - public class Indication - { - /// - /// The indication type. - /// - public enum IndicationType - { - /// - /// The trajectory type. - /// - Trajectory, - /// - /// The emotive type. - /// - Emotive - } - // Core objects. - private bool _needToStop; - private double[] Data { get; set; } - private double[,] Solution { get; set; } - private double[,] Forecast { get; set; } - private int SolutionSize { get; set; } - private BackPropagationNetwork BackPropagationNetwork { get; set; } - private double BackPropagationError { get; set; } - private double BackPropagationMeanError { get; set; } - private ActivationNetwork Activation { get; set; } - private BackPropagation EmotiveNetwork { get; set; } - private List SentenceWeightTrainingData { get; set; } - // Configuration-set properties. - private int SampleSize { get; set; } - /// - /// Gets or sets the iterations. - /// - public int Iterations { get; set; } - private int TrainingCycles { get; set; } - /// - /// Gets or sets the sigmoid alpha function. - /// - public double SigmoidAlpha { get; set; } - private double Momentum { get; set; } - private double LearningRate { get; set; } - private int NumberOfLayers { get; set; } - private int[] LayerSize { get; set; } - private double[][] Bias { get; set; } - private double[][][] Weight { get; set; } - /// - /// Gets or sets the size of the window. - /// - public int WindowSize { get; set; } - private int PredictionSize { get; set; } - private int PredictionSizeTrend { get; set; } - private double Epoch { get; set; } - private double LearningError { get; set; } - private double PredictionError { get; set; } - private double ForecastError { get; set; } - // Created parameters. - private double TrainingRate { get; set; } - private double ErrorTolerance { get; set; } - /// - /// Gets or sets the transfer function. - /// - /// - /// The transfer function. - /// - public TransferFunction TransferFunction { get; set; } - /// - /// Gets or sets the characteristic equation, which governs aeon's behaviour. - /// - /// - /// The characteristic equation. - /// - public string CharacteristicEquation { get; set; } - private Polynomial PolynomialExpression { get; set; } - private double[][] Input { get; set; } - private double[][] Desired { get; set; } - private double NetworkCorrection { get; set; } - private double[] NetworkInput { get; set; } - private int HiddenLayer { get; set; } - private int OutputLayer { get; set; } - /// - /// Initializes a new instance of the class. - /// - /// The transfer function to initialize on. - /// The characteristic equation governing the indication. Can be empty if this feature is not desired. - public Indication(TransferFunction function, string characteristicEquation) - { - TransferFunction = function; - CharacteristicEquation = characteristicEquation; - } - /// - /// Initializes a new instance of the class. - /// - /// The transfer function to initialize on. - /// The polynomial governing the indication. - public Indication(TransferFunction function, Polynomial polynomalExpression) - { - TransferFunction = function; - PolynomialExpression = polynomalExpression; - } - /// - /// Trains the network. - /// - /// Name of the output file. - /// if set to true [save as network file]. - /// - public double TrainNetwork(string outputFileName = "TrajectoryIndicationsTrainingData", bool saveAsNetworkFile = false) - { - // Call the test method to create the data objects. - var dataOperations = new DataOperations(); - dataOperations.CreateTrainingData(CharacteristicEquation); - SentenceWeightTrainingData = dataOperations.SentenceWeightSingle; - Data = SentenceWeightTrainingData.ToArray(); - //Logging.WriteLog(@"Based on the data provided, now training the (solver) network.", Logging.LogType.Information, Logging.LogCaller.AgentCore); - //TrainedNetworkName = outputFileName + XFileType; - // Create performace measure point. - // StartedOn = DateTime.Now; - // Create the network if it does not already exist. - if (BackPropagationNetwork == null) - { - var layerSizes = new[] { WindowSize, WindowSize * 2, 1 }; - var tFuncs = new[] { TransferFunction.None, TransferFunction, TransferFunction.Linear }; - BackPropagationNetwork = new BackPropagationNetwork(layerSizes, tFuncs) { Name = "TrainingIndicationData" }; - } - // Prepare the number of learning samples. What does this dataset consist? - SampleSize = Data.Length - PredictionSize - WindowSize; - Input = new double[SampleSize][]; - Desired = new double[SampleSize][]; - // Loop. - for (var i = 0; i < SampleSize; i++) - { - Input[i] = new double[WindowSize]; - Desired[i] = new double[1]; - // Set the input. - for (var j = 0; j < WindowSize; j++) - { - Input[i][j] = Data[i + j]; - } - // Set the desired values. - Desired[i][0] = Data[i + WindowSize]; - } - // Train the network. - var count = 0; - do - { - // Prepare for training epoch. - count++; - // Train the network. - for (var i = 0; i < Input.Length; i++) - { - BackPropagationError += BackPropagationNetwork.Train(ref Input[i], ref Desired[i], TrainingRate, Momentum); - //TrainingCycles++; - } - BackPropagationMeanError = BackPropagationError / Input.Length; - //Bias = BackPropagationNetwork.Bias; - //Weight = BackPropagationNetwork.Weight; - //Logging.WriteLog(@"Backpropagation error: " + BackPropagationError.ToString(CultureInfo.InvariantCulture), Logging.LogType.Information, Logging.LogCaller.Indications); - - for (var i = 0; i < WindowSize; i++) - { - BackPropagationError += BackPropagationNetwork.Train(ref Input[i], ref Desired[i], TrainingRate, Momentum); - //TrainingCycles++; - - } - BackPropagationMeanError = BackPropagationError / WindowSize; - - //Logging.WriteLog(@"Backpropagation residuals: " + BackPropagationError.ToString(CultureInfo.InvariantCulture), Logging.LogType.Information, Logging.LogCaller.Indications); - - } while (BackPropagationError > ErrorTolerance && count <= TrainingCycles); - - //if (saveAsNetworkFile) - //BackPropagationNetwork.SaveNetworkXml(Environment.CurrentDirectory + @"\data\networks\" + TrainedNetworkName); - // Record performance vectors for the operation. - //SolverTrainingDone = true; - //Duration = DateTime.Now - StartedOn; - //Logging.WriteLog("Solver training processing time: " + Duration.Seconds + @"." + Duration.Milliseconds.ToString(CultureInfo.InvariantCulture), Logging.LogType.Statistics, Logging.LogCaller.AgentCore); - - return BackPropagationMeanError; - } - /// - /// Searches the appropriate solution for the given inputs. - /// - /// - public double[,] SearchSolution() - { - _needToStop = false; - //_workerThread = new Thread(SearchSolution) { Name = "SearchSolution Thread" }; - //StartedOn = DateTime.Now; - // Set the network properties. - HiddenLayer = WindowSize * 2; - OutputLayer = 1; - // Implement data transformation factors for the chart. - var factor = 1.7 / 0.00405499999999992; - var yMin = 0.852045; - NetworkInput = new double[WindowSize]; - - for (var i = 0; i < SampleSize; i++) - { - for (var j = 0; j < WindowSize; j++) - { - Input[i][j] = (Data[i + j] - yMin) * factor - NetworkCorrection; - } - - Desired[i][0] = (Data[i + WindowSize] - yMin) * factor - NetworkCorrection; - } - // Todo: Add the new code to the Bph library starting at these points below. - switch (TransferFunction.ToString()) - { - case "BipolarSigmoid": - Activation = new ActivationNetwork(new BipolarSigmoidFunction(SigmoidAlpha), WindowSize, HiddenLayer, OutputLayer); - break; - case "Gaussian": - break; - case "Linear": - break; - case "NormalizedExponent": - break; - case "RationalSigmoid": - break; - case "Sigmoid": - Activation = new ActivationNetwork(new SigmoidFunction(SigmoidAlpha), WindowSize, HiddenLayer, OutputLayer); - break; - case "VanderPol": - break; - } - NumberOfLayers = 2; - LayerSize = new int[NumberOfLayers]; - LayerSize[0] = HiddenLayer; - LayerSize[1] = OutputLayer; - // One set of classes containing activation functions, from the first iteration of this code. - EmotiveNetwork = new BackPropagation(Activation) { LearningRate = LearningRate, Momentum = Momentum }; - // This is here but have no historical trace. What send an array of zeros to the algorithm? - Activation.Compute(NetworkInput); // This is an array of zeros. Can we feed the algorithm's correction here? - LearningError += Math.Abs(Data[1] - ((Activation.Compute(NetworkInput)[0] + NetworkCorrection) / factor + yMin)); - // Iterations. - var iteration = 1; - // Solution array. - SolutionSize = Data.Length - WindowSize; - Solution = new double[SolutionSize, 2]; - var solution = new double[SolutionSize, 2]; - // Calculate x-values to be used with solution function. - for (var j = 0; j < SolutionSize; j++) - { - Solution[j, 0] = j + WindowSize; - } - // Loop. - while (!_needToStop) - { - // Run epoch of learning procedure. - Epoch = EmotiveNetwork.RunEpoch(Input, Desired) / SampleSize; - // Introduce data scaling. - var scaleReduction = 0.1 * Data.Length;// <-- Nofucking way, not here! - // Calculate solution, learning, and prediction errors by iterating the data. - for (int i = 0, n = (int)scaleReduction - WindowSize; i < n; i++) - { - // Assign values from current window as network's input. - for (var j = 0; j < WindowSize; j++) - { - NetworkInput[j] = (Data[i + j] - yMin) * factor - NetworkCorrection; - // Evaluate the function. - // solution[i, 1] = (Activation.Compute(NetworkInput)[i] + NetworkCorrection) / factor + yMin; - } - //var hold = 0; - // Evaluate the function. - // solution[i, 1] = (NetworkInput[i] + NetworkCorrection) / (factor + yMin); - var sum = Activation.Compute(NetworkInput); - solution[i, 1] = (sum[0] + NetworkCorrection); - Solution = solution; - // Truncate to a pre-chosen set of decimal places. - // solution[i, 1] = Math.Round(Solution[i, 1], TrailingDigits); - // Compute the prediction and learning error. - if (i >= n - PredictionSizeTrend) - { - PredictionError += Math.Abs(Solution[i, 1] - Data[WindowSize + i]); - } - else - { - LearningError += Math.Abs(Solution[i, 1] - Data[WindowSize + i]); - } - } - // Set the dataset maximum and minimum values. - //DataMagnitudeUpper = Data.Max(); - //DataMagnitudeLower = Data.Min(); - // Increase the current iteration. - iteration++; - // Check if we need to stop. - if ((Iterations != 0) && (iteration > Iterations)) - { - //_workerThread.Abort(); - _needToStop = true; - //break; - } - } - // Record performance vectors for the operation and logfile. - //Duration = DateTime.Now - StartedOn; - //Logging.WriteLog("Neural network processed its given task in " + Duration.Seconds + @"." + Duration.Milliseconds + " seconds", Logging.LogType.Statistics, Logging.LogCaller.AgentCore); - //Logging.WriteLog("Program metrics: At an epoch of " + Epoch + ", " + Iterations + " iterations, " + LearningRate + " learning rate, " + PredictionSizeTrend + " prediction size for the trend computation; a sigmoid alpha value of " + SigmoidAlpha + " and a momentum of " + Momentum + " resulting in a learning error of " + LearningError + " and a prediction error of " + PredictionError, Logging.LogType.Statistics, Logging.LogCaller.AgentCore); - return Solution; - } - } -} diff --git a/core/Core/MatchState.cs b/core/Core/MatchState.cs deleted file mode 100644 index beb6310..0000000 --- a/core/Core/MatchState.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Cartheur.Animals.Core -{ - /// - /// Denotes what part of the input path a node represents. - /// - /// - /// Used when pushing values represented by wildcards onto collections for the star, thatstar, emotion, and topicstar values. - /// - public enum MatchState - { - /// - /// The user input state. - /// - UserInput, - /// - /// The that state. - /// - That, - /// - /// The topic state. - /// - Topic, - /// - /// The emotion state. - /// - Emotion - } -} diff --git a/core/Core/Mood.cs b/core/Core/Mood.cs deleted file mode 100644 index 3652496..0000000 --- a/core/Core/Mood.cs +++ /dev/null @@ -1,498 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; -using SweetPolynomial; - -namespace Cartheur.Animals.Personality -{ - // Emotions which can be expressed by the program. - /// - /// The set of emotions the aeon can experience. - /// - public enum Emotions { Happy, Confident, Energized, Helped, Insecure, Sad, Hurt, Tired } - /// - /// The set of emotions the aeon can recognize. - /// - public enum UserEmotions { Angry, Happy, Neutral, Sad } - // Subsets of these emotions. Parent is a feeling while the child is the mood. - /// - /// The subset emotions containing happy feelings. - /// - public enum HappyFeelings { Hopeful, Supported, Charmed, Grateful, Optimistic, Content, Loving } - /// - /// The subset emotions containing confident feelings. - /// - public enum ConfidentFeelings { Strong, Certain, Assured, Successful, Valuable, Beautiful, Relaxed } - /// - /// The subset emotions containing energized feelings. - /// - public enum EnergizedFeelings { Determined, Inspired, Creative, Healthy, Vibrant, Alert, Motivated } - /// - /// The subset emotions containing helped feelings. - /// - public enum HelpedFeelings { Cherished, Befriended, Appreciated, Understood, Empowered, Accepted, Loved } - /// - /// The subset emotions containing insecure feelings. - /// - public enum InsecureFeelings { Weak, Hopeless, Doubtful, Scared, Anxious, Stressed, Nervous } - /// - /// The subset emotions containing sad feelings. - /// - public enum SadFeelings { Depressed, Lonely, Angry, Frustrated, Upset, Disappointed, Hateful } - /// - /// The subset emotions containing hurt feelings. - /// - public enum HurtFeelings { Forgotten, Ignored, Offended, Rejected, Hated, Mistreated, Injured } - /// - /// The subset emotions containing tired feelings. - /// - public enum TiredFeelings { Indifferent, Bored, Sick, Weary, Powerless, Listless, Drained } - /// - /// The class which manifests the mood of the program. - /// - public class Mood - { - /// - /// The aeon that is experiencing the emotion. - /// - public Aeon ThisAeon; - /// - /// The user that is associated with this aeon. - /// - public User ThisUser; - /// - /// Gets or sets the characteristic equation, which governs aeon's behaviour. - /// - /// - /// The characteristic equation. - /// - public string CharacteristicEquation { get; set; } - /// - /// Gets or sets the polynomial expression used by the mood engine. - /// - private Polynomial MoodPolynomial { get; set; } - /// - /// The derivative of the mood polynomial. - /// - public Polynomial PolynomialDerivative { get; set; } - /// - /// The roots of the mood polynomial. - /// - public Complex[] PolynomialRoots { get; set; } - /// - /// Gets or sets the seed value for the mood engine randomizer. - /// - public int SeedValue { get; set; } - /// - /// Gets or sets the current mood of aeon. - /// - public static string CurrentMood { get; set; } - /// - /// Gets or sets a value indicating whether [in love]. - /// - /// - /// true if [in love]; otherwise, false. - /// - public static bool InLove { get; set; } - /// - /// Gets or sets a value indicating whether [intimate relationship]. - /// - /// - /// true if [intimate relationship]; otherwise, false. - /// - public static bool IntimateRelationship { get; set; } - /// - /// Gets or sets a value indicating whether [friendly relationship]. - /// - /// - /// true if [friendly relationship]; otherwise, false. - /// - public static bool FriendlyRelationship { get; set; } - /// - /// Gets or sets a value indicating whether [neutral relationship]. - /// - /// - /// true if [neutral relationship]; otherwise, false. - /// - public static bool NeutralRelationship { get; set; } - /// - /// Gets or sets a value indicating whether [unfriendly relationship]. - /// - /// - /// true if [unfriendly relationship]; otherwise, false. - /// - public static bool UnfriendlyRelationship { get; set; } - // For the next iteration of this implementation. - /// - /// Gets or sets a value indicating whether [affection detect]. - /// - /// - /// true if [affection detect]; otherwise, false. - /// - protected static bool AffectionDetect { get; set; } - private static int AboutMe { get; set; } - /// - /// Gets or sets the emotive indication. - /// - public Indication EmotiveIndication { get; set; } - /// - /// Gets or sets the training error output from the indication computation. - /// - public double TrainingError { get; private set; } - private double[,] EmotiveIndicationValue { get; set; } - // The values for a random determination of mood. - private static int WheelSpun { get; set; } - private static int NextWheelPosition { get; set; } - /// - /// The limit of the randomizer. - /// - protected const int Limit = 20; - /// - /// Collects points for insult detection. - /// - /// Emotional variety: the emotional weights. - public static int Insult { get; set; } - /// - /// Collects points for dislike detection. - /// - /// Emotional variety: the emotional weights. - public static int Dislike { get; set; } - /// - /// Collects points for neutral detection. - /// - /// Emotional variety: the emotional weights. - public static int Neutral { get; set; } - /// - /// Collects points for compliment detection. - /// - /// Emotional variety: the emotional weights. - public static int Compliment { get; set; } - /// - /// Collects points for love detection. - /// - /// Emotional variety: the emotional weights. - public static int Love { get; set; } - /// - /// Collects points for annoyance detection. - /// - /// Variety variables for cases of repetition or uncharacteristic input from the user. - public static int Annoy { get; set; } - /// - /// Collects points for shocking detection. - /// - /// Variety variables for cases of repetition or uncharacteristic input from the user. - public static int Shock { get; set; } - /// - /// Sets the emotional bias on mood creation. - /// - /// Randomly determined - public Emotions EmotionBias { get; set; } - /// - /// Initializes a new instance of the class. Allows the program to express emotional variety to the user. - /// - /// The seed value which controls random emotional expressions. Value should be between 0 and 20. - /// The aeon the emotion is attached to. - /// The characteristic equation for the emotive. - /// This section of code contains what is called the "mood engine". The mood engine is designed, via the class, that low seed values perpetuate the happy moods, mid-range sadness (insecurity), and upper-range the more anti-social moods. - public Mood(int seedValue, Aeon thisAeon, string emotiveEquation) - { - ThisAeon = thisAeon; - CharacteristicEquation = emotiveEquation; - SeedValue = seedValue; - EstablishMood(); - CheckIfInLove(); - ReturnIndication();// Here is where it will be interesting to extrapolate behaviour from code architecture abstractions. - } - /// - /// Initializes a new instance of the class. Allows the program to express emotional variety to the user. - /// - /// The seed value which controls random emotional expressions. Value should be between 0 and 20. - /// The aeon the emotion is attached to. - /// The user that is attached to the aeon. - /// The characteristic equation for the emotive. - /// This section of code contains what is called the "mood engine". The mood engine is designed, via the class, that low seed values perpetuate the happy moods, mid-range sadness (insecurity), and upper-range the more anti-social moods. - public Mood(int seedValue, Aeon thisAeon, User thisUser, string emotiveEquation, Emotions bias) - { - ThisAeon = thisAeon; - ThisUser = thisUser; - CharacteristicEquation = emotiveEquation; - SeedValue = seedValue; - //EmotionBias = Extensions.Of(); - InterpretUserEmotion(); - EstablishMood(); - CheckIfInLove(); - ReturnIndication();// Here is where it will be interesting to extrapolate behaviour from code architecture abstractions. - } - /// - /// Interpret the user's emotion from the file. An asterisk (*) is the default setting (neutral or undetectable). - /// - private void InterpretUserEmotion() - { - switch (ThisUser.Predicates.GrabSetting("emotion")) - { - case "*": - ThisUser.Emotion = UserEmotions.Neutral.ToString(); - break; - case "0": - ThisUser.Emotion = UserEmotions.Angry.ToString(); - break; - case "1": - ThisUser.Emotion = UserEmotions.Happy.ToString(); - break; - case "2": - ThisUser.Emotion = UserEmotions.Sad.ToString(); - break; - } - } - // Switches to determine class behaviour. - /// - /// Gets or sets a value indicating whether [store data] regarding the emotion. - /// - /// - /// true if [store data]; otherwise, false. - /// - public static bool StoreData { get; set; } - /// - /// Records the relationship outcome between the aeon and the user. - /// - /// The sentence being analyzed. - /// Method used to construct the dataset. This is a file posited to the dataset directory. - public void RelationshipOutcome(string sentence) - { // Start with tones. - if (sentence.Contains("how are you")) - { - AboutMe++; - Compliment++; - } - if (sentence.Contains("I think")) - { - - } - if (sentence.Contains("do you")) - { - AboutMe++; - } - // Collect the instance variables of the sentence utterances. - if (Compliment >= 10 && Love > 5) - IntimateRelationship = true; - if (Compliment.IsBetween(1, 9) & Love.IsBetween(1, 3)) - FriendlyRelationship = true; - if (Compliment == 0 & Love == 0) - NeutralRelationship = true; - if (Compliment < 0 && Love < 0) - UnfriendlyRelationship = true; - - DataOperations.StoreTrainingSet(ThisAeon); - - } - /// - /// Changes the mood of aeon. - /// - /// The mood resulting from detecting emotional triggers from a that. - /// What happens at each mood to those parts of the program when it is changed (for some reason)? - public void UpdateMood(Emotions mood) - { - switch (mood) - { - case Emotions.Confident: - CurrentMood = Emotions.Confident.ToString(); - Love = Love + 1; - Neutral = Neutral + 1; - Compliment = Compliment + 1; - ReturnIndication(); - break; - case Emotions.Energized: - CurrentMood = Emotions.Energized.ToString(); - Neutral = Neutral + 1; - Love = Love + 1; - ReturnIndication(); - break; - case Emotions.Hurt: - CurrentMood = Emotions.Hurt.ToString(); - Love = Love - 1; - Neutral = Neutral - 1; - Compliment = Compliment - 1; - Dislike = Dislike + 2; - Insult = Insult + 2; - ReturnIndication(); - break; - case Emotions.Happy: - CurrentMood = Emotions.Happy.ToString(); - Love = Love + 2; - Compliment = Compliment + 2; - ReturnIndication(); - break; - case Emotions.Helped: - CurrentMood = Emotions.Helped.ToString(); - Neutral = Neutral + 1; - Compliment = Compliment + 1; - ReturnIndication(); - break; - case Emotions.Insecure: - CurrentMood = Emotions.Insecure.ToString(); - Love = Love - 1; - Neutral = Neutral + 1; - Dislike = Dislike + 1; - ReturnIndication(); - break; - case Emotions.Sad: - CurrentMood = Emotions.Sad.ToString(); - Love = Love - 1; - Neutral = Neutral - 1; - Dislike = Dislike + 1; - Insult = Insult + 1; - ReturnIndication(); - break; - case Emotions.Tired: - CurrentMood = Emotions.Tired.ToString(); - Neutral = Neutral - 1; - Compliment = Compliment + 1; - ReturnIndication(); - break; - } - } - /// - /// Changes the mood of the aeon. - /// - public void ChangeMood() - { - CurrentMood = ""; - SeedValue = StaticRandom.Next(0, Limit); - EstablishMood(); - } - /// - /// Gets the current mood. - /// - /// - public string GetCurrentMood() - { - return CurrentMood; - } - /// - /// Establishes the mood of the aeon. - /// - public void EstablishMood() - { - //if (seedValue > Limit) return; - WheelSpun = StaticRandom.Next(0, Limit); - NextWheelPosition = new Random(SeedValue).Next(Limit); - // Emotional variety: a simple implementation. - if (NextWheelPosition.IsBetween(0, 5) & WheelSpun.IsBetween(11, Limit)) - { - CurrentMood = Emotions.Confident.ToString(); - Love = Love + 1; - Neutral = Neutral + 1; - Compliment = Compliment + 1; - } - if (NextWheelPosition.IsBetween(6, 15) & WheelSpun.IsBetween(0, 10)) - { - CurrentMood = Emotions.Energized.ToString(); - Neutral += 1; - Love = Love + 1; - } - if (NextWheelPosition.IsBetween(0, 5) & WheelSpun.IsBetween(0, 10)) - { - CurrentMood = Emotions.Happy.ToString(); - Love = Love + 2; - Compliment = Compliment + 2; - } - if (NextWheelPosition.IsBetween(6, 15) & WheelSpun.IsBetween(11, Limit)) - { - CurrentMood = Emotions.Helped.ToString(); - Neutral = Neutral + 1; - Compliment = Compliment + 1; - } - if (NextWheelPosition.IsBetween(16, Limit) & WheelSpun.IsBetween(11, Limit)) - { - CurrentMood = Emotions.Hurt.ToString(); - Love = Love - 1; - Neutral = Neutral - 1; - Compliment = Compliment - 1; - Dislike = Dislike + 2; - Insult = Insult + 2; - } - if (NextWheelPosition.IsBetween(16, Limit) & WheelSpun.IsBetween(0, 5)) - { - CurrentMood = Emotions.Insecure.ToString(); - Love = Love - 1; - Neutral = Neutral + 1; - Dislike = Dislike + 1; - } - if (NextWheelPosition.IsBetween(16, Limit) & WheelSpun.IsBetween(0, 10)) - { - CurrentMood = Emotions.Happy.ToString(); - Love -= 1; - Neutral -= 1; - Dislike += 1; - Insult += 1; - } - if (NextWheelPosition.IsBetween(0, Limit) & WheelSpun.IsBetween(16, Limit)) - { - CurrentMood = Emotions.Tired.ToString(); - Neutral = Neutral - 1; - Compliment = Compliment + 1; - } - } - /// - /// Checks if aeon is in love. - /// - public bool CheckIfInLove() - { - if (Love > 10) - return InLove = true; - if (ThisUser.Emotion == Emotions.Happy.ToString()) - return InLove = true; - return InLove = false; - } - /// - /// Return the (emotive) indication. - /// - /// Trajectory indication in , emotive indication here. - public void ReturnIndication() - { - // Using a simple polynomial expression to create maps in the "brain" and assign it either an emotive or trajectory indication. - EmotiveIndication = new Indication(Boagaphish.Numeric.TransferFunction.BipolarSigmoid, EmotivePolynomial()) - { - WindowSize = Convert.ToInt32(ThisAeon.GlobalSettings.GrabSetting("windowsize")), - SigmoidAlpha = Convert.ToDouble(ThisAeon.GlobalSettings.GrabSetting("sigmoidalpha")), - Iterations = Convert.ToInt32(ThisAeon.GlobalSettings.GrabSetting("iterations")) - }; - // NOTE: Using an aggressive solution search for the trajectory indication. - TrainingError = EmotiveIndication.TrainNetwork(); - // Assign default values to the emotive indication. Non-GPU. - EmotiveIndicationValue = new double[EmotiveIndication.Iterations - EmotiveIndication.WindowSize, 2]; - EmotiveIndicationValue = EmotiveIndication.SearchSolution(); - } - /// - /// I think a solution is to cast a characteristic polynomial in the space given by the trajectory, the x-axis in a virtual space. - /// - public Polynomial TrajectoryPolynomial() - { - MoodPolynomial = new Polynomial(CharacteristicEquation); - var polynomial = MoodPolynomial.LocalPolynomial; - return polynomial; - } - /// - /// I think a solution is to cast a characteristic polynomial in the space given by the emotive, the y-axis in a virtual space. - /// - public Polynomial EmotivePolynomial() - { - MoodPolynomial = new Polynomial(CharacteristicEquation); - var polynomial = MoodPolynomial.LocalPolynomial; - return polynomial; - } - /// - /// Gets the current mood polynomial. - /// - /// - public string ReturnMoodPolynomialProperties() - { - PolynomialRoots = PolynomialProperties.Roots; - PolynomialDerivative = PolynomialProperties.Derivative; - return MoodPolynomial.LocalPolynomial.ToString(); - } - } -} diff --git a/core/Core/Node.cs b/core/Core/Node.cs deleted file mode 100644 index bb40ed6..0000000 --- a/core/Core/Node.cs +++ /dev/null @@ -1,277 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Text; -using System.Xml; -using Cartheur.Animals.Normalize; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.Core -{ - /// - /// Encapsulates a node in the brain's tree structure. - /// - [Serializable] - public class Node - { - /// - /// Contains the child nodes of this node. - /// - private readonly Dictionary _children = new Dictionary(); - /// - /// The number of direct children (non-recursive) of this node. - /// - public int NumberOfChildNodes - { - get - { - return _children.Count; - } - } - /// - /// The template (if any) associated with this node. - /// - public string Template = string.Empty; - /// - /// The aeon source for the category that defines the template. - /// - public string Filename = string.Empty; - /// - /// The word that identifies this node to its parent node. - /// - public string Word = string.Empty; - /// - /// Adds a category to the node. - /// - /// The path for the category. - /// The template to find at the end of the path. - /// The file that was the source of this category. - public void AddCategory(string trajectory, string template, string filename) - { - if (template.Length == 0) - { - throw new XmlException("The category with a pattern: " + trajectory + " found in file: " + filename + " has an empty template tag."); - } - - // Check we're not at the leaf node. - if (trajectory.Trim().Length == 0) - { - Template = template; - Filename = filename; - return; - } - // Otherwise, this sentence requires further child nodemappers in order to be fully mapped within the program's structure. - // Split the input into its component words. - string[] words = trajectory.Trim().Split(" ".ToCharArray()); - // Get the first word (to form the key for the child nodemapper). - string firstWord = MakeCaseInsensitive.TransformInput(words[0]); - // Concatenate the rest of the sentence into a suffix (to act as the path argument in the child nodemapper). - string newTrajectory = trajectory.Substring(firstWord.Length, trajectory.Length - firstWord.Length).Trim(); - // Check we don't already have a child with the key from this sentence. If we do then pass the handling of this sentence down the branch to the child nodemapper otherwise the child nodemapper doesn't yet exist, so create a new one. - if (_children.ContainsKey(firstWord)) - { - Node childNode = _children[firstWord]; - childNode.AddCategory(newTrajectory, template, filename); - } - else - { - Node childNode = new Node {Word = firstWord}; - childNode.AddCategory(newTrajectory, template, filename); - _children.Add(childNode.Word, childNode); - } - } - /// - /// Navigates this node (and recusively into child nodes) for a match to the path passed as an argument while processing the referenced request. - /// - /// The normalized path derived from the user's input. - /// The query that this search is for. - /// An encapsulation of the request from the user. - /// The part of the input path the node represents. - /// The contents of the user input absorbed by wildcards "_" and "*". - /// The template to process to generate the output. - public string Evaluate(string trajectory, SubQuery query, Request request, MatchState matchstate, StringBuilder wildcard) - { - while (true) - { - // Check for timeout. - if (request.StartedOn.AddMilliseconds(request.ThisAeon.TimeOut) < DateTime.Now) - { - Logging.WriteLog("Request timeout. User: " + request.ThisUser.UserName + " raw input: \"" + request.RawInput + "\"", Logging.LogType.Warning, Logging.LogCaller.Node); - request.HasTimedOut = true; - return string.Empty; - } - // We still have time. - trajectory = trajectory.Trim(); - // Check if this is the end of a branch and return the Category for this node. - if (_children.Count == 0) - { - if (trajectory.Length > 0) - { - // If we get here it means that there is a wildcard in the user input part of the path. - StoreWildCard(trajectory, wildcard); - } - return Template; - } - // If we've matched all the words in the input sentence and this is the end of the line then return the Category for this node. - if (trajectory.Length == 0) - { - return Template; - } - // Otherwise split the input into its component words. - string[] splitTrajectory = trajectory.Split(" \r\n\t".ToCharArray()); - // Get the first word of the sentence. - string firstWord = MakeCaseInsensitive.TransformInput(splitTrajectory[0]); - // And concatenate the rest of the input into a new path for child nodes. - string newTrajectory = trajectory.Substring(firstWord.Length, trajectory.Length - firstWord.Length); - // First option is to see if this node has a child denoted by the "_" wildcard. "_" comes first in precedence in the alphabet. - if (_children.ContainsKey("_")) - { - // Look for the path in the child node denoted by "_". - Node childNode = _children["_"]; - // Add the next word to the wildcard match. - StringBuilder newWildcard = new StringBuilder(); - StoreWildCard(splitTrajectory[0], newWildcard); - // Move down into the identified branch of the structure. - string result = childNode.Evaluate(newTrajectory, query, request, matchstate, newWildcard); - // And if we get a result from the branch process the wildcard matches and return the result. - if (result.Length > 0) - { - if (newWildcard.Length > 0) - { - // Capture and push the star content appropriate to the current matchstate. - switch (matchstate) - { - case MatchState.UserInput: - query.InputStar.Add(newWildcard.ToString()); - // Added due to this match being the end of the line. - newWildcard.Remove(0, newWildcard.Length); - break; - case MatchState.That: - query.ThatStar.Add(newWildcard.ToString()); - break; - case MatchState.Topic: - query.TopicStar.Add(newWildcard.ToString()); - break; - case MatchState.Emotion: - query.EmotionStar.Add(newWildcard.ToString()); - break; - } - } - return result; - } - } - // Second option - the nodemapper may have contained a "_" child, but led to no match or it didn't contain a "_" child at all. So get the child nodemapper from this nodemapper that matches the first word of the input sentence. - if (_children.ContainsKey(firstWord)) - { - // Process the matchstate - this might not make sense but the matchstate is working with a "backwards" path: "topic that user input" the "classic" path looks like this: "user input that topic" but having it backwards is more efficient for searching purposes. - MatchState newMatchState = matchstate; - if (firstWord == "") - { - newMatchState = MatchState.That; - } - else if (firstWord == "") - { - newMatchState = MatchState.Topic; - } - else if (firstWord == "") - { - newMatchState = MatchState.Emotion; - } - // Look for the path in the child node denoted by the first word. - Node childNode = _children[firstWord]; - // Move down into the identified branch of the root structure using the new MatchState. - StringBuilder newWildcard = new StringBuilder(); - string result = childNode.Evaluate(newTrajectory, query, request, newMatchState, newWildcard); - // And if we get a result from the child return it. - if (result.Length > 0) - { - if (newWildcard.Length > 0) - { - // Capture and push the star content appropriate to the matchstate if it exists and then clear it for subsequent wildcards. - switch (matchstate) - { - case MatchState.UserInput: - query.InputStar.Add(newWildcard.ToString()); - newWildcard.Remove(0, newWildcard.Length); - break; - case MatchState.That: - query.ThatStar.Add(newWildcard.ToString()); - newWildcard.Remove(0, newWildcard.Length); - break; - case MatchState.Topic: - query.TopicStar.Add(newWildcard.ToString()); - newWildcard.Remove(0, newWildcard.Length); - break; - case MatchState.Emotion: - query.EmotionStar.Add(newWildcard.ToString()); - newWildcard.Remove(0, newWildcard.Length); - break; - } - } - return result; - } - } - // Third option - the input part of the path might have been matched so far but hasn't returned a match, so check to see it contains the "*" wildcard. "*" comes last in precedence in the alphabet. - if (_children.ContainsKey("*")) - { - // Look for the path in the child node denoted by "*". - Node childNode = _children["*"]; - // Add the next word to the wildcard match. - StringBuilder newWildcard = new StringBuilder(); - StoreWildCard(splitTrajectory[0], newWildcard); - string result = childNode.Evaluate(newTrajectory, query, request, matchstate, newWildcard); - // And if we get a result from the branch process and return it. - if (result.Length > 0) - { - if (newWildcard.Length > 0) - { - // Capture and push the star content appropriate to the current matchstate. - switch (matchstate) - { - case MatchState.UserInput: - query.InputStar.Add(newWildcard.ToString()); - // Added due to this match being the end of the line. - newWildcard.Remove(0, newWildcard.Length); - break; - case MatchState.That: - query.ThatStar.Add(newWildcard.ToString()); - break; - case MatchState.Topic: - query.TopicStar.Add(newWildcard.ToString()); - break; - case MatchState.Emotion: - query.EmotionStar.Add(newWildcard.ToString()); - break; - } - } - return result; - } - } - // If the nodemapper has failed to match at all: the input contains neither a "_", the FirstWord text, or "*" as a means of denoting a child node. However, if this node is itself representing a wildcard then the search continues to be valid if we proceed with the tail. - if ((Word == "_") || (Word == "*")) - { - StoreWildCard(splitTrajectory[0], wildcard); - trajectory = newTrajectory; - continue; - } - // If we get here then we're at a dead end so return an empty string. Hopefully, if the aeon code files have been set up to include a " * * * * " catch-all this state won't be reached. Remember to empty the surplus to requirements wildcard matches wildcard = new StringBuilder(); - return string.Empty; - } - } - /// - /// Correctly stores a word in the wildcard slot. - /// - /// The word matched by the wildcard. - /// The contents of the user input absorbed by wildcards "_" and "*". - private static void StoreWildCard(string word, StringBuilder wildcard) - { - if (wildcard.Length > 0) - { - wildcard.Append(" "); - } - wildcard.Append(word); - } - } -} diff --git a/core/Core/Request.cs b/core/Core/Request.cs deleted file mode 100644 index b2ba84f..0000000 --- a/core/Core/Request.cs +++ /dev/null @@ -1,51 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Cartheur.Animals.Core -{ - /// - /// Encapsulates information about a request sent to aeon for processing. - /// - public class Request - { - /// - /// The raw input from the user. - /// - public string RawInput; - /// - /// The time at which this request was created within the system. - /// - public DateTime StartedOn; - /// - /// The user who made this request. - /// - public User ThisUser; - /// - /// The aeon to which the request is being made. - /// - public Aeon ThisAeon; - /// - /// The final result produced by this request. - /// - public Result UserResult; - /// - /// Flag to show that the request has timed out. - /// - public bool HasTimedOut = false; - /// - /// Initializes a new instance of the class. - /// - /// The raw input from the user. - /// The user who made the request. - /// The presence for this request. - public Request(string rawInput, User thisUser, Aeon thisAeon) - { - RawInput = rawInput; - ThisUser = thisUser; - ThisAeon = thisAeon; - StartedOn = DateTime.Now; - } - } -} diff --git a/core/Core/Result.cs b/core/Core/Result.cs deleted file mode 100644 index ec6bf2c..0000000 --- a/core/Core/Result.cs +++ /dev/null @@ -1,176 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Text; -using Cartheur.Animals.Personality; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.Core -{ - /// - /// Encapsulates information about the result of a request to the mind. - /// - public class Result - { - /// - /// The user's aeon that is providing the answer. - /// - public Aeon ThisAeon; - /// - /// The user for whom this is a result. - /// - public User ThisUser; - /// - /// The request from the user which contains user input. - /// - public Request UserRequest; - /// - /// The normalized sentence(s) (paths) fed into the brain. - /// - public List NormalizedTrajectories = new List(); - /// - /// Gets or sets the equation trajectory. - /// - /// - /// The equation trajectory. - /// - public string EquationTrajectory { get; set; } - /// - /// The amount of time the request took to process. - /// - public TimeSpan Duration; - /// - /// The last message time. - /// - public DateTime LastMessageTime; - /// - /// Something which helps the program evolve as it follows Boagaphish processing. - /// - public Indication TrajectoryIndication { get; set; } - /// - /// Gets or sets the trajectory indication value. - /// - /// - /// The trajectory indication value. - /// - public double[,] TrajectoryIndicationValue { get; set; } - /// - /// The result from the presence including logging and checking. - /// - public string Output - { - get - { - if (OutputSentences.Count > 0) - { - return RawOutput; - } - if (UserRequest.HasTimedOut) - { - return ThisAeon.TimeOutMessage; - } - StringBuilder trajectories = new StringBuilder(); - foreach (string pattern in NormalizedTrajectories) - { - trajectories.Append(pattern + "\r\n"); - } - LastMessageTime = DateTime.Now; - ThisAeon.ErrorState = true; - Logging.WriteLog("Program error. Output is completely empty, which indicates there is no path for the query. You said: \"" + UserRequest.RawInput + "\". The path is: " + trajectories, Logging.LogType.Warning, Logging.LogCaller.Result); - - return string.Empty; - } - } - /// - /// Returns the raw sentences. This method is depreciated. - /// - public string RawOutput - { - get - { - StringBuilder result = new StringBuilder(); - foreach (string sentence in OutputSentences) - { - string sentenceForOutput = sentence.Trim(); - if (!CheckEndsAsSentence(sentenceForOutput)) - { - sentenceForOutput += "."; - } - result.Append(sentenceForOutput + " "); - LastMessageTime = DateTime.Now; - } - return result.ToString(); - } - } - /// - /// The SubQuery objects processed by the brain which contain the templates that are to be converted into the collection of Sentences. - /// - public List SubQueries = new List(); - /// - /// The individual sentences produced by the brain that form the complete response. - /// - public List OutputSentences = new List(); - /// - /// The individual sentences that constitute the raw input from the user. - /// - public List InputSentences = new List(); - /// - /// Initializes a new instance of the class. - /// - /// The user for whom this is a result. - /// The brain providing the result. - /// The request that originated this result. - /// The characteristic equation for the trajectory. - public Result(User thisUser, Aeon aeon, Request userRequest, string trajectoryEquation) - { - ThisUser = thisUser; - ThisAeon = aeon; - UserRequest = userRequest; - UserRequest.UserResult = this; - EquationTrajectory = trajectoryEquation; - } - /// - /// Returns the raw output from the brain. - /// - /// The raw output from the brain. - public override string ToString() - { - return Output; - } - /// - /// Checks that the provided sentence ends with a sentence splitter. - /// - /// The sentence to check. - /// True if ends with an appropriate sentence splitter. - private bool CheckEndsAsSentence(string sentence) - { - foreach (string splitter in ThisAeon.Splitters) - { - if (sentence.Trim().EndsWith(splitter)) - { - return true; - } - } - return false; - } - /// - /// Returns the trajectory indication. - /// - /// Emotive indication in , trajectory indication here. - public void ReturnIndication() - { - TrajectoryIndication = new Indication(Boagaphish.Numeric.TransferFunction.BipolarSigmoid, EquationTrajectory) - { - WindowSize = Convert.ToInt32(ThisAeon.GlobalSettings.GrabSetting("windowsize")), - Iterations = Convert.ToInt32(ThisAeon.GlobalSettings.GrabSetting("iterations")) - }; - // Using a simple polynomial expression to create maps in the "brain". - //TrajectoryIndication.TrajectoryPolynomial(); - // Using an aggressive solution search for the trajectory indication. - //var trainingError = TrajectoryIndication.TrainNetwork(); - //TrajectoryIndicationValue = TrajectoryIndication.SearchSolution(); - } - } -} diff --git a/core/Core/SettingsDictionary.cs b/core/Core/SettingsDictionary.cs deleted file mode 100644 index 0edd8d1..0000000 --- a/core/Core/SettingsDictionary.cs +++ /dev/null @@ -1,245 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; -using System.IO; -using System.Xml; -using Cartheur.Animals.Normalize; - -namespace Cartheur.Animals.Core -{ - /// - /// A dictionary for loading, adding, checking, removing, and extracting settings. - /// - public class SettingsDictionary - { - /// - /// Holds a dictionary of settings. - /// - private readonly Dictionary _settingsHash = new Dictionary(); - /// - /// Contains an ordered collection of all the keys. - /// - private readonly List _orderedKeys = new List(); - /// - /// The presence this dictionary is associated with. - /// - protected Aeon TheAeon; - /// - /// The number of items in the dictionary. - /// - public int Count - { - get - { - return _orderedKeys.Count; - } - } - /// - /// An xml representation of the contents of this dictionary. - /// - public XmlDocument DictionaryAsXml - { - get - { - XmlDocument result = new XmlDocument(); - XmlDeclaration dec = result.CreateXmlDeclaration("1.0", "UTF-8", ""); - result.AppendChild(dec); - XmlNode root = result.CreateNode(XmlNodeType.Element, "root", ""); - result.AppendChild(root); - foreach (string key in _orderedKeys) - { - XmlNode item = result.CreateNode(XmlNodeType.Element, "item", ""); - XmlAttribute name = result.CreateAttribute("name"); - name.Value = key; - XmlAttribute value = result.CreateAttribute("value"); - value.Value = _settingsHash[key]; - if (item.Attributes != null) - { - item.Attributes.Append(name); - item.Attributes.Append(value); - } - root.AppendChild(item); - } - return result; - } - } - /// - /// Initializes a new instance of the class. - /// - /// Aeon settings dictionary. - public SettingsDictionary(Aeon theAeon) - { - TheAeon = theAeon; - } - /// - /// Initializes a new instance of the class. - /// - public SettingsDictionary() { } - /// - /// Loads settings into the class from the file referenced in pathToSettings. The xml should have a declaration with a root tag with child nodes of the form: - /// - /// - /// The file containing the settings. - public void LoadSettings(string pathToSettings) - { - if (pathToSettings.Length > 0) - { - FileInfo fi = new FileInfo(pathToSettings); - if (fi.Exists) - { - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(pathToSettings); - LoadSettings(xmlDoc); - } - else - { - throw new FileNotFoundException(); - } - } - else - { - throw new FileNotFoundException(); - } - } - /// - /// Loads settings into the class from the file referenced in pathToSettings. The xml should have a declaration with a root tag with child nodes of the form: - /// - /// - /// The settings as an xml document. - public void LoadSettings(XmlDocument settingsAsXml) - { - // Empty the hash. - ClearSettings(); - - if (settingsAsXml.DocumentElement != null) - { - XmlNodeList rootChildren = settingsAsXml.DocumentElement.ChildNodes; - - foreach (XmlNode myNode in rootChildren) - { - if (myNode.Attributes != null && (myNode.Name == "item") & (myNode.Attributes.Count == 2)) - { - if ((myNode.Attributes[0].Name == "name") & (myNode.Attributes[1].Name == "value")) - { - string name = myNode.Attributes["name"].Value; - string value = myNode.Attributes["value"].Value; - if (name.Length > 0) - { - AddSetting(name, value); - } - } - } - } - } - } - /// - /// Adds a setting to the Settings class (accessed via the grabSettings(string name) method. - /// - /// The name of the new setting. - /// The value associated with this setting. - public void AddSetting(string name, string value) - { - string key = MakeCaseInsensitive.TransformInput(name); - if (key.Length > 0) - { - RemoveSetting(key); - _orderedKeys.Add(key); - _settingsHash.Add(MakeCaseInsensitive.TransformInput(key), value); - } - } - /// - /// Removes a named setting from this class. - /// - /// The name of the setting to remove. - public void RemoveSetting(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - _orderedKeys.Remove(normalizedName); - RemoveFromHash(normalizedName); - } - /// - /// Removes a named setting from the dictionary. - /// - /// The key for the dictionary. - private void RemoveFromHash(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - _settingsHash.Remove(normalizedName); - } - /// - /// Updates the named setting with a new value while retaining the position in the dictionary. - /// - /// The name of the setting. - /// The new value. - public void UpdateSetting(string name, string value) - { - string key = MakeCaseInsensitive.TransformInput(name); - if (_orderedKeys.Contains(key)) - { - RemoveFromHash(key); - _settingsHash.Add(MakeCaseInsensitive.TransformInput(key), value); - } - } - /// - /// Clears the dictionary to an empty state. - /// - public void ClearSettings() - { - _orderedKeys.Clear(); - _settingsHash.Clear(); - } - /// - /// Returns the value of a setting given the name of the setting. - /// - /// The name of the setting whose value is of interest. - /// The value of the setting. - public string GrabSetting(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - if (ContainsSettingCalled(normalizedName)) - { - return _settingsHash[normalizedName]; - } - return string.Empty; - } - /// - /// Checks to see if a setting of a particular name exists. - /// - /// The setting name to check. - /// Existential truth value. - public bool ContainsSettingCalled(string name) - { - string normalizedName = MakeCaseInsensitive.TransformInput(name); - if (normalizedName.Length > 0) - { - return _orderedKeys.Contains(normalizedName); - } - return false; - } - /// - /// Returns a collection of the names of all the settings defined in the dictionary. - /// - /// A collection of the names of all the settings defined in the dictionary. - public string[] SettingNames - { - get - { - string[] result = new string[_orderedKeys.Count]; - _orderedKeys.CopyTo(result, 0); - return result; - } - } - /// - /// Copies the values in the current object into the SettingsDictionary passed as the target. - /// - /// The target to recieve the values from this SettingsDictionary. - public void Clone(SettingsDictionary target) - { - foreach (string key in _orderedKeys) - { - target.AddSetting(key, GrabSetting(key)); - } - } - } -} diff --git a/core/Core/SubQuery.cs b/core/Core/SubQuery.cs deleted file mode 100644 index d065f9c..0000000 --- a/core/Core/SubQuery.cs +++ /dev/null @@ -1,46 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; - -namespace Cartheur.Animals.Core -{ - /// - /// A container class for holding wildcard matches encountered during a path interrogation. - /// - public class SubQuery - { - /// - /// The trajectory that this query relates to. - /// - public string Trajectory; - /// - /// The template found from searching the brain with the path . - /// - public string Template = string.Empty; - /// - /// If the raw input matches a wildcard then this attribute will contain the block of text that the user has inputted that is matched by the wildcard. - /// - public List InputStar = new List(); - /// - /// If the "that" part of the normalized path contains a wildcard then this attribute will contain the block of text that the user has inputted that is matched by the wildcard. - /// - public List ThatStar = new List(); - /// - /// If the "topic" part of the normalized path contains a wildcard then this attribute will contain the block of text that the user has inputted that is matched by the wildcard. - /// - public List TopicStar = new List(); - /// - /// The "emotional" part of the normalized path contains a wildcard then this attribute will contain the block of text that the user has inputted that is matched by the wildcard. - /// - public List EmotionStar = new List(); - /// - /// Initializes a new instance of the class. - /// - /// The trajectory that this query relates to. - public SubQuery(string trajectory) - { - Trajectory = trajectory; - } - } -} diff --git a/core/Core/Syntax.cs b/core/Core/Syntax.cs deleted file mode 100644 index 5a93577..0000000 --- a/core/Core/Syntax.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Cartheur.Animals.Core -{ - /// - /// Commands recognized by aeon to perform an activity outside of its conversational significance. - /// - public class Syntax - { - /// - /// The aeon listen command, inclusive trailing space. - /// - public static string AeonListenCommand = "aeon "; - /// - /// The listen command using more obvious intonation from the speaker and that cannot be confused with ordinary words. - /// - public static string ListenCommand = "baytow";// Not used but keeping it here. - /// - /// The amend conversation command. - /// - public static string AmendConversationCommand = "alter conversation"; - /// - /// The change emotion command. - /// - public static string ChangeEmotionCommand = "aeon change emotion"; - /// - /// The nao stand up command. - /// - public static string StandUpCommand = "nao stand up"; - /// - /// The nao rest position command. - /// - public static string RestPositionCommand = "nao rest position"; - /// - /// Gets or sets a value indicating whether [command received]. - /// - /// - /// true if [command received]; otherwise, false. - /// - public static bool CommandReceived { get; set; } - } -} diff --git a/core/Core/Trajectory.cs b/core/Core/Trajectory.cs deleted file mode 100644 index 6cbbe53..0000000 --- a/core/Core/Trajectory.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// - -namespace Cartheur.Animals.Core -{ - /// - /// The class responsible for engaging the learning algorithm. - /// - /// USPTO-301 - public class Trajectory - { - /// - /// The indication type. - /// - public enum TrajectoryType - { - /// - /// The trajectory type for a language-based scenario. - /// - Langauge, - /// - /// The trajectory type for a nonlanguage-based scenario. - /// - NonLanguage - } - /// - /// Encapsulate a trajectory for processing. - /// - public Trajectory Create(Topic topic, Sentences sentence, IntentionCatalog catalog) - { - return new Trajectory();// USPTO-307. - } - - /// - /// Encapsulate a trajectory for passing to the algorithmic technique - USPTO-310. - /// - public Trajectory ParseTopic(Topic topic, Sentences sentence, IntentionCatalog catalog) - { - return new Trajectory();// USPTO-308. - } - } -} \ No newline at end of file diff --git a/core/Core/User.cs b/core/Core/User.cs deleted file mode 100644 index ed0ed00..0000000 --- a/core/Core/User.cs +++ /dev/null @@ -1,165 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; - -namespace Cartheur.Animals.Core -{ - /// - /// Encapsulates information and history of a user who has interacted with aeon. - /// - public class User - { - /// - /// The aeon this user is using. - /// - public Aeon UserAeon; - /// - /// The GUID that identifies this user. - /// - public string UserName { get; set; } - /// - /// A collection of all the result objects returned to the user in this session. - /// - public readonly List AeonReplies = new List(); - /// - /// The value of the "topic" predicate. - /// - public string Topic - { - get - { - return Predicates.GrabSetting("topic"); - } - } - /// - /// The user's emotion, initially loaded to the "emotion" value set in the predicates file. - /// - public string Emotion { get; set; } - /// - /// The predicates associated with this particular user. - /// - public SettingsDictionary Predicates; - /// - /// The most recent result to be returned by aeon. - /// - public Result LastAeonReply - { - get - { - return AeonReplies.Count > 0 ? AeonReplies[0] : null; - } - } - /// - /// Initializes a new instance of the class. - /// - /// The name of the user. - /// The aeon the user is connected to. - /// The UserID cannot be empty. - public User(string userName, Aeon aeon) - { - if (userName.Length > 0) - { - UserName = userName; - UserAeon = aeon; - Predicates = new SettingsDictionary(UserAeon); - Predicates = UserAeon.DefaultPredicates; - } - else - { - throw new Exception("The UserID cannot be empty."); - } - } - /// - /// Returns the string to use for the next that part of a subsequent path. - /// - /// The string to use for that. - public string GetLastAeonOutput() - { - if (AeonReplies.Count > 0) - { - return AeonReplies[0].Output; - } - return "*"; - } - /// - /// Returns the first sentence of the last output from aeon. - /// - /// The first sentence of the last output from aeon. - public string GetThat() - { - return GetThat(0,0); - } - /// - /// Returns the first sentence of the output n-steps ago from aeon. - /// - /// The number of steps back to go. - /// The first sentence of the output n-steps ago from aeon. - public string GetThat(int n) - { - return GetThat(n, 0); - } - /// - /// Returns the sentence numbered by "sentence" of the output n-steps ago from aeon. - /// - /// The number of steps back to go. - /// The sentence number to get. - /// The sentence numbered by "sentence" of the output n-steps ago from aeon. - public string GetThat(int n, int sentence) - { - if ((n >= 0) & (n < AeonReplies.Count)) - { - Result historicResult = AeonReplies[n]; - if ((sentence >= 0) & (sentence < historicResult.OutputSentences.Count)) - { - return historicResult.OutputSentences[sentence]; - } - } - return string.Empty; - } - /// - /// Returns the first sentence of the last output from aeon. - /// - /// The first sentence of the last output from aeon. - public string GetAeonReply() - { - return GetAeonReply(0, 0); - } - /// - /// Returns the first sentence from the output from aeon n-steps ago. - /// - /// The number of steps back to go. - /// The first sentence from the output from aeon n-steps ago. - public string GetAeonReply(int n) - { - return GetAeonReply(n, 0); - } - /// - /// Returns the identified sentence number from the output from aeon n-steps ago. - /// - /// The number of steps back to go. - /// The sentence number to return. - /// The identified sentence number from the output from aeon n-steps ago. - public string GetAeonReply(int n, int sentence) - { - if ((n >= 0) & (n < AeonReplies.Count)) - { - Result historicResult = AeonReplies[n]; - if ((sentence >= 0) & (sentence < historicResult.InputSentences.Count)) - { - return historicResult.InputSentences[sentence]; - } - } - return string.Empty; - } - /// - /// Adds the latest result from aeon to the results collection. - /// - /// The latest result from aeon. - public void AddResult(Result latestResult) - { - AeonReplies.Insert(0, latestResult); - } - } -} diff --git a/core/FileLogic/Category.cs b/core/FileLogic/Category.cs deleted file mode 100644 index 05cf578..0000000 --- a/core/FileLogic/Category.cs +++ /dev/null @@ -1,20 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Cartheur.Animals.FileLogic -{ - /// - /// The category storage object. - /// - public class Category - { - /// - /// Gets or sets the category identifier. - /// - public string CategoryID { get; set; } - /// - /// Gets or sets the name of the category. - /// - public string CategoryName { get; set; } - } -} diff --git a/core/FileLogic/CategoryList.cs b/core/FileLogic/CategoryList.cs deleted file mode 100644 index 354fa4d..0000000 --- a/core/FileLogic/CategoryList.cs +++ /dev/null @@ -1,67 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; -using System.Data; - -namespace Cartheur.Animals.FileLogic -{ - /// - /// The category list storage object. - /// - public class CategoryList - { - /// - /// Gets the category. - /// - /// The category identifier. - /// - public static Category GetCategory(string categoryID) - { - DataRow dataRow = XmlCategory.Select(categoryID); - Category result = null; - if (dataRow != null) - { - Category category = new Category(); - category.CategoryID = ((dataRow[0] != DBNull.Value) ? dataRow[0].ToString() : string.Empty); - category.CategoryName = ((dataRow[1] != DBNull.Value) ? dataRow[1].ToString() : string.Empty); - result = category; - } - return result; - } - /// - /// Gets the category list. - /// - /// The filepath. - /// - public static IList GetCategoryList(string filepath) - { - return XmlCategory.SelectAll(filepath); - } - /// - /// Updates the category. - /// - /// The cat. - public static void UpdateCategory(Category cat) - { - XmlCategory.Update(cat.CategoryID, cat.CategoryName); - } - /// - /// Inserts the category. - /// - /// The cat. - public static void InsertCategory(Category cat) - { - XmlCategory.Insert(cat.CategoryID, cat.CategoryName); - } - /// - /// Deletes the category. - /// - /// The category identifier. - public static void DeleteCategory(string categoryID) - { - XmlCategory.Delete(categoryID); - } - } -} diff --git a/core/FileLogic/Command.cs b/core/FileLogic/Command.cs deleted file mode 100644 index 34f279e..0000000 --- a/core/FileLogic/Command.cs +++ /dev/null @@ -1,20 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace Cartheur.Animals.FileLogic -{ - /// - /// The command storage object. - /// - public class Command - { - /// - /// Gets or sets the command identifier. - /// - public string CommandID { get; set; } - /// - /// Gets or sets the name of the command. - /// - public string CommandName { get; set; } - } -} diff --git a/core/FileLogic/CommandList.cs b/core/FileLogic/CommandList.cs deleted file mode 100644 index 76b522b..0000000 --- a/core/FileLogic/CommandList.cs +++ /dev/null @@ -1,67 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; -using System.Data; - -namespace Cartheur.Animals.FileLogic -{ - /// - /// The command list storage object. - /// - public class CommandList - { - /// - /// Gets the command. - /// - /// The command identifier. - /// - public static Command GetCommand(string commandID) - { - DataRow dataRow = XmlCommand.Select(commandID); - Command result = null; - if (dataRow != null) - { - Command command = new Command(); - command.CommandID = ((dataRow[0] != DBNull.Value) ? dataRow[0].ToString() : string.Empty); - command.CommandName = ((dataRow[1] != DBNull.Value) ? dataRow[1].ToString() : string.Empty); - result = command; - } - return result; - } - /// - /// Gets the command list. - /// - /// The filepath. - /// - public static IList GetCommandList(string filepath) - { - return XmlCommand.SelectAll(filepath, XmsFileType.Command); - } - /// - /// Updates the command. - /// - /// The command. - public static void UpdateCommand(Command command) - { - XmlCategory.Update(command.CommandID, command.CommandName); - } - /// - /// Inserts the command. - /// - /// The command. - public static void InsertCommand(Command command) - { - XmlCategory.Insert(command.CommandID, command.CommandName); - } - /// - /// Deletes the command. - /// - /// The command identifier. - public static void DeleteCommand(string commandID) - { - XmlCategory.Delete(commandID); - } - } -} diff --git a/core/FileLogic/FileTemplate.cs b/core/FileLogic/FileTemplate.cs deleted file mode 100644 index 32e781f..0000000 --- a/core/FileLogic/FileTemplate.cs +++ /dev/null @@ -1,60 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.IO; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.FileLogic -{ - /// - /// A static class for writing new files to the aeon's working memory. - /// - public static class FileTemplate - { - private const string NuFilenameBlank = "blank.aeon"; - /// - /// Gets or sets the pattern text. - /// - public static string PatternText { get; set; } - //private static string _patternFragment = "" + PatternText + ""; - /// - /// Gets or sets the template text. - /// - public static string TemplateText { get; set; } - //private static string _templateFragment = ""; - /// - /// The XMS file template blank - /// - public static string FileTemplateBlank = ""; - /// - /// Creates the XMS template. - /// - /// - public static string CreateFileTemplate() - { - return FileTemplateBlank = "" + PatternText + ""; - } - /// - /// Writes a nufile to data storage. - /// - /// The name of the nufile. If empty, then will use the xms filename field. - /// The thematic group of the addition. (Experimental) - /// True if successful. - public static bool WriteNuFile(string filename, string group) - { - if (filename == "") - filename = NuFilenameBlank; - try - { - File.WriteAllText(Environment.CurrentDirectory + @"\nucode\" + filename, FileTemplateBlank, System.Text.Encoding.UTF8); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.SharedFunction); - return false; - } - return true; - } - } -} diff --git a/core/FileLogic/XmlCategory.cs b/core/FileLogic/XmlCategory.cs deleted file mode 100644 index 6947779..0000000 --- a/core/FileLogic/XmlCategory.cs +++ /dev/null @@ -1,92 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Data; - -namespace Cartheur.Animals.FileLogic -{ - /// - /// The xml category storage object. - /// - public static class XmlCategory - { - private static readonly DataSet ReadonlyDataSet = new DataSet(); - private static DataView _dataView = new DataView(); - private static string _filepath; - /// - /// Saves the specified filepath. - /// - /// The filepath. - public static void Save(string filepath) - { - _filepath = filepath; - ReadonlyDataSet.WriteXml(filepath, XmlWriteMode.WriteSchema); - } - /// - /// Inserts the specified category identifier. - /// - /// The category identifier. - /// Name of the category. - public static void Insert(string categoryID, string categoryName) - { - DataRow dataRow = _dataView.Table.NewRow(); - dataRow[0] = categoryID; - dataRow[1] = categoryName; - _dataView.Table.Rows.Add(dataRow); - Save(_filepath); - } - /// - /// Updates the specified category identifier. - /// - /// The category identifier. - /// Name of the category. - public static void Update(string categoryID, string categoryName) - { - DataRow dataRow = Select(categoryID); - dataRow[1] = categoryName; - Save(_filepath); - } - /// - /// Deletes the specified category identifier. - /// - /// The category identifier. - public static void Delete(string categoryID) - { - _dataView.RowFilter = "categoryID='" + categoryID + "'"; - _dataView.Sort = "categoryID"; - _dataView.Delete(0); - _dataView.RowFilter = ""; - Save(_filepath); - } - /// - /// Selects the specified category identifier. - /// - /// The category identifier. - /// - public static DataRow Select(string categoryID) - { - _dataView.RowFilter = "categoryID='" + categoryID + "'"; - _dataView.Sort = "categoryID"; - DataRow result = null; - if (_dataView.Count > 0) - { - result = _dataView[0].Row; - } - _dataView.RowFilter = ""; - return result; - } - /// - /// Selects all data views. - /// - /// The filepath. - /// - public static DataView SelectAll(string filepath) - { - _filepath = filepath; - ReadonlyDataSet.Clear(); - ReadonlyDataSet.ReadXml(filepath, XmlReadMode.ReadSchema); - _dataView = ReadonlyDataSet.Tables[0].DefaultView; - return _dataView; - } - } -} diff --git a/core/FileLogic/XmlCommand.cs b/core/FileLogic/XmlCommand.cs deleted file mode 100644 index 5dfa27c..0000000 --- a/core/FileLogic/XmlCommand.cs +++ /dev/null @@ -1,140 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Cartheur.Animals.Utilities; -using System; -using System.Data; - -namespace Cartheur.Animals.FileLogic -{ - /// - /// The xms file type. - /// - public enum XmsFileType - { - /// - /// The category file type. - /// - Category, - /// - /// The command file type. - /// - Command - } - - /// - /// The xml command storage object. - /// - public static class XmlCommand - { - private static readonly DataSet ReadonlyDataSet = new DataSet(); - private static DataView _dataView = new DataView(); - private static string _filepath; - static string _filename; - /// - /// Saves the specified file at the path. - /// - /// The filepath. - /// Type of the file. - public static void Save(string filepath, XmsFileType fileType) - { - switch (fileType) - { - case XmsFileType.Category: - _filename = @"\Category.xml"; - break; - case XmsFileType.Command: - _filename = @"\Command.xml"; - break; - } - _filepath = filepath + _filename; - ReadonlyDataSet.WriteXml(filepath, XmlWriteMode.WriteSchema); - } - /// - /// Inserts the specified category identifier. - /// - /// The category identifier. - /// Name of the category. - /// Type of the file. - public static void Insert(string categoryID, string categoryName, XmsFileType fileType) - { - DataRow dataRow = _dataView.Table.NewRow(); - dataRow[0] = categoryID; - dataRow[1] = categoryName; - _dataView.Table.Rows.Add(dataRow); - Save(_filepath, fileType); - } - /// - /// Updates the specified category identifier. - /// - /// The category identifier. - /// Name of the category. - /// Type of the file. - public static void Update(string categoryID, string categoryName, XmsFileType fileType) - { - DataRow dataRow = Select(categoryID); - dataRow[1] = categoryName; - Save(_filepath, fileType); - } - /// - /// Deletes the specified category identifier. - /// - /// The category identifier. - /// Type of the file. - public static void Delete(string categoryID, XmsFileType fileType) - { - _dataView.RowFilter = "commandID='" + categoryID + "'"; - _dataView.Sort = "commandID"; - _dataView.Delete(0); - _dataView.RowFilter = ""; - Save(_filepath, fileType); - } - /// - /// Selects the specified category identifier. - /// - /// The category identifier. - /// - public static DataRow Select(string categoryID) - { - _dataView.RowFilter = "commandID='" + categoryID + "'"; - _dataView.Sort = "commandID"; - DataRow result = null; - if (_dataView.Count > 0) - { - result = _dataView[0].Row; - } - _dataView.RowFilter = ""; - return result; - } - /// - /// Selects all data views. - /// - /// The filepath. - /// Type of the file. - /// - public static DataView SelectAll(string filepath, XmsFileType fileType) - { - switch (fileType) - { - case XmsFileType.Category: - _filename = @"\Category.xml"; - break; - case XmsFileType.Command: - _filename = @"\Command.xml"; - break; - } - _filepath = filepath + _filename; - ReadonlyDataSet.Clear(); - try - { - ReadonlyDataSet.ReadXml(_filepath, XmlReadMode.ReadSchema); - } - catch(Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.Xms); - } - _dataView = ReadonlyDataSet.Tables[0].DefaultView; - return _dataView; - } - } -} diff --git a/core/Normalize/ApplySubstitutions.cs b/core/Normalize/ApplySubstitutions.cs deleted file mode 100644 index e67c1e6..0000000 --- a/core/Normalize/ApplySubstitutions.cs +++ /dev/null @@ -1,90 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Text; -using System.Text.RegularExpressions; -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.Normalize -{ - /// - /// Checks the text for any matches in the bot's substitutions dictionary and makes any appropriate changes. - /// - public class ApplySubstitutions : TextTransformer - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon this transformer is a part of - /// The input string to be transformed - public ApplySubstitutions(Aeon aeon, string inputString) - : base(aeon, inputString) - { } - /// - /// Initializes a new instance of the class. - /// - /// The aeon this transformer is a part of - public ApplySubstitutions(Aeon aeon) - : base(aeon) - { } - /// - /// Gets the marker. - /// - /// The length. - private static string GetMarker(int len) - { - char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); - StringBuilder result = new StringBuilder(); - Random r = new Random(); - for (int i = 0; i < len; i++) - { - result.Append(chars[r.Next(chars.Length)]); - } - return result.ToString(); - } - /// - /// The method that does the actual processing of the text. - /// - protected override string ProcessChange() - { - return Substitute(ThisAeon, ThisAeon.Substitutions, InputString); - } - /// - /// Static helper that applies replacements from the passed dictionary object to the target string. - /// - /// The aeon for whom this is being processed - /// The dictionary containing the substitutions - /// the target string to which the substitutions are to be applied - /// The processed string - public static string Substitute(Aeon aeon, SettingsDictionary dictionary, string target) - { - string marker = GetMarker(5); - string result = target; - foreach (string pattern in dictionary.SettingNames) - { - string p2 = MakeRegexSafe(pattern); - //string match = "\\b"+@p2.Trim().Replace(" ","\\s*")+"\\b"; - string match = "\\b" + p2.TrimEnd().TrimStart() + "\\b"; - string replacement = marker+dictionary.GrabSetting(pattern).Trim()+marker; - result = Regex.Replace(result, match, replacement, RegexOptions.IgnoreCase); - } - - return result.Replace(marker, ""); - } - /// - /// Given an input, escapes certain characters so they can be used as part of a regex. - /// - /// The raw input - /// the safe version - private static string MakeRegexSafe(string input) - { - string result = input.Replace("\\",""); - result = result.Replace(")", "\\)"); - result = result.Replace("(", "\\("); - result = result.Replace(".", "\\."); - return result; - } - } -} diff --git a/core/Normalize/MakeCaseInsensitive.cs b/core/Normalize/MakeCaseInsensitive.cs deleted file mode 100644 index 5d13f3d..0000000 --- a/core/Normalize/MakeCaseInsensitive.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.Normalize -{ - /// - /// Normalizes the input text into upper case. - /// - public class MakeCaseInsensitive : TextTransformer - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon is this transformer a part of - /// The input string to be transformed - public MakeCaseInsensitive(Aeon aeon, string inputString) : base(aeon, inputString) - { } - /// - /// Initializes a new instance of the class. - /// - /// The aeon this transformer is a part of - public MakeCaseInsensitive(Aeon aeon) : base(aeon) - { } - /// - /// The method that does the actual processing of the text. - /// - protected override string ProcessChange() - { - return InputString.ToUpper(); - } - /// - /// An ease-of-use static method that re-produces the instance transformation methods. - /// - /// The string to transform - /// The resulting string - public static string TransformInput(string input) - { - return input.ToUpper(); - } - } -} diff --git a/core/Normalize/SplitIntoSentences.cs b/core/Normalize/SplitIntoSentences.cs deleted file mode 100644 index 8839851..0000000 --- a/core/Normalize/SplitIntoSentences.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Collections.Generic; -using Cartheur.Animals.Core; - -namespace Cartheur.Animals.Normalize -{ - /// - /// Splits the raw input into its constituent sentences. Split using the tokens found in aeon's Splitters string array. - /// - public class SplitIntoSentences - { - /// - /// The aeon this sentence splitter is associated with - /// - private readonly Aeon _aeon; - /// - /// The raw input string - /// - private string _inputString; - /// - /// Initializes a new instance of the class. - /// - /// The aeon this sentence splitter is associated with - /// The raw input string to be processed - public SplitIntoSentences(Aeon aeon, string inputString) - { - _aeon = aeon; - _inputString = inputString; - } - /// - /// Initializes a new instance of the class. - /// - /// The aeon this sentence splitter is associated with - public SplitIntoSentences(Aeon aeon) - { - _aeon = aeon; - } - /// - /// Splits the supplied raw input into an array of strings according to the tokens found in aeon's Splitters list. - /// - /// The raw input to split - /// An array of strings representing the constituent "sentences" - public string[] Transform(string inputString) - { - _inputString = inputString; - return Transform(); - } - /// - /// Splits the raw input supplied via the constructor into an array of strings according to the tokens found in aeon's Splitters list. - /// - /// An array of strings representing the constituent "sentences" - public string[] Transform() - { - string[] tokens = _aeon.Splitters.ToArray(); - string[] rawResult = {}; - char[] charTokens = {}; - char charToken = new char(); - foreach (string token in tokens) - { - charTokens = token.ToCharArray(); - } - for (int i = 0; i < charTokens.Length; i++) - { - rawResult = _inputString.Split(charToken); - } - - List tidyResult = new List(); - foreach (string rawSentence in rawResult) - { - string tidySentence = rawSentence.Trim(); - if (tidySentence.Length > 0) - { - tidyResult.Add(tidySentence); - } - } - return tidyResult.ToArray(); - } - } -} diff --git a/core/Normalize/StripIllegalCharacters.cs b/core/Normalize/StripIllegalCharacters.cs deleted file mode 100644 index 963f75d..0000000 --- a/core/Normalize/StripIllegalCharacters.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Cartheur.Animals.Core; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Animals.Normalize -{ - /// - /// Strips any illegal characters found in the input string. Illegal characters are referenced from aeon's Strippers regex that is defined in the setup XML file. - /// - public class StripIllegalCharacters : TextTransformer - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon is this transformer a part of - /// The input string to be transformed - public StripIllegalCharacters(Aeon aeon, string inputString) : base(aeon, inputString) - { } - /// - /// Initializes a new instance of the class. - /// - /// The aeon this transformer is a part of - public StripIllegalCharacters(Aeon aeon) - : base(aeon) - { } - /// - /// The method that does the actual processing of the text. - /// - protected override string ProcessChange() - { - return ThisAeon.Strippers.Replace(InputString, " "); - } - } -} diff --git a/core/Utilities/AeonGpio.cs b/core/Utilities/AeonGpio.cs deleted file mode 100644 index 0f2a78d..0000000 --- a/core/Utilities/AeonGpio.cs +++ /dev/null @@ -1,183 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Class responsible for connecting to the motor controller, via the Gpio interface. - /// - public class AeonGpio - { - /// - /// Gets or sets a value indicating whether this is debug. - /// - /// - /// true if debug; otherwise, false. - /// - public static bool Debug { get; set; } - - /// - /// The collection of pinsets for the Chip. - /// - public enum PinSets - { - /// - /// Chip XIO-P0. - /// - P0 = 1013, - /// - /// Chip XIO-P1. - /// - P1 = 1014, - /// - /// Chip XIO-P2. - /// - P2 = 1015, - /// - /// Chip XIO-P3. - /// - P3 = 1016, - /// - /// Chip XIO-P4. - /// - P4 = 1017, - /// - /// Chip XIO-P5. - /// - P5 = 1018, - /// - /// Chip XIO-P6. - /// - P6 = 1019, - /// - /// Chip XIO-P7. - /// - P7 = 1020 - }; - /// - /// In which direction is the data flowing? - /// - public enum PinDirection - { - /// - /// An inward direction. - /// - In, - /// - /// An outward direction. - /// - Out - }; - - /// - /// The gpio path. - /// - private const string GpioPath ="/sys/class/gpio/"; - // Contains a list of pins exported with an OUT direction. - readonly List _outExported = new List(); - // Contains a list of pins exported with an IN direction. - readonly List _inExported = new List(); - - private void SetupPin(PinSets pin, PinDirection direction) - { - // Unexport if it we're using it already - if (_outExported.Contains(pin) || _inExported.Contains(pin)) UnexportPin(pin); - // Export. - File.WriteAllText(GpioPath + "export", GetPinNumber(pin)); - - if (Debug) Logging.WriteLog("Exporting pin " + pin + " as " + direction + ".", Logging.LogType.Information, Logging.LogCaller.Aeon); - - // set i/o direction - File.WriteAllText(GpioPath + pin + "/direction", direction.ToString().ToLower()); - - //record the fact that we've setup that pin - if (direction == PinDirection.Out) - _outExported.Add(pin); - else - _inExported.Add(pin); - } - /// - /// Sets an output on the pin. - /// - /// The pin. - /// if set to true [value]. - public void OutputPin(PinSets pin, bool value) - { - // If we havent used the pin before, or if we used it as an input before, set it up. - if (!_outExported.Contains(pin) || _inExported.Contains(pin)) SetupPin(pin, PinDirection.Out); - - var writeValue = "0"; - if (value) writeValue = "1"; - File.WriteAllText(GpioPath + pin + "/value", writeValue); - - if (Debug) Logging.WriteLog("Output to pin " + pin + ", value was " + value + ".", Logging.LogType.Information, Logging.LogCaller.Aeon); - } - /// - /// Sets an input on the pin. - /// - /// The pin. - /// - /// - public bool InputPin(PinSets pin) - { - var returnValue = false; - if (!_inExported.Contains(pin) || _outExported.Contains(pin)) SetupPin(pin, PinDirection.In); - - var filename = GpioPath + pin + "/value"; - if (File.Exists(filename)) - { - var readValue = File.ReadAllText(filename); - if (readValue.Length > 0 && readValue[0] == '1') returnValue = true; - } - else - throw new Exception(string.Format("Cannot read from {0}. File does not exist", pin)); - - if (Debug) Logging.WriteLog("Input from pin " + pin + ", value was " + returnValue + ".", Logging.LogType.Information, Logging.LogCaller.Aeon); - - return returnValue; - } - /// - /// Unexports the pin. - /// - /// The pin. - /// if for any reason you want to unexport a particular pin use this, otherwise just call CleanUpAllPins when you're done - public void UnexportPin(PinSets pin) - { - var found = false; - if (_outExported.Contains(pin)) - { - found = true; - _outExported.Remove(pin); - } - if (_inExported.Contains(pin)) - { - found = true; - _inExported.Remove(pin); - } - - if (found) - { - File.WriteAllText(GpioPath + "unexport", GetPinNumber(pin)); - if (Debug) Logging.WriteLog("Unexporting pin " + pin + ".", Logging.LogType.Information, Logging.LogCaller.Aeon); - } - } - /// - /// Cleans up all pins. - /// - public void CleanUpAllPins() - { - for (var p = _outExported.Count - 1; p >= 0; p--) UnexportPin(_outExported[p]); // Unexport in reverse order. - for (var p = _inExported.Count - 1; p >= 0; p--) UnexportPin(_inExported[p]); - } - - private static string GetPinNumber(PinSets pin) - { - return ((int) pin).ToString(CultureInfo.InvariantCulture) ; // Returns 17 for enum value of gpio17 - } - } -} diff --git a/core/Utilities/AeonLoader.cs b/core/Utilities/AeonLoader.cs deleted file mode 100644 index 7c53ce1..0000000 --- a/core/Utilities/AeonLoader.cs +++ /dev/null @@ -1,398 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.IO; -using System.Text; -using System.Xml; -using Cartheur.Animals.Core; -using Cartheur.Animals.Normalize; - -namespace Cartheur.Animals.Utilities -{ - /// - /// A class for loading *.aeon files from the file system into the program's architecture that forms an aeon brain. - /// - public class AeonLoader - { - private readonly Aeon _aeon; - /// - /// Initializes a new instance of the class. - /// - /// The presence whose brain is being processed. - public AeonLoader(Aeon aeon) - { - _aeon = aeon; - } - /// - /// Loads the *.aeon from files found in the path. - /// - /// The path where the aeon code files are. - public void LoadAeon(string path) - { - if (Directory.Exists(path)) - { - // Log the loading activity. - Logging.WriteLog("Starting to process files found in the directory " + path, Logging.LogType.Information, Logging.LogCaller.AeonLoader); - - string[] fileEntries = Directory.GetFiles(path, "*.aeon"); - if (fileEntries.Length > 0) - { - foreach (string filename in fileEntries) - { - LoadAeonCodeFile(filename); - } - Logging.WriteLog("Finished processing *.aeon files: " + Convert.ToString(_aeon.Size) + " categories processed", Logging.LogType.Information, Logging.LogCaller.AeonLoader); - Aeon.PersonalityLoaded = true; - } - else - { - throw new FileNotFoundException("Could not find any data files in the specified directory (" + path + "). Make sure that these files end in a lowercase extension like *.aeon."); - } - } - else - { - throw new FileNotFoundException("The directory specified as the path to the *.aeon files (" + path + ") cannot be found by the AeonLoader object. Please make sure the directory where the *.aeon files are to be found is the same as the directory specified in the settings file."); - } - } - /// - /// Given the name of a file in the aeon code path directory, attempts to load it into the program. - /// - /// The name of the file to process. - public void LoadAeonCodeFile(string filename) - { - // Log the processing activities. - Logging.WriteLog("Processing *.aeon file: " + filename, Logging.LogType.Information, Logging.LogCaller.AeonLoader); - // Load the document. - XmlDocument doc = new XmlDocument(); - doc.Load(filename); - LoadAeonFromXml(doc, filename); - } - /// - /// Given an xml document containing valid aeon code, attempts to load it into the brain. - /// - /// The xml document containing the aeon-formatted code. - /// Where the xml document originated. - public void LoadAeonFromXml(XmlDocument doc, string filename) - { - // Get a list of the nodes that are children of the tag these nodes should only be either or the nodes will contain more nodes. - if (doc.DocumentElement == null) return; - XmlNodeList rootChildren = doc.DocumentElement.ChildNodes; - // Process each of the child nodes. - foreach (XmlNode currentNode in rootChildren) - { - switch (currentNode.Name) - { - case "topic": - ProcessTopic(currentNode, filename); - break; - case "category": - ProcessCategory(currentNode, filename); - break; - } - } - } - /// - /// Given a name will try to find a node named "name" in the childnodes or return null. - /// - /// The name of the node. - /// The node whose children need searching. - /// The node (or null). - private static XmlNode FindNode(string name, XmlNode node) - { - foreach (XmlNode child in node.ChildNodes) - { - if (child.Name == name) - { - return child; - } - } - return null; - } - /// - /// Given a "topic" node, processes all the categories for the topic and adds them to the brain. - /// - /// The "topic" node. - /// The file from which this node is taken. - private void ProcessTopic(XmlNode node, string filename) - { - // Find the name of the topic or set to default "*". - string topicName = "*"; - if (node.Attributes != null && (node.Attributes.Count == 1) & (node.Attributes[0].Name == "name")) - { - topicName = node.Attributes["name"].Value; - } - // Process all the category nodes. - foreach (XmlNode thisNode in node.ChildNodes) - { - if (thisNode.Name == "category") - { - ProcessCategory(thisNode, topicName, filename); - } - } - } - /// - /// Adds a category to the program's structure using the default topic ("*"). - /// - /// The xml node containing the category. - /// The file from which this category was taken. - private void ProcessCategory(XmlNode node, string filename) - { - ProcessCategory(node, "*", filename); - } - /// - /// Adds a category to the program's structure using the given topic. - /// - /// The xml node containing the category. - /// The topic to be used. - /// The file from which this category was taken. - private void ProcessCategory(XmlNode node, string topicName, string filename) - { - // Reference and check the required nodes. - XmlNode pattern = FindNode("pattern", node); - XmlNode template = FindNode("template", node); - - if (Equals(null, pattern)) - { - throw new XmlException("Missing pattern tag in a node found in " + filename); - } - if (Equals(null, template)) - { - throw new XmlException("Missing template tag in the node with pattern: " + pattern.InnerText + " found in " + filename); - } - // Generate the path based on its category. - string categoryTrajectory = GenerateTrajectory(node, topicName, false); - // Add the processed aeon code to the aeon structure. - if (categoryTrajectory.Length > 0) - { - try - { - _aeon.ThisNode.AddCategory(categoryTrajectory, template.OuterXml, filename); - // Keep count of the number of categories that have been processed. - _aeon.Size++; - } - catch - { - Logging.WriteLog("Failed to load a new category into the brain where the path = " + categoryTrajectory + " and template = " + template.OuterXml + " produced by a category in the file:" + filename, Logging.LogType.Error, Logging.LogCaller.AeonLoader); - } - } - else - { - Logging.WriteLog("Attempted to load a new category with an empty pattern where the path = " + categoryTrajectory + " and template = " + template.OuterXml + " produced by a category in the file: " + filename, Logging.LogType.Warning, Logging.LogCaller.AeonLoader); - } - } - /// - /// Generates a path from a category xml node and topic name. - /// - /// The category xml node. - /// The topic. - /// Marks the path to be created as originating from user input - so normalize out the * and _ wildcards used by *.aeon. - /// The appropriately processed path. - public string GenerateTrajectory(XmlNode node, string topicName, bool isUserInput) - { - // Get the required nodes. - XmlNode pattern = FindNode("pattern", node); - XmlNode that = FindNode("that", node); - string thatText = "*"; - string patternText = Equals(null, pattern) ? string.Empty : pattern.InnerText; - - if (!Equals(null, that)) - { - thatText = that.InnerText; - } - - return GenerateTrajectory(patternText, thatText, topicName, isUserInput); - } - /// - /// Generates a path from the passed arguments. - /// - /// The pattern. - /// The that. - /// The topic. - /// Marks the path to be created as originating from user input - so normalize out the * and _ wildcards used by the aeon code. - /// The appropriately processed path. - public string GenerateTrajectory(string pattern, string that, string topicName, bool isUserInput) - { - // To hold the normalized path entered. - StringBuilder normalizedTrajectory = new StringBuilder(); - string normalizedPattern; - string normalizedThat; - string normalizedTopic; - - if ((_aeon.TrustCodeFiles) & (!isUserInput)) - { - normalizedPattern = pattern.Trim(); - normalizedThat = that.Trim(); - normalizedTopic = topicName.Trim(); - } - else - { - normalizedPattern = Normalize(pattern, isUserInput).Trim(); - normalizedThat = Normalize(that, isUserInput).Trim(); - normalizedTopic = Normalize(topicName, isUserInput).Trim(); - } - // Check sizes. - if (normalizedPattern.Length > 0) - { - if (normalizedThat.Length == 0) - { - normalizedThat = "*"; - } - if (normalizedTopic.Length == 0) - { - normalizedTopic = "*"; - } - // This check is in place to avoid overly large "that" elements having to be processed. - if (normalizedThat.Length > _aeon.MaxThatSize) - { - normalizedThat = "*"; - } - // Build the path. - normalizedTrajectory.Append(normalizedPattern); - normalizedTrajectory.Append(" "); - normalizedTrajectory.Append(normalizedThat); - normalizedTrajectory.Append(" "); - normalizedTrajectory.Append(normalizedTopic); - - return normalizedTrajectory.ToString(); - } - return string.Empty; - } - /// - /// Generates a path from the passed arguments. - /// - /// The pattern. - /// The that. - /// The topic. - /// The emotion of aeon. - /// Marks the path to be created as originating from user input - so normalize out the * and _ wildcards used by the aeon code. - /// The appropriately processed path. - public string GenerateTrajectory(string pattern, string that, string topicName, string emotion, bool isUserInput) - { - // To hold the normalized path entered. - StringBuilder normalizedTrajectory = new StringBuilder(); - string normalizedPattern; - string normalizedThat; - string normalizedTopic; - string normalizedEmotion; - - if ((_aeon.TrustCodeFiles) & (!isUserInput)) - { - normalizedPattern = pattern.Trim(); - normalizedThat = that.Trim(); - normalizedTopic = topicName.Trim(); - normalizedEmotion = emotion.Trim(); - } - else - { - normalizedPattern = Normalize(pattern, isUserInput).Trim(); - normalizedThat = Normalize(that, isUserInput).Trim(); - normalizedTopic = Normalize(topicName, isUserInput).Trim(); - normalizedEmotion = Normalize(emotion, isUserInput).Trim(); - } - // Check sizes. - if (normalizedPattern.Length > 0) - { - if (normalizedThat.Length == 0) - { - normalizedThat = "*"; - } - if (normalizedTopic.Length == 0) - { - normalizedTopic = "*"; - } - if (normalizedEmotion.Length == 0) - { - normalizedEmotion = "*"; - } - // This check is in place to avoid overly large "that" elements having to be processed. - if (normalizedThat.Length > _aeon.MaxThatSize) - { - normalizedThat = "*"; - } - // Build the path. - normalizedTrajectory.Append(normalizedPattern); - normalizedTrajectory.Append(" "); - normalizedTrajectory.Append(normalizedThat); - normalizedTrajectory.Append(" "); - normalizedTrajectory.Append(normalizedTopic); - normalizedTrajectory.Append(" "); - normalizedTrajectory.Append(normalizedEmotion); - - return normalizedTrajectory.ToString(); - } - return string.Empty; - } - - #region Utilities - /// - /// Given an input, provide a normalized output. - /// - /// The string to be normalized. - /// True if the string being normalized is part of the user input path - flags that we need to normalize out * and _ chars. - /// The normalized string. - public string Normalize(string input, bool isUserInput) - { - StringBuilder result = new StringBuilder(); - // Objects for normalization of the input. - ApplySubstitutions substitutor = new ApplySubstitutions(_aeon); - StripIllegalCharacters stripper = new StripIllegalCharacters(_aeon); - string substitutedInput = substitutor.Transform(input); - // Split the pattern into its component words. - string[] substitutedWords = substitutedInput.Split(" \r\n\t".ToCharArray()); - // Normalize all words unless wildcards "*" and "_". - foreach (string word in substitutedWords) - { - string normalizedWord; - if (isUserInput) - { - normalizedWord = stripper.Transform(word); - } - else - { - if ((word == "*") || (word == "_")) - { - normalizedWord = word; - } - else - { - normalizedWord = stripper.Transform(word); - } - } - result.Append(normalizedWord.Trim() + " "); - } - - return result.ToString().Replace(" "," "); // Make sure the whitespace is neat. - } - // /// - // /// Does the file decrypt. - // /// - // /// The path where the file should be stored. - // public void DoFileDecrypt(string path) - // { - // try - // { - // Cryptography.Key = _aeon.DefaultPredicates.GrabSetting("password"); - // if (Directory.Exists(path)) - // { - // Logging.WriteLog("Starting to process encrypted aeon files found in the directory " + path, - // Logging.LogType.Information, Logging.LogCaller.AeonLoader); - - // string[] fileEntries = Directory.GetFiles(path, "*.aeon"); - // if (fileEntries.Length > 0) - // { - // foreach (string filename in fileEntries) - // { - // filename.DecryptFile(path + @"output.aeon", Cryptography.Key); - // } - // } - // } - // } - // catch (Exception ex) - // { - // Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.AeonLoader); - // } - // } - #endregion - } -} diff --git a/core/Utilities/AeonTagHandler.cs b/core/Utilities/AeonTagHandler.cs deleted file mode 100644 index 5961913..0000000 --- a/core/Utilities/AeonTagHandler.cs +++ /dev/null @@ -1,79 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System.Xml; -using Cartheur.Animals.Core; - -namespace Cartheur.Animals.Utilities -{ - /// - /// The template for all classes that handle the tags found within template nodes of a category. - /// - public abstract class AeonTagHandler : TextTransformer - { - /// - /// Initializes a new instance of the class. - /// - /// The aeon involved in this request. - /// The user making the request. - /// The query that originated this node. - /// The request sent by the user. - /// The result to be sent back to the user. - /// The node to be processed. - protected AeonTagHandler(Aeon aeon, - User thisUser, - SubQuery query, - Request userRequest, - Result userResult, - XmlNode templateNode) - : base(aeon, templateNode.OuterXml) - { - ThisUser = thisUser; - Query = query; - UserRequest = userRequest; - UserResult = userResult; - TemplateNode = templateNode; - XmlAttributeCollection xmlAttributeCollection = TemplateNode.Attributes; - if (xmlAttributeCollection != null) xmlAttributeCollection.RemoveNamedItem("xmlns"); - } - /// - /// Default to use when late-binding. - /// - protected AeonTagHandler() { } - /// - /// A flag to denote if inner tags are to be processed recursively before processing this tag. - /// - public bool IsRecursive = true; - /// - /// A representation of the user making the request. - /// - public User ThisUser; - /// - /// The query that produced this node containing the wildcard matches. - /// - public SubQuery Query; - /// - /// A representation of the input made by the user. - /// - public Request UserRequest; - /// - /// A representation of the result to be returned to the user. - /// - public Result UserResult; - /// - /// The template node to be processed by the class. - /// - public XmlNode TemplateNode; - /// - /// Helper method that turns the passed string into an xml node. - /// - /// The string to xmlize. - /// The xml node. - public static XmlNode GetNode(string outerXml) - { - XmlDocument temp = new XmlDocument(); - temp.LoadXml(outerXml); - return temp.FirstChild; - } - } -} diff --git a/core/Utilities/Base64Tool.cs b/core/Utilities/Base64Tool.cs deleted file mode 100644 index 9ed2942..0000000 --- a/core/Utilities/Base64Tool.cs +++ /dev/null @@ -1,37 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Text; - -namespace Cartheur.Animals.Utilities -{ - /// - /// An encryption/decryption activity for aeon source files. - /// - public static class Base64Tool - { - /// - /// Performs a Base64 encode. - /// - /// The plain text. - /// - public static string Encode(string plainText) - { - if (plainText == "") return "Input string is null."; - var plainTextBytes = Encoding.UTF8.GetBytes(plainText); - return Convert.ToBase64String(plainTextBytes); - } - /// - /// Performs a Base64 decode. - /// - /// The Base64 encoded data. - /// - public static string Decode(string base64EncodedData) - { - if (base64EncodedData == "") return "Input string is null."; - byte[] base64EncodedBytes = Convert.FromBase64String(base64EncodedData); - return Encoding.UTF8.GetString(base64EncodedBytes, 0, base64EncodedBytes.Length); - } - } -} diff --git a/core/Utilities/Build.cs b/core/Utilities/Build.cs deleted file mode 100644 index 49157c3..0000000 --- a/core/Utilities/Build.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Reflection; -using System.IO; -using Cartheur.Animals.Core; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Contains the build details for the application. - /// - public static class Build - { - /// - /// The path to the executing assembly's debug folder. - /// - public static string DebugFolder = SharedFunctions.PathDebugFolder; - /// - /// The path to the executing assembly's release folder. - /// - public static string ReleaseFolder = SharedFunctions.PathReleaseFolder; - /// - /// A dictionary object that looks after all the settings associated with this aeon. - /// - public static SettingsDictionary BuildSettings; - - private static long compileTime = System.DateTime.UtcNow.Ticks; - /// - /// Returns the compilation date-time. - /// - public static long CompileTime { get => compileTime; set => compileTime = value; } - /// - /// Gets the linker time. - /// - /// The linker time. - /// Assembly. - /// Target. - public static DateTime GetLinkerTime(this Assembly assembly, TimeZoneInfo target = null) - { - var filePath = assembly.Location; - const int c_PeHeaderOffset = 60; - const int c_LinkerTimestampOffset = 8; - - var buffer = new byte[2048]; - - using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) - stream.Read(buffer, 0, 2048); - - var offset = BitConverter.ToInt32(buffer, c_PeHeaderOffset); - var secondsSince1970 = BitConverter.ToInt32(buffer, offset + c_LinkerTimestampOffset); - var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - - var linkTimeUtc = epoch.AddSeconds(secondsSince1970); - - var tz = target ?? TimeZoneInfo.Local; - var localTime = TimeZoneInfo.ConvertTimeFromUtc(linkTimeUtc, tz); - - return localTime; - } - /// - /// Gets the path to the build settings. - /// - public static string PathToBuildSettings - { - get - { - return Path.Combine(DebugFolder, Path.Combine("config", "Build.xml")); - } - } - - /// - /// Loads the build settings for aeon's environment. - /// - /// Path to the configuration file. - public static void LoadSettings(string settingsPath) - { - BuildSettings = new SettingsDictionary(); - BuildSettings.LoadSettings(settingsPath); - } - - } -} diff --git a/core/Utilities/Cryptography.cs b/core/Utilities/Cryptography.cs deleted file mode 100644 index 1bd384b..0000000 --- a/core/Utilities/Cryptography.cs +++ /dev/null @@ -1,85 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.IO; -using System.Security.Cryptography; -using System.Text; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Class to encrypt and decrypt files. - /// - public static class Cryptography - { - /// - /// Gets or sets the key. - /// - public static string Key { get; set; } - /// - /// Encrypts the file. - /// - /// The input file. - /// The output file. - /// The password. - public static void EncryptFile(string inputFile, string outputFile, string password) - { - try - { - //string password = @"myKey123"; // Your Key Here - UnicodeEncoding encoding = new UnicodeEncoding(); - byte[] key = encoding.GetBytes(password); - string cryptFile = outputFile; - FileStream fileStreamCrypt = new FileStream(cryptFile, FileMode.Create); - RijndaelManaged rijnManaged = new RijndaelManaged(); - CryptoStream cryptoStream = new CryptoStream(fileStreamCrypt, rijnManaged.CreateEncryptor(key, key), CryptoStreamMode.Write); - FileStream fileStreamInput = new FileStream(inputFile, FileMode.Open); - - int data; - while ((data = fileStreamInput.ReadByte()) != -1) - cryptoStream.WriteByte((byte)data); - - fileStreamInput.Close(); - cryptoStream.Close(); - fileStreamCrypt.Close(); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.Cryptography); - } - } - /// - /// Decrypts the file. - /// - /// The input file. - /// The output file. - /// The password. - public static void DecryptFile(string inputFile, string outputFile, string password) - { - try - { - //string password = @"myKey123"; // Your Key Here - UnicodeEncoding encoding = new UnicodeEncoding(); - byte[] key = encoding.GetBytes(password); - FileStream fileStreamCrypt = new FileStream(inputFile, FileMode.Open); - RijndaelManaged rijnManaged = new RijndaelManaged(); - CryptoStream cryptoStream = new CryptoStream(fileStreamCrypt, rijnManaged.CreateDecryptor(key, key), CryptoStreamMode.Read); - FileStream fileStreamOutput = new FileStream(outputFile, FileMode.Create); - - int data; - while ((data = cryptoStream.ReadByte()) != -1) - fileStreamOutput.WriteByte((byte) data); - - fileStreamOutput.Close(); - cryptoStream.Close(); - fileStreamCrypt.Close(); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.Cryptography); - } - - } - } -} diff --git a/core/Utilities/CustomTag.cs b/core/Utilities/CustomTag.cs deleted file mode 100644 index e9e77fe..0000000 --- a/core/Utilities/CustomTag.cs +++ /dev/null @@ -1,15 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Cartheur.Animals.Utilities -{ - /// - /// A custom attribute to be applied to all custom tags in external late-binding libraries. - /// - [AttributeUsage(AttributeTargets.Class)] - public class CustomTagAttribute : Attribute - { - } -} diff --git a/core/Utilities/DataOperations.cs b/core/Utilities/DataOperations.cs deleted file mode 100644 index b0cf9f0..0000000 --- a/core/Utilities/DataOperations.cs +++ /dev/null @@ -1,204 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using Cartheur.Animals.Core; - -namespace Cartheur.Animals.Utilities -{ - /// - /// A two tuple. - /// - /// The type of one. - /// The type of two. - public class TupleTwo : List> - { - /// - /// Adds the specified item. - /// - /// The item. - /// The item2. - public void Add(T1 item, T2 item2) - { - Add(new Tuple(item, item2)); - } - } - /// - /// A three tuple. - /// - /// The type of one. - /// The type of two. - /// The type of three. - public class TupleTwee : List> - { - /// - /// Adds the specified item. - /// - /// The item. - /// The item2. - /// The item3. - public void Add(T1 item, T2 item2, T3 item3) - { - Add(new Tuple(item, item2, item3)); - } - } - /// - /// - /// - /// The type of one. - /// The type of two. - /// The type of three. - /// The type of four. - public class TupleQuad : List> - { - /// - /// Adds the specified item. - /// - /// The item. - /// The item2. - /// The item3. - /// The item4. - public void Add(T1 item, T2 item2, T3 item3, T4 item4) - { - Add(new Tuple(item, item2, item3, item4)); - } - } - - /// - /// The class containing the data operations. - /// - public class DataOperations - { - /// - /// Gets or sets this aeon the operations apply to. - /// - protected Aeon ThisAeon { get; set; } - protected LoaderPaths Configuration; - /// - /// Gets or sets the freqeuncy word dictionary. - /// - protected Dictionary FreqeuncyWordDictionary { get; set; } - /// - /// Gets or sets the relationship list. - /// - protected List RelationshipList { get; set; } - /// - /// Gets or sets the item means sentence. - /// - public TupleTwo ItemMeansSentence { get; set; } - /// - /// Gets or sets the sentence weight single. - /// - public List SentenceWeightSingle { get; set; } - /// - /// Gets or sets the sentence weight duo. - /// - public TupleTwo SentenceWeightDuo { get; set; } - /// - /// Gets or sets the sentence weight triple. - /// - public TupleTwee SentenceWeightTriple { get; set; } - /// - /// Gets or sets the sentence weight four. - /// - public TupleQuad> SentenceWeightFour { get; set; } - /// - /// Compiles the training set. - /// - /// The file. - public static void CompileTrainingSet(StringBuilder file) - { - - } - /// - /// Stores the training set. - /// - /// The this aeon. - /// - public static bool StoreTrainingSet(Aeon thisAeon) - { - // Write to file for training set. - var fileOutput = new StringBuilder(); - - try - { - var streamWriter = new StreamWriter(Environment.CurrentDirectory + thisAeon.GlobalSettings.GrabSetting("learningdataset"), true); - streamWriter.WriteLine(fileOutput); - streamWriter.Close(); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.Me); - return false; - } - return true; - } - /// - /// Creates the training data. - /// - public void CreateTrainingData(string characteristicEquation) - { - Configuration = new LoaderPaths("Debug"); - ThisAeon = new Aeon(characteristicEquation); - ThisAeon.LoadSettings(Configuration.PathToSettings); - FreqeuncyWordDictionary = new Dictionary(); - ItemMeansSentence = new TupleTwo(); - SentenceWeightSingle = new List(); - SentenceWeightDuo = new TupleTwo(); - SentenceWeightTriple = new TupleTwee(); - SentenceWeightFour = new TupleQuad>(); - // Step 1: Create a dictionary object from the seed *.csv file. - using (var seedReader = new StreamReader(Environment.CurrentDirectory + ThisAeon.GlobalSettings.GrabSetting("learningdatasetseed"))) - { - while (!seedReader.EndOfStream) - { - var line = seedReader.ReadLine(); - var values = line.Split(','); - if (!FreqeuncyWordDictionary.ContainsKey(values[0])) - { - FreqeuncyWordDictionary.Add(values[0], Convert.ToInt32(values[1])); - } - } - } - // Step 2: Read the relationship-type file into a list. - var relationshipFile = File.ReadAllLines(Environment.CurrentDirectory + ThisAeon.GlobalSettings.GrabSetting("relationshipfile")); - RelationshipList = new List(relationshipFile).Distinct().ToList(); - // Step 3: Assigned a value to each sentence from the relationship list from a lookup in the dictionary. - // a. Split the sentences and lookup each word from the dictionary. - // b. Compute the mean value of each sentence value. - // c. Store the value along with the word count of each sentence into a tuple. - foreach (var sentence in RelationshipList) - { - var words = sentence.Split(' '); - var itemMean = new List(); - foreach (var s in words) - { - if (FreqeuncyWordDictionary.ContainsKey(s)) - { - var itemValue = FreqeuncyWordDictionary[s]; - ItemMeansSentence.Add(itemValue, sentence); - itemMean.Add(itemValue); - } - } - var meanValueZipf = itemMean.Count > 0 ? itemMean.Average() : 0.0; - SentenceWeightSingle.Add(meanValueZipf); - SentenceWeightDuo.Add(meanValueZipf, words.Count()); - SentenceWeightTriple.Add(meanValueZipf, words.Count(), sentence.Length); - SentenceWeightFour.Add(meanValueZipf, words.Count(), sentence.Length, ItemMeansSentence); - } - // Step 4: Congratulations, you now have the compiled training list with a tuple containing the index to prevent entropy and aid in training the algorithm as I think one needs the answer to be able to determine if it is functioning correctly. Not exactly sure of the object format as it is a little heavy now. Later. - // Or how about persisting the dataobjects for use in the training data, which by the way would be the better option?! - } - } - /// - /// The extension class for probability utilities. - /// - public static class ProbabilityUtilities - { - // Was Zipf from the MathNet library. - } -} diff --git a/core/Utilities/Exceptions.cs b/core/Utilities/Exceptions.cs deleted file mode 100644 index 6d145c4..0000000 --- a/core/Utilities/Exceptions.cs +++ /dev/null @@ -1,18 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Cartheur.Animals.Utilities -{ - class PinAlreadyExportedException : Exception - { - public PinAlreadyExportedException() - : base() - { } - - public PinAlreadyExportedException(string message) - : base(message) - { } - } -} diff --git a/core/Utilities/GpioPin.cs b/core/Utilities/GpioPin.cs deleted file mode 100644 index 2a716c4..0000000 --- a/core/Utilities/GpioPin.cs +++ /dev/null @@ -1,171 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.IO; - -namespace Cartheur.Animals.Utilities -{ - public class GPIOPinDriver : IDisposable - { - private const string GPIO_ROOT_DIR = "/sys/class/gpio/"; - private static List _exported_pins = new List(); - private bool _disposed; - private Pin _gpioPin; - private GPIODirection _gpioDirection; - - /// - /// The set of chip GPIO pins. - /// - public enum Pin - { - XIOP0, - XIOP1, - XIOP2, - XIOP3, - XIOP4, - XIOP5, - XIOP6, - XIOP7, - XIOP8 - }; - /// - /// Direction of the GPIO Pin - /// - public enum GPIODirection - { - In, - Out - }; - /// - /// The value (High or Low) of a GPIO pin. - /// - public enum GPIOState - { - Low = 0, - High = 1 - }; - /// - /// Sets up an interface for accessing the specified GPIO pin with direction set to OUT and initial value to LOW. - /// - /// The GPIO pin to be accessed - public GPIOPinDriver(Pin gpioPin) - : this(gpioPin, GPIODirection.Out, GPIOState.Low) { } - - /// - /// Sets up an interface for accessing the specified GPIO pin with the given direction and initial value set to LOW. - /// - /// The GPIO pin to be accessed. - /// The direction the GPIO pin should have. - public GPIOPinDriver(Pin gpioPin, GPIODirection direction) - : this(gpioPin, direction, GPIOState.Low) { } - - /// - /// Sets up an interface for accessing the specified GPIO pin with the given direction and given initial value. - /// - /// The GPIO pin to be accessed. - /// The direction the GPIO pin should have. - /// The initial value the GPIO pin should have. - public GPIOPinDriver(Pin gpioPin, GPIODirection direction, GPIOState initialValue) - { - this._disposed = false; - this.GPIOPin = gpioPin; - this.Direction = direction; - if (this.Direction == GPIODirection.Out) - { - this.State = initialValue; - } - } - /// - /// Gets the GPIO pin number. - /// - public Pin GPIOPin - { - get { return _gpioPin; } - private set - { - lock (_exported_pins) - { - if (_disposed) - throw new ObjectDisposedException("Selected pin has been disposed."); - else if (_exported_pins.IndexOf(value) != -1) - throw new PinAlreadyExportedException("Requested pin is already exported."); - else - { // 0 1 2 3 4 5 - File.WriteAllText(GPIO_ROOT_DIR + "export", value.ToString().Substring(4)); // G P I O 8 - _exported_pins.Add(value); - _gpioPin = value; - } - } - } - } - /// - /// Gets or sets the direction of of an output GPIO pin. - /// - public GPIODirection Direction - { - get { return _gpioDirection; } - set - { - if (_disposed) - throw new ObjectDisposedException("Selected pin has been disposed."); - else - { - File.WriteAllText(String.Format("{0}gpio{1}/direction", GPIO_ROOT_DIR, GPIOPin.ToString().Substring(4)), (value == GPIODirection.In ? "in" : "out")); - _gpioDirection = value; - } - } - } - /// - /// The current value of a GPIO pin. - /// - public GPIOState State - { - get - { - if (_disposed) - throw new ObjectDisposedException("Selected pin has been disposed."); - else - { - string state = File.ReadAllText(String.Format("{0}gpio{1}/value", GPIO_ROOT_DIR, GPIOPin.ToString().Substring(4))); - return (state[0] == '1' ? GPIOState.High : GPIOState.Low); - } - } - set - { - if (_disposed) - throw new ObjectDisposedException("Selected pin has been disposed."); - else if (this.Direction == GPIODirection.In) - throw new InvalidOperationException("State of an input pin can only be read."); - else - { - File.WriteAllText(String.Format("{0}gpio{1}/value", GPIO_ROOT_DIR, GPIOPin.ToString().Substring(4)), (value == GPIOState.High ? "1" : "0")); - } - } - } - /// - /// Unexports the GPIO interface. - /// - public void Unexport() - { - if (!_disposed) - Dispose(); - } - - public void Dispose() - { - if (_disposed) - throw new ObjectDisposedException("Selected pin has already been disposed."); - File.WriteAllText(GPIO_ROOT_DIR + "unexport", GPIOPin.ToString().Substring(4)); - _exported_pins.Remove(this.GPIOPin); - _disposed = true; - } - - ~GPIOPinDriver() - { - if (!_disposed) - Dispose(); - } - } -} diff --git a/core/Utilities/LoaderPaths.cs b/core/Utilities/LoaderPaths.cs deleted file mode 100644 index ebd4360..0000000 --- a/core/Utilities/LoaderPaths.cs +++ /dev/null @@ -1,254 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.IO; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Sets the paths for the files given the configuration, either debug or release. - /// - public class LoaderPaths - { - /// - /// The active configuration for the application runtume. - /// - public string ActiveRuntime; - /// - /// Initializes a new instance of the class with a build configuration. - /// - /// The active runtime configuration. - public LoaderPaths(string configuration) - { - if (configuration == "Debug") - ActiveRuntime = SharedFunctions.PathDebugFolder; - if (configuration == "Release") - ActiveRuntime = SharedFunctions.PathReleaseFolder; - } - /// - /// Gets the path to the nucode file area. - /// - public string PathToNucode - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("nucodedirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to xms file storage. - /// - public string PathToXms - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("xmsdirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to the friendly personality. - /// - public string PathToFriendlyPersonality - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("personalitydirectoryfriendly")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to the play personality. - /// - public string PathToPlayPersonality - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("personalitydirectoryplay")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to the default personality. - /// - public string PathToDefaultPersonality - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("personalitydirectorydefault")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to the toy personality. - /// - public string PathToToyPersonality - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("personalitydirectorytoy")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to the aeon-assist personality. - /// - public string PathToAeonAssist - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("aeonassistdirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to reductions. - /// - public string PathToReductions - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("reductionsdirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to mindpixel. - /// - public string PathToMindpixel - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("mindpixeldirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to update. - /// - public string PathToUpdate - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("updatedirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to configuration files. - /// - public string PathToConfigFiles - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("configdirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to extra compiled libraries. - /// - public string PathToLibraries - { - get - { - return Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("librariesdirectory")); - } - } - /// - /// Gets the path to the build settings. - /// - public string PathToBuildSettings - { - get - { - return Path.Combine(ActiveRuntime, Path.Combine("config", "Build.xml")); - } - } - /// - /// Gets the path to the settings. - /// - public string PathToSettings - { - get - { - return Path.Combine(ActiveRuntime, Path.Combine("config", "Settings.xml")); - } - } - /// - /// Gets the path to extra file fragments. - /// - public string PathToFragments - { - get - { - return Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("fragmentsdirectory")); - } - } - /// - /// Gets the path to learning map. - /// - public string PathToLearningMap - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("mapdirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to encrypted files. - /// - public string PathToEncryptedFiles - { - get - { - return Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("encryptedfilesdirectory")); - } - } - /// - /// Gets the path to the blank file. - /// - public string PathToBlankFile - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("blankdirectory")); - return new Uri(path).LocalPath; - } - } - /// - /// Gets the path to the python or lua script files. - /// - public string PathToScripts - { - get - { - return Path.Combine(ActiveRuntime, "scripts"); - } - } - /// - /// Gets the path to the language processing model files. - /// - public string PathToLanguageModel - { - get - { - return Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("languagemodeldirectory")); - } - } - /// - /// Gets the path to tonal language file definitions. - /// - public string PathToTonalRoot - { - get - { - var path = Path.Combine(ActiveRuntime, SharedFunctions.ThisAeon.GlobalSettings.GrabSetting("tonalrootdirectory")); - return new Uri(path).LocalPath; - } - } - } -} diff --git a/core/Utilities/Logger.cs b/core/Utilities/Logger.cs deleted file mode 100644 index 187e737..0000000 --- a/core/Utilities/Logger.cs +++ /dev/null @@ -1,424 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.IO; -using System.Text; - -namespace Cartheur.Animals.Utilities -{ - /// - /// The class which performs logging for the library. Originated in MacOS 9.0.4 (via CodeWarrior in SheepShaver, September - December 2014). - /// - public static class Logging - { - private static bool _fileCreated = false; - /// - /// Default logging and transcripting if the setting is left blank in the config file. - /// - private static string LogModelName { get { return @"logfile"; } } - private static string TranscriptModelName { get { return @"transcript"; } } - /// - /// The active configuration of the application. - /// - public static string ActiveConfiguration { get; set; } - /// - /// The type of model to use for logging. - /// - public static string LogModelFile { get; set; } - /// - /// The type of model to use for the transcript. - /// - public static string TranscriptModelFile { get; set; } - /// - /// Whether or not running tests. - /// - public static bool TestExecution { get; set; } - /// - /// The path for logging and transcripting when testing. - /// - public static string TestingPath { get; set; } - /// - /// The file path for executing assemblies. Set to true and indicate the . Set the active configuration parameter first. - /// - public static string FilePath() - { - if (TestExecution) - return TestingPath; - if (ActiveConfiguration == "") - return Environment.CurrentDirectory; - else - return ActiveConfiguration; - } - - /// - /// The type of log to write. - /// - public enum LogType - { - /// - /// The informational log. - /// - Information, - /// - /// The error log. - /// - Error, - /// - /// The gossip log. - /// - Gossip, - /// - /// The temporal log. - /// - Temporal, - /// - /// The warning log. - /// - Warning - }; - /// - /// The classes within the interpreter calling the log. - /// - public enum LogCaller - { - /// - /// The aeon. - /// - Aeon, - /// - /// The aeon runtime application. - /// - AeonRuntime, - /// - /// The aeon loader. - /// - AeonLoader, - /// - /// The booth runtime aeon application. - /// - Booth, - /// - /// The bot. - /// - Bot, - /// - /// The conversational aeon application. - /// - ConversationalAeonApplication, - /// - /// The cognizance ideal. - /// - Cognizance, - /// - /// The conditional manager. - /// - Condition, - /// - /// The cryptography engine. - /// - Cryptography, - /// - /// The onstage demo aeon application. - /// - Demo, - /// - /// The emotive display. - /// - EmotiveDisplay, - /// - /// The external bear connection (puppeteering). - /// - ExternalBear, - /// - /// The external robot connection (puppeteering). - /// - ExternalRobotConnection, - /// - /// The file template. - /// - FileTemplate, - /// - /// The get. - /// - Get, - /// - /// The gossip. - /// - Gossip, - /// - /// The input. - /// - Input, - /// - /// The interaction. - /// - Interaction, - /// - /// The indications. - /// - Indications, - /// - /// The learn. - /// - Learn, - /// - /// The learning thread. - /// - LearningThread, - /// - /// M.E. - /// - Me, - /// - /// The mono runtime. - /// - MonoRuntime, - /// - /// The mood. - /// - Mood, - /// - /// The nao voicing application. - /// - NaoVoicingApplication, - /// - /// The node. - /// - Node, - /// - /// The non emotive aeon. - /// - NonEmotiveAeon, - /// - /// The robot dialogue. - /// - RobotDialogue, - /// - /// The result. - /// - Result, - /// - /// The script. - /// - Script, - /// - /// The set. - /// - Set, - /// - /// The shared function. - /// - SharedFunction, - /// - /// The speech recognizer. - /// - SpeechRecognizer, - /// - /// The star lexicon. - /// - Star, - /// - /// The test framework. - /// - TestFramework, - /// - /// The that lexicon. - /// - That, - /// - /// The that star lexicon. - /// - ThatStar, - /// - /// The think. - /// - Think, - /// - /// The topic star lexicon. - /// - TopicStar, - /// - /// The XMS. - /// - Xms - } - /// - /// The last message passed to logging. - /// - public static string LastMessage = ""; - /// - /// The delegate for returning the last log message to the calling application. - /// - public delegate void LoggingDelegate(); - /// - /// Occurs when [returned to console] is called. - /// - public static event LoggingDelegate ReturnedToConsole; - /// - /// Optional means to model the logfile from its original "logfile" model. - /// - /// - /// The path for the logfile. - public static void ChangeLogModel(string modelName) - { - LogModelFile = modelName; - } - - /// - /// Logs a message sent from the calling application to a file. - /// - /// The message to log. Space between the message and log type enumeration provided. - /// Type of the log. - /// The class creating the log entry. - public static void WriteLog(string message, LogType logType, LogCaller caller) - { - if(LogModelFile == null) - { - LogModelFile = LogModelName; - } - LastMessage = message; - // Use FilePath() when outside of a test framework. - StreamWriter stream = new StreamWriter(FilePath() + @"/logs/" + LogModelFile + @".txt", true); - switch (logType) - { - case LogType.Error: - stream.WriteLine(DateTime.Now + " - " + " ERROR " + " - " + message + " from class " + caller + "."); - break; - case LogType.Warning: - stream.WriteLine(DateTime.Now + " - " + " WARNING " + " - " + message + " from class " + caller + "."); - break; - case LogType.Information: - stream.WriteLine(DateTime.Now + " - " + message + ". This was called from the class " + caller + "."); - break; - case LogType.Temporal: - stream.WriteLine(DateTime.Now + " - " + message + "."); - break; - case LogType.Gossip: - stream.WriteLine(DateTime.Now + " - " + message + "."); - break; - } - stream.Close(); - if (!Equals(null, ReturnedToConsole)) - { - ReturnedToConsole(); - } - } - /// - /// Records a transcript of the conversation. - /// - /// The message to save in transcript format. - /// Inserts a new line, if required. - /// Use for saving iterative transcript files. - public static void RecordTranscript(string message, int fileNumber, bool insertNewLine = false) - { - try - { - StreamWriter stream = new StreamWriter(FilePath() + @"/logs/transcript.txt", true); - if (!_fileCreated && fileNumber == 0) - { - // File has not been created previously, write the header to the file. - stream.WriteLine(@"August 2017 Template" + Environment.NewLine + @"A transcript log for an interative conversation between two aeons, in pursuit of validation / critique of a paper as well as outlining an example of ethical application."); - stream.WriteLine(Environment.NewLine); - _fileCreated = true; - } - if (fileNumber != 0) - { - stream.Dispose(); - stream = new StreamWriter(FilePath() + @"/logs/transcript" + fileNumber + ".txt", true); - if (!_fileCreated) - { - stream.WriteLine(@"August 2017 Template" + Environment.NewLine + @"A transcript log for an interative conversation between two aeons, in pursuit of validation / critique of a paper as well as outlining an example of ethical application."); - stream.WriteLine(Environment.NewLine); - _fileCreated = true; - } - } - if (insertNewLine) - stream.WriteLine(Environment.NewLine); - stream.WriteLine(message); - stream.Close(); - } - catch (Exception ex) - { - WriteLog(ex.Message, LogType.Error, LogCaller.Me); - } - - } - /// - /// Records a transcript of the conversation. - /// - /// The message to save in transcript format. - public static void RecordTranscript(string message) - { - if (TranscriptModelFile == "") - { - TranscriptModelFile = TranscriptModelName; - } - try - { - // Use FilePath() when outside of a test framework. - StreamWriter stream = new StreamWriter(FilePath() + @"/logs/" + TranscriptModelFile + @".txt", true); - stream.WriteLine(DateTime.Now + " - " + message); - stream.Close(); - } - catch (Exception ex) - { - WriteLog(ex.Message, LogType.Error, LogCaller.Me); - } - - } - /// - /// Saves the last result to support analysis of the algorithm. - /// - /// The output from the conversation. - public static void SaveLastResult(StringBuilder output) - { - try - { - // Use FilePath() when outside of a test framework. - StreamWriter stream = new StreamWriter(FilePath() + @"/db/analytics.txt", true); - stream.WriteLine(DateTime.Now + " - " + output); - stream.Close(); - } - catch (Exception ex) - { - WriteLog(ex.Message, LogType.Error, LogCaller.Me); - } - - } - /// - /// Saves the last result to support analysis of the algorithm to storage. - /// - /// The output from the conversation. - public static void SaveLastResultToStorage(StringBuilder output) - { - try - { - // Use FilePath() when outside of a test framework. - StreamWriter stream = new StreamWriter(FilePath() + @"/db/analyticsStorage.txt", true); - stream.WriteLine("#" + DateTime.Now + ";" + output); - stream.Close(); - } - catch (Exception ex) - { - WriteLog(ex.Message, LogType.Error, LogCaller.Me); - } - - } - /// - /// Writes a debug log with object parameters. - /// - /// The objects. - public static void Debug(params object[] objects) - { - // Use FilePath() when outside of a test framework. - StreamWriter stream = new StreamWriter(FilePath() + @"/logs/debugdump.txt", true); - foreach (object obj in objects) - { - stream.WriteLine(obj); - } - stream.WriteLine("--"); - stream.Close(); - } - } -} diff --git a/core/Utilities/SerializeDictionary.cs b/core/Utilities/SerializeDictionary.cs deleted file mode 100644 index f77a259..0000000 --- a/core/Utilities/SerializeDictionary.cs +++ /dev/null @@ -1,241 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Runtime.Serialization; -using System.Xml; -using System.Xml.Schema; -using System.Xml.Serialization; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Represents an xml serializable collection of keys and values. - /// - /// The type of the keys in the dictionary. - /// The type of the values in the dictionary. - [Serializable] - [XmlRoot("root")] - public class SerializeDictionary : Dictionary, IXmlSerializable - { - /// - /// The default XML tag name for an item. - /// - private const string DefaultItemTag = "item"; - /// - /// The default XML tag name for a key. - /// - private const string DefaultKeyTag = "key"; - /// - /// The default XML tag name for a value. - /// - private const string DefaultValueTag = "value"; - /// - /// The XML serializer for the key type. - /// - private static readonly XmlSerializer KeySerializer = new XmlSerializer(typeof(TKey)); - /// - /// The XML serializer for the value type. - /// - private static readonly XmlSerializer ValueSerializer = new XmlSerializer(typeof(TValue)); - /// - /// Initializes a new instance of the - /// class. - /// - public SerializeDictionary() { } - /// - /// Initializes a new instance of the - /// class. - /// - /// A - /// object - /// containing the information required to serialize the - /// . - /// A - /// structure - /// containing the source and destination of the serialized stream - /// associated with the - /// . - protected SerializeDictionary(SerializationInfo info, StreamingContext context) - : base(info, context) { } - /// - /// Gets the XML tag name for an item. - /// - protected virtual string ItemTagName - { - get - { - return DefaultItemTag; - } - } - /// - /// Gets the XML tag name for a key. - /// - protected virtual string KeyTagName - { - get - { - return DefaultKeyTag; - } - } - /// - /// Gets the XML tag name for a value. - /// - protected virtual string ValueTagName - { - get - { - return DefaultValueTag; - } - } - /// - /// Gets the XML schema for the XML serialization. - /// - /// An XML schema for the serialized object. - public XmlSchema GetSchema() - { - return null; - } - /// - /// Deserializes the object from XML. - /// - /// The XML representation of the object. - public void ReadXml(XmlReader reader) - { - var wasEmpty = reader.IsEmptyElement; - - reader.Read(); - if (wasEmpty) - { - return; - } - - try - { - while (reader.NodeType != XmlNodeType.EndElement) - { - ReadItem(reader); - reader.MoveToContent(); - } - } - finally - { - reader.ReadEndElement(); - } - } - /// - /// Serializes this instance to XML. - /// - /// The XML writer to serialize to. - public void WriteXml(XmlWriter writer) - { - foreach (var keyValuePair in this) - { - WriteItem(writer, keyValuePair); - } - } - /// - /// Deserializes the dictionary item. - /// - /// The XML representation of the object. - private void ReadItem(XmlReader reader) - { - reader.ReadStartElement(ItemTagName); - try - { - Add(ReadKey(reader), ReadValue(reader)); - } - finally - { - reader.ReadEndElement(); - } - } - /// - /// Deserializes the dictionary item's key. - /// - /// The XML representation of the object. - /// The dictionary item's key. - private TKey ReadKey(XmlReader reader) - { - reader.ReadStartElement(KeyTagName); - try - { - return (TKey)KeySerializer.Deserialize(reader); - } - finally - { - reader.ReadEndElement(); - } - } - /// - /// Deserializes the dictionary item's value. - /// - /// The XML representation of the object. - /// The dictionary item's value. - private TValue ReadValue(XmlReader reader) - { - reader.ReadStartElement(ValueTagName); - try - { - return (TValue)ValueSerializer.Deserialize(reader); - } - finally - { - reader.ReadEndElement(); - } - } - /// - /// Serializes the dictionary item. - /// - /// The XML writer to serialize to. - /// The key/value pair. - private void WriteItem(XmlWriter writer, KeyValuePair keyValuePair) - { - writer.WriteStartElement(ItemTagName); - try - { - WriteKey(writer, keyValuePair.Key); - WriteValue(writer, keyValuePair.Value); - } - finally - { - writer.WriteEndElement(); - } - } - /// - /// Serializes the dictionary item's key. - /// - /// The XML writer to serialize to. - /// The dictionary item's key. - private void WriteKey(XmlWriter writer, TKey key) - { - writer.WriteStartElement(KeyTagName); - try - { - KeySerializer.Serialize(writer, key); - } - finally - { - writer.WriteEndElement(); - } - } - /// - /// Serializes the dictionary item's value. - /// - /// The XML writer to serialize to. - /// The dictionary item's value. - private void WriteValue(XmlWriter writer, TValue value) - { - writer.WriteStartElement(ValueTagName); - try - { - ValueSerializer.Serialize(writer, value); - } - finally - { - writer.WriteEndElement(); - } - } - } -} diff --git a/core/Utilities/SerializeHashtable.cs b/core/Utilities/SerializeHashtable.cs deleted file mode 100644 index a90dbef..0000000 --- a/core/Utilities/SerializeHashtable.cs +++ /dev/null @@ -1,98 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; -using System.Xml; -using System.Xml.Serialization; - -namespace Cartheur.Animals.Utilities -{ - /// - /// The serial hashtable class. - /// - public class SerializeHashtable : Hashtable, IXmlSerializable - { - public System.Xml.Schema.XmlSchema GetSchema() - { - return null; - } - /// - /// Generates an object from its XML representation. - /// - /// The stream from which the object is deserialized. - public void ReadXml(XmlReader reader) - { - // Start to use the reader. - reader.Read(); - // Read the first element ie root of this object - reader.ReadStartElement("root"); - - // Read all elements - while(reader.NodeType != XmlNodeType.EndElement) - { - // parsing the item - reader.ReadStartElement("item"); - - // PArsing the key and value - string key = reader.ReadElementString("key"); - string value = reader.ReadElementString("value"); - - // en reading the item. - reader.ReadEndElement(); - reader.MoveToContent(); - - // add the item - Add(key, value); - } - // Extremely important to read the node to its end. Next call of the reader methods will crash if not called. - reader.ReadEndElement(); - } - /// - /// Converts an object into its XML representation. - /// - /// The stream to which the object is serialized. - public void WriteXml(XmlWriter writer) - { - // Write the root elemnt - writer.WriteStartElement("root"); - - // For each object in this - foreach(object key in Keys) - { - object value = this[key]; - // Write item, key and value - writer.WriteStartElement("item"); - writer.WriteElementString("key", key.ToString()); - writer.WriteElementString("value", value.ToString()); - - // write - writer.WriteEndElement(); - } - // write - writer.WriteEndElement(); - } - /// - /// Saves the Xml hash to a file. - /// - /// The hash. - /// The filename. - public static void SaveXml(Hashtable hash, string filename) - { - System.IO.StreamWriter stream = null; - try - { - stream = new System.IO.StreamWriter(filename); - XmlSerializer serialize = new XmlSerializer(hash.GetType()); - serialize.Serialize(stream, hash); - stream.Close(); - } - catch(Exception ex) - { - if (stream != null) - stream.Close(); - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.Get); - } - } - } -} diff --git a/core/Utilities/SharedFunctions.cs b/core/Utilities/SharedFunctions.cs deleted file mode 100644 index a71edcf..0000000 --- a/core/Utilities/SharedFunctions.cs +++ /dev/null @@ -1,141 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.IO; -using System.Reflection; -using Cartheur.Animals.Core; - -namespace Cartheur.Animals.Utilities -{ - /// - /// A static class containing commonly-used (shared) functions. - /// - public static class SharedFunctions - { - /// - /// The application version information. - /// - public static string ApplicationVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); - /// - /// The path to the debug folder. - /// - public static string PathDebugFolder = Environment.CurrentDirectory + @""; - /// - /// The path to the release folder. - /// - public static string PathReleaseFolder = Path.Combine(Environment.CurrentDirectory, "animals", @""); - /// - /// Gets or sets the aeon. - /// - public static Aeon ThisAeon { get; set; } - /// - /// Loads the dictionaries. - /// - /// The this aeon. - /// The active configuration. - public static bool LoadDictionaries(this Aeon thisAeon, LoaderPaths configuration) - { - ThisAeon = thisAeon; - try - { - // Load various default settings and text tools. - ThisAeon.PersonSubstitutions.LoadSettings(Path.Combine(configuration.PathToConfigFiles, ThisAeon.GlobalSettings.GrabSetting("personsubstitutionsfile"))); - ThisAeon.DefaultPredicates.LoadSettings(Path.Combine(configuration.PathToConfigFiles, ThisAeon.GlobalSettings.GrabSetting("defaultpredicates"))); - ThisAeon.Substitutions.LoadSettings(Path.Combine(configuration.PathToConfigFiles, ThisAeon.GlobalSettings.GrabSetting("substitutionsfile"))); - ThisAeon.LoadSplitters(Path.Combine(configuration.PathToConfigFiles, ThisAeon.GlobalSettings.GrabSetting("splittersfile"))); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.SharedFunction); - return false; - } - return true; - - } - /// - /// Loads the personality by aeon's name. - /// - /// The this aeon. - /// The active configuration. - /// - public static bool LoadPersonality(this Aeon thisAeon, LoaderPaths configuration) - { - ThisAeon = thisAeon; - try - { - var loader = new AeonLoader(ThisAeon); - ThisAeon.IsAcceptingUserInput = false; - // Load in the proper order. - if (ThisAeon.Name.ToLower() == "aeon") - { - loader.LoadAeon(configuration.PathToAeonAssist); - } - if (ThisAeon.Name.ToLower() == "henry" || ThisAeon.Name.ToLower() == "fred") - { - loader.LoadAeon(configuration.PathToReductions); - loader.LoadAeon(configuration.PathToMindpixel); - loader.LoadAeon(configuration.PathToToyPersonality); - loader.LoadAeon(configuration.PathToUpdate); - loader.LoadAeon(configuration.PathToFragments); - } - if (ThisAeon.Name.ToLower() == "rhodo") - { - loader.LoadAeon(configuration.PathToReductions); - loader.LoadAeon(configuration.PathToMindpixel); - loader.LoadAeon(configuration.PathToDefaultPersonality); - loader.LoadAeon(configuration.PathToUpdate); - loader.LoadAeon(configuration.PathToFragments); - } - if (ThisAeon.Name.ToLower() == "samantha") - { - loader.LoadAeon(configuration.PathToReductions); - loader.LoadAeon(configuration.PathToMindpixel); - loader.LoadAeon(configuration.PathToFriendlyPersonality); - loader.LoadAeon(configuration.PathToUpdate); - loader.LoadAeon(configuration.PathToFragments); - } - if (ThisAeon.Name.ToLower() == "mitsuku") - { - loader.LoadAeon(configuration.PathToReductions); - loader.LoadAeon(configuration.PathToMindpixel); - loader.LoadAeon(configuration.PathToPlayPersonality); - loader.LoadAeon(configuration.PathToUpdate); - loader.LoadAeon(configuration.PathToFragments); - } - Logging.WriteLog(@"Personality loaded, baseline personality is set to " + ThisAeon.Name.ToLower(), Logging.LogType.Information, Logging.LogCaller.SharedFunction); - ThisAeon.IsAcceptingUserInput = true; - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.SharedFunction); - return false; - } - return true; - } - /// - /// Loads a blank robot. - /// - /// - /// - /// - public static bool LoadBlank(this Aeon thisAeon, LoaderPaths configuration) - { - ThisAeon = thisAeon; - try - { - var loader = new AeonLoader(ThisAeon); - ThisAeon.IsAcceptingUserInput = false; - loader.LoadAeon(configuration.PathToBlankFile); - Logging.WriteLog(@"Blank robot loaded", Logging.LogType.Information, Logging.LogCaller.SharedFunction); - ThisAeon.IsAcceptingUserInput = true; - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.SharedFunction); - return false; - } - return true; - } - } -} diff --git a/core/Utilities/StaticRandom.cs b/core/Utilities/StaticRandom.cs deleted file mode 100644 index 40b9509..0000000 --- a/core/Utilities/StaticRandom.cs +++ /dev/null @@ -1,82 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Thread-safe equivalent of System.Random using static methods. - /// - public static class StaticRandom - { - static readonly Random Random = new Random(); - static readonly object StaticRandomLock = new object(); - /// - /// Returns a nonnegative random number. - /// - /// A 32-bit signed integer greater than or equal to zero and less than Int32.MaxValue. - public static int Next() - { - lock (StaticRandomLock) - { - return Random.Next(); - } - } - /// - /// Returns a nonnegative random number less than the specified maximum. - /// - /// - /// A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values includes zero but not maxValue. - /// - /// If maxValue is less than zero. - public static int Next(int max) - { - lock (StaticRandomLock) - { - return Random.Next(max); - } - } - /// - /// Returns a random number within a specified range. - /// - /// The inclusive lower bound of the random number returned. - /// - /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue. - /// - /// - /// A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned. - /// - /// If minValue is greater than maxValue. - public static int Next(int min, int max) - { - lock (StaticRandomLock) - { - return Random.Next(min, max); - } - } - /// - /// Returns a random number between 0.0 and 1.0. - /// - /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0. - public static double NextDouble() - { - lock (StaticRandomLock) - { - return Random.NextDouble(); - } - } - /// - /// Fills the elements of a specified array of bytes with random numbers. - /// - /// An array of bytes containing random numbers. - /// If buffer is null. - public static void NextBytes(byte[] buffer) - { - lock (StaticRandomLock) - { - Random.NextBytes(buffer); - } - } - } -} diff --git a/core/Utilities/TagHandler.cs b/core/Utilities/TagHandler.cs deleted file mode 100644 index 257a15d..0000000 --- a/core/Utilities/TagHandler.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections.Generic; -using System.Reflection; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Encapsulates information about a custom tag class. - /// - public class TagHandler - { - /// - /// The assembly this class is found in. - /// - public string AssemblyName; - /// - /// The class name for the assembly. - /// - public string ClassName; - /// - /// The name of the tag. - /// - public string TagName; - /// - /// Provides an instantiation of the class represented by this tag handler. - /// - /// All the assemblies the bot knows about. - /// The instantiated class. - public AeonTagHandler Instantiate(Dictionary assemblies) - { - if (assemblies.ContainsKey(AssemblyName)) - { - Assembly tagDll = assemblies[AssemblyName]; - Type[] tagDllTypes = tagDll.GetTypes(); - return (AeonTagHandler)tagDll.CreateInstance(ClassName); - } - return null; - } - } -} diff --git a/core/Utilities/TextTransformer.cs b/core/Utilities/TextTransformer.cs deleted file mode 100644 index 65d3154..0000000 --- a/core/Utilities/TextTransformer.cs +++ /dev/null @@ -1,87 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using Cartheur.Animals.Core; - -namespace Cartheur.Animals.Utilities -{ - /// - /// Encapsulates all the required methods and attributes for any text transformation. An input string is provided and various methods and attributes can be used to grab a transformed string. The protected ProcessChange() method is abstract and should be overridden to contain the code for transforming the input text into the output text. - /// - public abstract class TextTransformer - { - /// - /// Instance of the input string. - /// - string _inputString; - /// - /// The aeon that this transformation is connected with. - /// - public Aeon ThisAeon; - /// - /// The input string to be transformed. - /// - public string InputString - { - get { return _inputString; } - set { _inputString = value; } - } - /// - /// The transformed string. - /// - public string OutputString - { - get { return Transform(); } - } - /// - /// Initializes a new instance of the class. - /// - /// The aeon is this transformer a part of. - /// The input string to be transformed. - protected TextTransformer(Aeon aeon, string inputString) - { - ThisAeon = aeon; - _inputString = inputString; - } - /// - /// Initializes a new instance of the class. - /// - /// The aeon this transformer is a part of. - protected TextTransformer(Aeon aeon) - { - ThisAeon = aeon; - _inputString = string.Empty; - } - /// - /// Initializes a new instance of the class. Used as part of late-binding mechanism. - /// - protected TextTransformer() - { - ThisAeon = null; - _inputString = string.Empty; - } - /// - /// Do a transformation on the supplied input string. - /// - /// The string to be transformed. - /// The resulting output. - public string Transform(string input) - { - _inputString = input; - return Transform(); - } - /// - /// Do a transformation on the string found in the InputString attribute. - /// - /// The resulting transformed string. - public string Transform() - { - return _inputString.Length > 0 ? ProcessChange() : string.Empty; - } - /// - /// The method that does the actual processing of the text. - /// - /// The resulting processed text. - protected abstract string ProcessChange(); - } -} diff --git a/core/core.csproj b/core/core.csproj deleted file mode 100644 index 80e4ee1..0000000 --- a/core/core.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - 2.1.5 - net6.0 - - - diff --git a/core/flow-patterns/Figure 1.jpg b/core/flow-patterns/Figure 1.jpg deleted file mode 100644 index d2da9ef..0000000 Binary files a/core/flow-patterns/Figure 1.jpg and /dev/null differ diff --git a/core/flow-patterns/Figure 2.jpg b/core/flow-patterns/Figure 2.jpg deleted file mode 100644 index 00d246b..0000000 Binary files a/core/flow-patterns/Figure 2.jpg and /dev/null differ diff --git a/core/flow-patterns/Figure 3.jpg b/core/flow-patterns/Figure 3.jpg deleted file mode 100644 index 6e45198..0000000 Binary files a/core/flow-patterns/Figure 3.jpg and /dev/null differ diff --git a/core/flow-patterns/Figure 4.jpg b/core/flow-patterns/Figure 4.jpg deleted file mode 100644 index 935cf3c..0000000 Binary files a/core/flow-patterns/Figure 4.jpg and /dev/null differ diff --git a/core/flow-patterns/Figure 5.jpg b/core/flow-patterns/Figure 5.jpg deleted file mode 100644 index 21dcd83..0000000 Binary files a/core/flow-patterns/Figure 5.jpg and /dev/null differ diff --git a/core/flow-patterns/Figure 6.jpg b/core/flow-patterns/Figure 6.jpg deleted file mode 100644 index 56b83c6..0000000 Binary files a/core/flow-patterns/Figure 6.jpg and /dev/null differ diff --git a/core/flow-patterns/Figure 7.jpg b/core/flow-patterns/Figure 7.jpg deleted file mode 100644 index 8b180d7..0000000 Binary files a/core/flow-patterns/Figure 7.jpg and /dev/null differ diff --git a/docker/Dockerfile b/docker/Dockerfile deleted file mode 100644 index 9030051..0000000 --- a/docker/Dockerfile +++ /dev/null @@ -1,40 +0,0 @@ -FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build -WORKDIR /source - -# Copy the *.csproj files. -COPY ./core . -COPY ./poly . -COPY ./run . - -# Copy the folders needed to run the application. -COPY ./run/config /animals/config/ -COPY ./run/dataset /animals/dataset/ -COPY ./run/emotive /animals/emotive/ -COPY ./run/fragments /animals/fragments/ -COPY ./run/grammar /animals/grammar/ -COPY ./run/logs /animals/logs/ -COPY ./run/mindpixel /animals/mindpixel/ -COPY ./run/nucode /animals/nucode/ -COPY ./run/personality /animals/personality/ -COPY ./run/python /animals/python/ -COPY ./run/reductions /animals/reductions/ -COPY ./run/snippets /animals/snippets/ -COPY ./run/sounds /animals/sounds/ -COPY ./run/tonal /animals/tonal/ -COPY ./run/update /animals/update/ - -# Copy and publish the application and its libraries. -COPY . . -RUN dotnet restore ./run/run.csproj -RUN dotnet publish ./run/run.csproj -c debug -o /animals --no-restore - -# Final stage/image -FROM mcr.microsoft.com/dotnet/runtime:8.0 -WORKDIR /animals -COPY --from=build /animals . -#VOLUME [ "/config" ] -#COPY ./config/Settings.xml -v /config/ -ENV DOTNET_AttachStdout=1 -ENV DOTNET DOTNET_CLI_TELEMETRY_OPTOUT=1 -ENTRYPOINT ["dotnet", "run.dll"] -CMD ["-u"] \ No newline at end of file diff --git a/docker/build-run b/docker/build-run deleted file mode 100644 index 8df636d..0000000 --- a/docker/build-run +++ /dev/null @@ -1,7 +0,0 @@ -docker build -t animals . - -docker run -it animals - -docker run -it -v config:/animals/config animals - - diff --git a/poly/Complex.cs b/poly/Complex.cs deleted file mode 100644 index 40ea2bd..0000000 --- a/poly/Complex.cs +++ /dev/null @@ -1,653 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace SweetPolynomial -{ - /// - /// Class representation of a complex number. - /// - public class Complex - { - /// - /// Contains the real part of a complex number. - /// - public double Real { get; set; } - /// - /// Contains the imaginary part of a complex number. - /// - public double Imaginary { get; set; } - /// - /// The difference threshold to prevent rounding errors. - /// - const double Epsilon = 1E-6; - /// - /// Imaginary unit. - /// - public static Complex I - { - get - { - return new Complex(0, 1); - } - } - /// - /// Complex number zero. - /// - public static Complex Zero - { - get - { - return new Complex(0, 0); - } - } - /// - /// Complex number valued at one. - /// - public static Complex One - { - get - { - return new Complex(1, 0); - } - } - /// - /// Initializes a new instance of the class as (0, 0). - /// - public Complex() - { - Real = 0; - Imaginary = 0; - } - /// - /// Initializes a new instance of the class with imaginary part equal to 0. - /// - /// The real part. - public Complex(double realPart) - { - Real = realPart; - Imaginary = 0; - } - /// - /// Initializes a new instance of the class. - /// - /// The real part. - /// The imaginary part. - public Complex(double realPart, double imaginaryPart) - { - Real = realPart; - Imaginary = imaginaryPart; - } - /// - /// Inits complex number from string like "a+bi". - /// - /// - public Complex(string s) - { - var split = s.Split('+'); - Real = Convert.ToDouble(split[0]); - var next = split[1].Remove(1); - Imaginary = Convert.ToDouble(next); - } - /// - /// Tests the specified input. - /// - /// The s. - /// - public static Match Test(string s) - { - - const string dp = "([0-9]+[.]?[0-9]*|[.][0-9]+)"; - const string dm = "[-]?" + dp; - var r = new Regex("^(?(" + dm + ")[-+](?(" + dp + "))[i])$"); - - return r.Match(s); - } - - #region Operators - - /// - /// Implements the operator +. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator +(Complex a, Complex b) - { - //if (a == null) return b; - //else if (b == null) return a; - //else - return new Complex(a.Real + b.Real, a.Imaginary + b.Imaginary); - } - /// - /// Implements the operator +. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator +(Complex a, double b) - { - return new Complex(a.Real + b, a.Imaginary); - } - /// - /// Implements the operator +. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator +(double a, Complex b) - { - return new Complex(a + b.Real, b.Imaginary); - } - /// - /// Implements the operator -. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator -(Complex a, Complex b) - { - return new Complex(a.Real - b.Real, a.Imaginary - b.Imaginary); - } - /// - /// Implements the operator -. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator -(Complex a, double b) - { - return new Complex(a.Real - b, a.Imaginary); - } - /// - /// Implements the operator -. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator -(double a, Complex b) - { - return new Complex(a - b.Real, -b.Imaginary); - } - /// - /// Implements the operator -. - /// - /// a. - /// - /// The result of the operator. - /// - public static Complex operator -(Complex a) - { - return new Complex(-a.Real, -a.Imaginary); - } - /// - /// Implements the operator *. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator *(Complex a, Complex b) - { - return new Complex(a.Real * b.Real - a.Imaginary * b.Imaginary, - a.Imaginary * b.Real + a.Real * b.Imaginary); - } - /// - /// Implements the operator *. - /// - /// a. - /// The d. - /// - /// The result of the operator. - /// - public static Complex operator *(Complex a, double d) - { - return new Complex(d * a.Real, d * a.Imaginary); - } - /// - /// Implements the operator *. - /// - /// The d. - /// a. - /// - /// The result of the operator. - /// - public static Complex operator *(double d, Complex a) - { - return new Complex(d * a.Real, d * a.Imaginary); - } - /// - /// Implements the operator /. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator /(Complex a, Complex b) - { - return a * Conj(b) * (1 / (Abs(b) * Abs(b))); - } - /// - /// Implements the operator /. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator /(Complex a, double b) - { - return a * (1 / b); - } - /// - /// Implements the operator /. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static Complex operator /(double a, Complex b) - { - return a * Conj(b) * (1 / (Abs(b) * Abs(b))); - } - /// - /// Implements the operator ==. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static bool operator ==(Complex a, Complex b) - { - return a.Real == b.Real && Math.Abs(a.Imaginary - b.Imaginary) < Epsilon; - } - /// - /// Implements the operator ==. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static bool operator ==(Complex a, double b) - { - return a == new Complex(b); - } - /// - /// Implements the operator ==. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static bool operator ==(double a, Complex b) - { - return new Complex(a) == b; - } - /// - /// Implements the operator !=. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static bool operator !=(Complex a, Complex b) - { - return !(a == b); - } - /// - /// Implements the operator !=. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static bool operator !=(Complex a, double b) - { - return !(a == b); - } - /// - /// Implements the operator !=. - /// - /// a. - /// The b. - /// - /// The result of the operator. - /// - public static bool operator !=(double a, Complex b) - { - return !(a == b); - } - - #endregion - - #region Static funcs & overrides - - /// - /// Calcs the absolute value of a complex number. - /// - /// - /// - public static double Abs(Complex a) - { - return Math.Sqrt(a.Imaginary * a.Imaginary + a.Real * a.Real); - } - /// - /// Inverts a. - /// - /// - /// - public static Complex Inv(Complex a) - { - return new Complex(a.Real / (a.Real * a.Real + a.Imaginary * a.Imaginary), - -a.Imaginary / (a.Real * a.Real + a.Imaginary * a.Imaginary)); - } - /// - /// Tangent of a. - /// - /// - /// - public static Complex Tan(Complex a) - { - return Sin(a) / Cos(a); - } - /// - /// Hyperbolic cosine of a. - /// - /// - /// - public static Complex Cosh(Complex a) - { - return (Exp(a) + Exp(-a)) / 2; - } - /// - /// Hyperbolic sine of a. - /// - /// - /// - public static Complex Sinh(Complex a) - { - return (Exp(a) - Exp(-a)) / 2; - } - /// - /// Hyperbolic tangent of a. - /// - /// - /// - public static Complex Tanh(Complex a) - { - return (Exp(2 * a) - 1) / (Exp(2 * a) + 1); - } - /// - /// Hyperbolic cotangent of a. - /// - /// - /// - public static Complex Coth(Complex a) - { - return (Exp(2 * a) + 1) / (Exp(2 * a) - 1); - } - /// - /// Hyperbolic secant of a. - /// - /// - /// - public static Complex Sech(Complex a) - { - return Inv(Cosh(a)); - } - /// - /// Hyperbolic cosecant of a. - /// - /// - /// - public static Complex Csch(Complex a) - { - return Inv(Sinh(a)); - } - /// - /// Cotangent of a. - /// - /// - /// - public static Complex Cot(Complex a) - { - return Cos(a) / Sin(a); - } - /// - /// Computes the conjugation of a complex number. - /// - /// - /// - public static Complex Conj(Complex a) - { - return new Complex(a.Real, -a.Imaginary); - } - /// - /// Complex square root. - /// - /// - /// - public static Complex Sqrt(double d) - { - if (d >= 0) - return new Complex(Math.Sqrt(d)); - return new Complex(0, Math.Sqrt(-d)); - } - /// - /// Complex square root. - /// - /// - /// - public static Complex Sqrt(Complex a) - { - return Pow(a, .5); - } - /// - /// Complex exponential function. - /// - /// - /// - public static Complex Exp(Complex a) - { - return new Complex(Math.Exp(a.Real) * Math.Cos(a.Imaginary), Math.Exp(a.Real) * Math.Sin(a.Imaginary)); - } - /// - /// Main value of the complex logarithm. - /// - /// - /// - public static Complex Log(Complex a) - { - // Log[|w|]+I*(Arg[w]+2*Pi*k) - - return new Complex(Math.Log(Abs(a)), Arg(a)); - } - /// - /// Argument of the complex number. - /// - /// - /// - public static double Arg(Complex a) - { - if (a.Real < 0) - { - if (a.Imaginary < 0) - return Math.Atan(a.Imaginary / a.Real) - Math.PI; - return Math.PI - Math.Atan(-a.Imaginary / a.Real); - } - return Math.Atan(a.Imaginary / a.Real); - } - /// - /// Complex cosine. - /// - /// - /// - public static Complex Cos(Complex a) - { - return .5 * (Exp(I * a) + Exp(-I * a)); - } - /// - /// Complex sine. - /// - /// - /// - public static Complex Sin(Complex a) - { - return (Exp(I * a) - Exp(-I * a)) / (2 * I); - } - /// - /// Power of a by b. - /// - /// a. - /// The b. - /// - public static Complex Pow(Complex a, Complex b) - { - return Exp(b * Log(a)); - } - /// - /// Power of a by b. - /// - /// a. - /// The b. - /// - public static Complex Pow(double a, Complex b) - { - return Exp(b * Math.Log(a)); - } - /// - /// Power of a by b. - /// - /// a. - /// The b. - /// - public static Complex Pow(Complex a, double b) - { - return Exp(b * Log(a)); - } - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - if (this == Zero) return "0"; - - string imaginary, sign; - - if (Imaginary < 0) - { - sign = Math.Abs(Real) < Epsilon ? "-" : " - "; - } - else if (Imaginary > 0 && Math.Abs(Real) > Epsilon) sign = " + "; - else sign = ""; - - var real = Math.Abs(Real) < Epsilon ? "" : Real.ToString(CultureInfo.InvariantCulture); - - if (Math.Abs(Imaginary) < Epsilon) imaginary = ""; - else if (Math.Abs(Imaginary - (-1)) < Epsilon || Math.Abs(Imaginary - 1) < Epsilon) imaginary = "i"; - else imaginary = Math.Abs(Imaginary) + "i"; - - return real + sign + imaginary; - } - /// - /// Returns a that represents this instance. - /// - /// The format. - /// - /// A that represents this instance. - /// - public string ToString(string format) - { - if (this == Zero) return "0"; - if (double.IsInfinity(Real) || double.IsInfinity(Imaginary)) return "oo"; - if (double.IsNaN(Real) || double.IsNaN(Imaginary)) return "?"; - - string imaginary, sign; - - if (Imaginary < 0) - { - sign = Math.Abs(Real) < Epsilon ? "-" : " - "; - } - else if (Imaginary > 0 && Math.Abs(Real) > Epsilon) sign = " + "; - else sign = ""; - - string real = Math.Abs(Real) < Epsilon ? "" : Real.ToString(format); - - if (Math.Abs(Imaginary) < Epsilon) imaginary = ""; - else if (Math.Abs(Imaginary - (-1)) < Epsilon || Math.Abs(Imaginary - 1) < Epsilon) imaginary = "i"; - else imaginary = Math.Abs(Imaginary).ToString(format) + "i"; - - return real + sign + imaginary; - } - /// - /// Determines whether the specified , is equal to this instance. - /// - /// The to compare with this instance. - /// - /// true if the specified is equal to this instance; otherwise, false. - /// - public override bool Equals(object obj) - { - return obj.ToString() == ToString(); - } - /// - /// Returns a hash code for this instance. - /// - /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - /// - public override int GetHashCode() - { - return -1; - } - - #endregion - - #region Dynamics - - /// - /// Determines whether this value is real. - /// - /// - public bool IsReal() - { - return (Math.Abs(Imaginary) < Epsilon); - } - /// - /// Determines whether this value is imaginary. - /// - /// - public bool IsImaginary() - { - return (Math.Abs(Real) < Epsilon); - } - - #endregion - } -} diff --git a/poly/FactorizedPolynomial.cs b/poly/FactorizedPolynomial.cs deleted file mode 100644 index 57df0d0..0000000 --- a/poly/FactorizedPolynomial.cs +++ /dev/null @@ -1,34 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -namespace SweetPolynomial -{ - /// - /// Factorized polynomial p := set of polynomials p_1,...,p_k and their corRealsponding powers n_1,...,n_k, such that p = (p_1)^(n_1)*...*(p_k)^(n_k). - /// - public struct FactorizedPolynomial - { - /// - /// Set of factors the polynomial consists of. - /// - public Polynomial[] Factor; - /// - /// Set of powers, where the real Factor[i] is lifted to Power[i]. - /// - public int[] Power; - } - /// - /// The differential operator structure. - /// - public struct DifferentialOperator - { - /// - /// Set of operations for the differential. - /// - public Polynomial[] Operator; - /// - /// Set of magnitudes, where the real-valued Operator[i] has Magnitude[i]. - /// - public int[] Magnitude; - } -} diff --git a/poly/Polynomial.cs b/poly/Polynomial.cs deleted file mode 100644 index e065a53..0000000 --- a/poly/Polynomial.cs +++ /dev/null @@ -1,1154 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -using System; -using System.Collections; -using System.Collections.Generic; - -namespace SweetPolynomial -{ - /// - /// The class representation of a polynomial expression. - /// - public class Polynomial - { - /// - /// The local instance of the operating polynomial. - /// - public Polynomial LocalPolynomial { get; set; } - /// - /// Coefficients a0,...,a_n of a polynomial p, such that p(x) = a0 + a1 * x + a2 * x^2 + ... + a_n * x^n. - /// - public Complex[] Coefficients; - /// - /// Intializes a zero polynomial as p = 0. - /// - public Polynomial() - { - Coefficients = new Complex[1]; - Coefficients[0] = Complex.Zero; - } - /// - /// Initializes a polynomial given complex coefficient array. - /// - /// - public Polynomial(params Complex[] coeffs) - { - if (coeffs == null || coeffs.Length < 1) - { - Coefficients = new Complex[1]; - Coefficients[0] = Complex.Zero; - } - else - { - Coefficients = (Complex[])coeffs.Clone(); - } - } - /// - /// Initializes polynomial from given real-numbered coefficient array. - /// - /// The real-number coefficients - public Polynomial(params double[] coeffs) - { - if (coeffs == null || coeffs.Length < 1) - { - Coefficients = new Complex[1]; - Coefficients[0] = Complex.Zero; - } - else - { - Coefficients = new Complex[coeffs.Length]; - for (var i = 0; i < coeffs.Length; i++) - Coefficients[i] = new Complex(coeffs[i]); - } - } - /// - /// Initializes a new instance of the class. - /// - /// The x-coefficents - /// The y-coefficents - public Polynomial(double[] x, params double[] y) - { - throw new NotImplementedException("not implemented"); - } - /// - /// Initializes a constant polynomial. - /// - /// - public Polynomial(Complex c) - { - Coefficients = new Complex[1]; - - if (c == null) - Coefficients[0] = Complex.Zero; - else - Coefficients[0] = c; - } - /// - /// Initializes a constant polynomial. - /// - /// - public Polynomial(double c) - { - Coefficients = new Complex[1]; - Coefficients[0] = new Complex(c); - } - /// - /// Initializes a polynomial from string like "2x^2 + 4x + (2+2i)" Using: y=2x^2+2x+1 - /// - /// - public Polynomial(string p) - { - // TESTED WITH: p(x) = 1 + x^2 + 2x^3 - double firstTerm = 0; - double secondTerm= 0; - double thirdTerm= 0; - double fourthTerm= 0; - // Parse the string and generate a formatted polynomial expression. - var equalsSign = p.Split('='); - var poly = equalsSign[1].Split('+'); - var polyLength = poly.Length; - if (polyLength == 4) - { - // Parse the first part of the expression. - if (!poly[0].Contains("x")) - firstTerm = Convert.ToDouble(poly[0]); - if (poly[0].Contains("x") && !poly[0].Contains("x^")) - { - firstTerm = 0; - var secondTermSplit = poly[0].Split('x'); - secondTerm = Convert.ToDouble(secondTermSplit[0]); - } - if (poly[0].Contains("x^")) - { - var sp = poly[0].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - thirdTerm = Convert.ToDouble(spValue); - } - if (sp[1].TrimEnd() == "3") - { - thirdTerm = 0; - var spValue = sp[0].Split('x'); - fourthTerm = Convert.ToDouble(spValue); - } - } - // Parse the second part of the expression. - if (poly[1].Contains("x") && !poly[1].Contains("x^")) - { - var secondTermSplit = poly[1].Split('x'); - secondTerm = Convert.ToDouble(secondTermSplit[0]); - } - if (poly[1].Contains("x^")) - { - var sp = poly[1].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - if (spValue[0] == " ") - thirdTerm = 1; - else - thirdTerm = Convert.ToDouble(spValue[0]); - } - if (sp[1].TrimEnd() == "3") - { - thirdTerm = 0; - var spValue = sp[0].Split('x'); - fourthTerm = Convert.ToDouble(spValue[0]); - } - } - // Parse the third part of the expression. - if (poly[2].Contains("x^")) - { - var sp = poly[2].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - if (spValue[0] == " ") - thirdTerm = 1; - else - thirdTerm = Convert.ToDouble(spValue[0]); - } - if (sp[1].TrimEnd() == "3") - { - var spValue = sp[0].Split('x'); - if (spValue[0] == " ") - fourthTerm = 1; - else - fourthTerm = Convert.ToDouble(spValue[0]); - } - } - // Parse the fourth part of the expression. - if (poly[3].Contains("x^")) - { - var sp = poly[3].Split('^'); - if (sp[1].TrimEnd() == "3") - { - var spValue = sp[0].Split('x'); - if (spValue[0] == " ") - fourthTerm = 1; - else - fourthTerm = Convert.ToDouble(spValue[0]); - } - } - } - if (polyLength == 3) - { - // Parse the first part of the expression. - if (!poly[0].Contains("x")) - firstTerm = Convert.ToDouble(poly[0]); - if (poly[0].Contains("x") && !poly[0].Contains("x^")) - { - firstTerm = 0; - var secondTermSplit = poly[0].Split('x'); - secondTerm = Convert.ToDouble(secondTermSplit[0]); - } - if (poly[0].Contains("x^")) - { - var sp = poly[0].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - thirdTerm = Convert.ToDouble(spValue); - } - if (sp[1].TrimEnd() == "3") - { - thirdTerm = 0; - var spValue = sp[0].Split('x'); - fourthTerm = Convert.ToDouble(spValue); - } - } - // Parse the second part of the expression. - if (poly[1].Contains("x") && !poly[1].Contains("x^")) - { - var secondTermSplit = poly[1].Split('x'); - secondTerm = Convert.ToDouble(secondTermSplit[0]); - } - if (poly[1].Contains("x^")) - { - var sp = poly[1].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - if (spValue[0] == " ") - thirdTerm = 1; - else - thirdTerm = Convert.ToDouble(spValue[0]); - } - if (sp[1].TrimEnd() == "3") - { - thirdTerm = 0; - var spValue = sp[0].Split('x'); - fourthTerm = Convert.ToDouble(spValue[0]); - } - } - // Parse the third part of the expression. - if (poly[2].Contains("x^")) - { - var sp = poly[2].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - thirdTerm = Convert.ToDouble(spValue[0]); - } - if (sp[1].TrimEnd() == "3") - { - var spValue = sp[0].Split('x'); - if (spValue[0] == " ") - fourthTerm = 1; - else - fourthTerm = Convert.ToDouble(spValue[0]); - } - } - } - if (polyLength == 2) - { - // Parse the first part of the expression. - if (!poly[0].Contains("x")) - firstTerm = Convert.ToDouble(poly[0]); - if (poly[0].Contains("x") && !poly[0].Contains("x^")) - { - firstTerm = 0; - var secondTermSplit = poly[0].Split('x'); - secondTerm = Convert.ToDouble(secondTermSplit[0]); - } - if (poly[0].Contains("x^")) - { - var sp = poly[0].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - thirdTerm = Convert.ToDouble(spValue); - } - if (sp[1].TrimEnd() == "3") - { - thirdTerm = 0; - var spValue = sp[0].Split('x'); - fourthTerm = Convert.ToDouble(spValue); - } - } - // Parse the second part of the expression. - if (poly[1].Contains("x") && !poly[1].Contains("x^")) - { - var secondTermSplit = poly[1].Split('x'); - secondTerm = Convert.ToDouble(secondTermSplit[0]); - } - if (poly[1].Contains("x^")) - { - var sp = poly[1].Split('^'); - if (sp[1].TrimEnd() == "2") - { - var spValue = sp[0].Split('x'); - if (spValue[0] == " ") - thirdTerm = 1; - else - thirdTerm = Convert.ToDouble(spValue[0]); - } - if (sp[1].TrimEnd() == "3") - { - thirdTerm = 0; - var spValue = sp[0].Split('x'); - fourthTerm = Convert.ToDouble(spValue[0]); - } - } - } - // Generate the local polynomial expression. - LocalPolynomial = new Polynomial(firstTerm, secondTerm, thirdTerm, fourthTerm); - // Find the roots of the polynomial. - Complex[] roots = LocalPolynomial.Roots(); - // Find the derivative. - Polynomial deriv = Polynomial.Derivative(LocalPolynomial); - // Pass the values to a static class to return to the program. - PolynomialProperties.Degree = LocalPolynomial.Degree; - PolynomialProperties.Roots = roots; - PolynomialProperties.Derivative = deriv; - } - /// - /// Computes the value of the diffeRealntiated polynomial at x. - /// - /// - /// - public Complex Diffentiate(Complex x) - { - var buffer = new Complex[Degree]; - - for (var i = 0; i < buffer.Length; i++) - buffer[i] = (i + 1) * Coefficients[i + 1]; - - return (new Polynomial(buffer)).Evaluate(x); - } - /// - /// Computes the definite integral within the borders a and b. - /// - /// Left integration border. - /// Right integration border. - /// - public Complex Integrate(Complex a, Complex b) - { - var buffer = new Complex[Degree + 2]; - buffer[0] = Complex.Zero; // this value can be arbitrary, in fact - - for (var i = 1; i < buffer.Length; i++) - buffer[i] = Coefficients[i - 1] / i; - - var p = new Polynomial(buffer); - - return (p.Evaluate(b) - p.Evaluate(a)); - } - /// - /// Degree of the polynomial. - /// - public int Degree - { - get - { - return Coefficients.Length - 1; - } - } - /// - /// Checks if given polynomial is zero. - /// - /// - public bool IsZero() - { - for (var i = 0; i < Coefficients.Length; i++) - if (Coefficients[i] != 0) return false; - - return true; - } - /// - /// Evaluates polynomial by using the horner scheme. - /// - /// - /// - public Complex Evaluate(Complex x) - { - var buf = Coefficients[Degree]; - - for (var i = Degree - 1; i >= 0; i--) - { - buf = Coefficients[i] + x * buf; - } - - return buf; - } - /// - /// Normalizes the polynomial, e.i. divides each coefficient by the coefficient of a_n the gRealatest term if a_n != 1. - /// - public void Normalize() - { - Clean(); - - if (Coefficients[Degree] != Complex.One) - for (var k = 0; k <= Degree; k++) - Coefficients[k] /= Coefficients[Degree]; - } - /// - /// Realmoves unnecessary zero terms. - /// - public void Clean() - { - int i; - - for (i = Degree; i >= 0 && Coefficients[i] == 0; i--) - { - } - - var coeffs = new Complex[i + 1]; - - for (var k = 0; k <= i; k++) - coeffs[k] = Coefficients[k]; - - Coefficients = (Complex[])coeffs.Clone(); - } - /// - /// Factorizes polynomial to its linear factors. - /// - /// - public FactorizedPolynomial Factorize() - { - // this is to be returned - var p = new FactorizedPolynomial(); - - // cannot factorize polynomial of degree 0 or 1 - if (Degree <= 1) - { - p.Factor = new[] { this }; - p.Power = new[] { 1 }; - - return p; - } - - var roots = Roots(this); - // Below commented previously. - var rootlist = new ArrayList(); - foreach (Complex z in roots) rootlist.Add(z); - - roots = null; // don't need you anymore - - rootlist.Sort(); - - // number of diffeRealnt roots - int num = 1; // ... at least one - int len = 0; - // ...or more? - for (int i = 1; i < rootlist.Count; i++) - if (rootlist[i] != rootlist[i - 1]) num++; - - // Above commented previously. - var factor = new Polynomial[roots.Length]; - var power = new int[roots.Length]; - // Below commented previously. - factor[0] = new Polynomial(new[]{ -(Complex)rootlist[0] * Coefficients[Degree], - Coefficients[Degree] }); - power[0] = 1; - - num = 1; - len = 0; - for (int i = 1; i < rootlist.Count; i++) - { - len++; - if (rootlist[i] != rootlist[i - 1]) - { - factor[num] = new Polynomial(new[] { -(Complex)rootlist[i], Complex.One }); - power[num] = len; - num++; - len = 0; - } - } - // Above commented previously. - power[0] = 1; - factor[0] = new Polynomial(new[] { -Coefficients[Degree] * roots[0], Coefficients[Degree] }); - - for (var i = 1; i < roots.Length; i++) - { - power[i] = 1; - factor[i] = new Polynomial(new[] { -roots[i], Complex.One }); - } - - p.Factor = factor; - p.Power = power; - - return p; - } - /// - /// Computes the roots of polynomial via Weierstrass iteration. - /// - /// - public Complex[] Roots() - { - const double tolerance = 1e-12; - const int maxIterations = 30; - - var q = Normalize(this); - //Polynomial q = p; - - var z = new Complex[q.Degree]; // approx. for roots - var w = new Complex[q.Degree]; // Weierstra� corRealctions - - // init z - for (var k = 0; k < q.Degree; k++) - //z[k] = (new Complex(.4, .9)) ^ k; - z[k] = Complex.Exp(2 * Math.PI * Complex.I * k / q.Degree); - - - for (var iter = 0; iter < maxIterations - && MaxValue(q, z) > tolerance; iter++) - for (var i = 0; i < 10; i++) - { - for (var k = 0; k < q.Degree; k++) - w[k] = q.Evaluate(z[k]) / WeierNull(z, k); - - for (var k = 0; k < q.Degree; k++) - z[k] -= w[k]; - } - - // clean... - for (var k = 0; k < q.Degree; k++) - { - z[k].Real = Math.Round(z[k].Real, 12); - z[k].Imaginary = Math.Round(z[k].Imaginary, 12); - } - - return z; - } - /// - /// Computes the roots of polynomial p via Weierstrass iteration. - /// - /// Polynomial to compute the roots of. - /// Computation precision; e.g. 1e-12 denotes 12 exact digits. - /// Maximum number of iterations; this value is used to bound the computation effort if desiReald pecision is hard to achieve. - /// - public Complex[] Roots(double tolerance, int maxIterations) - { - var q = Normalize(this); - - var z = new Complex[q.Degree]; // approx. for roots - var w = new Complex[q.Degree]; // Weierstra� corRealctions - - // init z - for (var k = 0; k < q.Degree; k++) - //z[k] = (new Complex(.4, .9)) ^ k; - z[k] = Complex.Exp(2 * Math.PI * Complex.I * k / q.Degree); - - - for (var iter = 0; iter < maxIterations - && MaxValue(q, z) > tolerance; iter++) - for (var i = 0; i < 10; i++) - { - for (var k = 0; k < q.Degree; k++) - w[k] = q.Evaluate(z[k]) / WeierNull(z, k); - - for (var k = 0; k < q.Degree; k++) - z[k] -= w[k]; - } - - // clean... - for (var k = 0; k < q.Degree; k++) - { - z[k].Real = Math.Round(z[k].Real, 12); - z[k].Imaginary = Math.Round(z[k].Imaginary, 12); - } - - return z; - } - /// - /// Expands factorized polynomial p_1(x)^(k_1)*...*p_r(x)^(k_r) to its normal form a_0 + a_1 x + ... + a_n x^n. - /// - /// - /// - public static Polynomial Expand(FactorizedPolynomial p) - { - var q = new Polynomial(new[] { Complex.One }); - - for (var i = 0; i < p.Factor.Length; i++) - { - for (var j = 0; j < p.Power[i]; j++) - q *= p.Factor[i]; - - q.Clean(); - } - - // clean... - for (var k = 0; k <= q.Degree; k++) - { - q.Coefficients[k].Real = Math.Round(q.Coefficients[k].Real, 12); - q.Coefficients[k].Imaginary = Math.Round(q.Coefficients[k].Imaginary, 12); - } - - return q; - } - /// - /// Evaluates factorized polynomial p at point x. - /// - /// - /// - public static Complex Evaluate(FactorizedPolynomial p, Complex x) - { - var z = Complex.One; - - for (var i = 0; i < p.Factor.Length; i++) - { - z *= Complex.Pow(p.Factor[i].Evaluate(x), p.Power[i]); - } - - return z; - } - /// - /// Realmoves unncessary leading zeros. - /// - /// - /// - public static Polynomial Clean(Polynomial p) - { - int i; - - for (i = p.Degree; i >= 0 && p.Coefficients[i] == 0; i--) ; - - var coeffs = new Complex[i + 1]; - - for (var k = 0; k <= i; k++) - coeffs[k] = p.Coefficients[k]; - - return new Polynomial(coeffs); - } - /// - /// Normalizes the polynomial, i.e., divides each coefficient by the coefficient of a_n the gRealatest term if a_n != 1. - /// - public static Polynomial Normalize(Polynomial p) - { - var q = Clean(p); - - if (q.Coefficients[q.Degree] != Complex.One) - for (var k = 0; k <= q.Degree; k++) - q.Coefficients[k] /= q.Coefficients[q.Degree]; - - return q; - } - /// - /// Computes the roots of polynomial p via Weierstrass iteration. - /// - /// - /// - public static Complex[] Roots(Polynomial p) - { - const double tolerance = 1e-12; - const int maxIterations = 30; - - var q = Normalize(p); - //Polynomial q = p; - - var z = new Complex[q.Degree]; // approx. for roots - var w = new Complex[q.Degree]; // Weierstra� corRealctions - - // init z - for (var k = 0; k < q.Degree; k++) - //z[k] = (new Complex(.4, .9)) ^ k; - z[k] = Complex.Exp(2 * Math.PI * Complex.I * k / q.Degree); - - for (var iter = 0; iter < maxIterations - && MaxValue(q, z) > tolerance; iter++) - for (var i = 0; i < 10; i++) - { - for (var k = 0; k < q.Degree; k++) - w[k] = q.Evaluate(z[k]) / WeierNull(z, k); - - for (var k = 0; k < q.Degree; k++) - z[k] -= w[k]; - } - - // clean... - for (var k = 0; k < q.Degree; k++) - { - z[k].Real = Math.Round(z[k].Real, 12); - z[k].Imaginary = Math.Round(z[k].Imaginary, 12); - } - - return z; - } - /// - /// Computes the roots of polynomial p via Weierstrass iteration. - /// - /// Polynomial to compute the roots of. - /// Computation pRealcision; e.g. 1e-12 denotes 12 exact digits. - /// Maximum number of iterations; this value is used to bound - /// the computation effort if desiReald pecision is hard to achieve. - /// - public static Complex[] Roots(Polynomial p, double tolerance, int maxIterations) - { - var q = Normalize(p); - - var z = new Complex[q.Degree]; // approx. for roots - var w = new Complex[q.Degree]; // Weierstra� corRealctions - - // init z - for (var k = 0; k < q.Degree; k++) - //z[k] = (new Complex(.4, .9)) ^ k; - z[k] = Complex.Exp(2 * Math.PI * Complex.I * k / q.Degree); - - - for (var iter = 0; iter < maxIterations - && MaxValue(q, z) > tolerance; iter++) - for (var i = 0; i < 10; i++) - { - for (var k = 0; k < q.Degree; k++) - w[k] = q.Evaluate(z[k]) / WeierNull(z, k); - - for (var k = 0; k < q.Degree; k++) - z[k] -= w[k]; - } - - // clean... - for (var k = 0; k < q.Degree; k++) - { - z[k].Real = Math.Round(z[k].Real, 12); - z[k].Imaginary = Math.Round(z[k].Imaginary, 12); - } - - return z; - } - /// - /// Computes the gRealatest value |p(z_k)|. - /// - /// - /// - /// - public static double MaxValue(Polynomial p, Complex[] z) - { - double buf = 0; - - - for (var i = 0; i < z.Length; i++) - { - if (Complex.Abs(p.Evaluate(z[i])) > buf) - buf = Complex.Abs(p.Evaluate(z[i])); - } - - return buf; - } - /// - /// For g(x) = (x-z_0)*...*(x-z_n), this method returns g'(z_k) = \prod_{j != k} (z_k - z_j). - /// - /// - /// - private static Complex WeierNull(IList z, int k) - { - if (k < 0 || k >= z.Count) - throw new ArgumentOutOfRangeException(); - - var buf = Complex.One; - - for (var j = 0; j < z.Count; j++) - if (j != k) buf *= (z[k] - z[j]); - - return buf; - } - /// - /// DiffeRealntiates given polynomial p. - /// - /// - /// - public static Polynomial Derivative(Polynomial p) - { - var buf = new Complex[p.Degree]; - - for (var i = 0; i < buf.Length; i++) - buf[i] = (i + 1) * p.Coefficients[i + 1]; - - return new Polynomial(buf); - } - /// - /// Integrates given polynomial p. - /// - /// - /// - public static Polynomial Integral(Polynomial p) - { - var buf = new Complex[p.Degree + 2]; - buf[0] = Complex.Zero; // this value can be arbitrary, in fact - - for (var i = 1; i < buf.Length; i++) - buf[i] = p.Coefficients[i - 1] / i; - - return new Polynomial(buf); - } - /// - /// Computes the monomial x^degReale. - /// - /// - /// - public static Polynomial Monomial(int degReale) - { - if (degReale == 0) return new Polynomial(1); - - var coeffs = new Complex[degReale + 1]; - - for (var i = 0; i < degReale; i++) - coeffs[i] = Complex.Zero; - - coeffs[degReale] = Complex.One; - - return new Polynomial(coeffs); - } - /// - /// Gets the standard base. - /// - /// The dim. - /// - /// Dimension expected to be gRealater than zero. - public static Polynomial[] GetStandardBase(int dim) - { - if (dim < 1) - throw new ArgumentException("Dimension expected to be gRealater than zero."); - - var buf = new Polynomial[dim]; - - for (var i = 0; i < dim; i++) - buf[i] = Monomial(i); - - return buf; - } - /// - /// Implements the operator +. - /// - /// The p. - /// The q. - /// - /// The result of the operator. - /// - public static Polynomial operator +(Polynomial p, Polynomial q) - { - - var degReale = Math.Max(p.Degree, q.Degree); - - var coeffs = new Complex[degReale + 1]; - - for (var i = 0; i <= degReale; i++) - { - if (i > p.Degree) coeffs[i] = q.Coefficients[i]; - else if (i > q.Degree) coeffs[i] = p.Coefficients[i]; - else coeffs[i] = p.Coefficients[i] + q.Coefficients[i]; - } - - return new Polynomial(coeffs); - } - /// - /// Implements the operator -. - /// - /// The p. - /// The q. - /// - /// The result of the operator. - /// - public static Polynomial operator -(Polynomial p, Polynomial q) - { - return p + (-q); - } - /// - /// Implements the operator -. - /// - /// The p. - /// - /// The result of the operator. - /// - public static Polynomial operator -(Polynomial p) - { - var coeffs = new Complex[p.Degree + 1]; - - for (var i = 0; i < coeffs.Length; i++) - coeffs[i] = -p.Coefficients[i]; - - return new Polynomial(coeffs); - } - /// - /// Implements the operator *. - /// - /// The d. - /// The p. - /// - /// The result of the operator. - /// - public static Polynomial operator *(Complex d, Polynomial p) - { - var coeffs = new Complex[p.Degree + 1]; - - for (var i = 0; i < coeffs.Length; i++) - coeffs[i] = d * p.Coefficients[i]; - - return new Polynomial(coeffs); - } - /// - /// Implements the operator *. - /// - /// The p. - /// The d. - /// - /// The result of the operator. - /// - public static Polynomial operator *(Polynomial p, Complex d) - { - var coeffs = new Complex[p.Degree + 1]; - - for (var i = 0; i < coeffs.Length; i++) - coeffs[i] = d * p.Coefficients[i]; - - return new Polynomial(coeffs); - } - /// - /// Implements the operator *. - /// - /// The d. - /// The p. - /// - /// The result of the operator. - /// - public static Polynomial operator *(double d, Polynomial p) - { - var coeffs = new Complex[p.Degree + 1]; - - for (var i = 0; i < coeffs.Length; i++) - coeffs[i] = d * p.Coefficients[i]; - - return new Polynomial(coeffs); - } - /// - /// Implements the operator *. - /// - /// The p. - /// The d. - /// - /// The result of the operator. - /// - public static Polynomial operator *(Polynomial p, double d) - { - var coeffs = new Complex[p.Degree + 1]; - - for (var i = 0; i < coeffs.Length; i++) - coeffs[i] = d * p.Coefficients[i]; - - return new Polynomial(coeffs); - } - /// - /// Implements the operator /. - /// - /// The p. - /// The d. - /// - /// The result of the operator. - /// - public static Polynomial operator /(Polynomial p, Complex d) - { - var coeffs = new Complex[p.Degree + 1]; - - for (var i = 0; i < coeffs.Length; i++) - coeffs[i] = p.Coefficients[i] / d; - - return new Polynomial(coeffs); - } - /// - /// Implements the operator /. - /// - /// The p. - /// The d. - /// - /// The result of the operator. - /// - public static Polynomial operator /(Polynomial p, double d) - { - var coeffs = new Complex[p.Degree + 1]; - - for (var i = 0; i < coeffs.Length; i++) - coeffs[i] = p.Coefficients[i] / d; - - return new Polynomial(coeffs); - } - /// - /// Implements the operator *. - /// - /// The p. - /// The q. - /// - /// The result of the operator. - /// - public static Polynomial operator *(Polynomial p, Polynomial q) - { - var degReale = p.Degree + q.Degree; - - var r = new Polynomial(); - - - for (var i = 0; i <= p.Degree; i++) - for (var j = 0; j <= q.Degree; j++) - r += (p.Coefficients[i] * q.Coefficients[j]) * Monomial(i + j); - - return r; - } - /// - /// Implements the operator ^. - /// - /// The p. - /// The k. - /// - /// The result of the operator. - /// - public static Polynomial operator ^(Polynomial p, uint k) - { - if (k == 0) - return Monomial(0); - if (k == 1) - return p; - return p * (p ^ (k - 1)); - } - /// - /// Returns a that represents this instance. - /// - /// The format. - /// - /// A that represents this instance. - /// - public string ToString(string format) - { - if (IsZero()) return "0"; - var s = ""; - - for (var i = 0; i < Degree + 1; i++) - { - if (Coefficients[i] != Complex.Zero) - { - if (Coefficients[i] == Complex.I) - s += "i"; - else if (Coefficients[i] != Complex.One) - { - if (Coefficients[i].IsReal() && Coefficients[i].Real > 0) - s += Coefficients[i].ToString(format); - else - s += "(" + Coefficients[i].ToString(format) + ")"; - - } - else if (/*Coefficients[i] == Complex.One && */i == 0) - s += 1; - - if (i == 1) - s += "x"; - else if (i > 1) - s += "x^" + i.ToString(format); - } - - if (i < Degree && Coefficients[i + 1] != 0 && s.Length > 0) - s += " + "; - } - - return s; - } - /// - /// Returns a that represents this instance. - /// - /// - /// A that represents this instance. - /// - public override string ToString() - { - if (IsZero()) return "0"; - var s = ""; - - for (var i = 0; i < Degree + 1; i++) - { - if (Coefficients[i] != Complex.Zero) - { - if (Coefficients[i] == Complex.I) - s += "i"; - else if (Coefficients[i] != Complex.One) - { - if (Coefficients[i].IsReal() && Coefficients[i].Real > 0) - s += Coefficients[i].ToString(); - else - s += "(" + Coefficients[i] + ")"; - - } - else if (/*Coefficients[i] == Complex.One && */i == 0) - s += 1; - - if (i == 1) - s += "x"; - else if (i > 1) - s += "x^" + i; - } - - if (i < Degree && Coefficients[i + 1] != 0 && s.Length > 0) - s += " + "; - } - - return s; - } - /// - /// Determines whether the specified , is equal to this instance. - /// - /// The to compare with this instance. - /// - /// true if the specified is equal to this instance; otherwise, false. - /// - public override bool Equals(object obj) - { - return (ToString() == obj.ToString()); - } - /// - /// Checks if coefficients are equal. - /// - /// The other. - /// - protected bool Equals(Polynomial other) - { - return Equals(Coefficients, other.Coefficients); - } - /// - /// Returns a hash code for this instance. - /// - /// - /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. - /// - public override int GetHashCode() - { - return (Coefficients != null ? Coefficients.GetHashCode() : 0); - } - } - - /// - /// The properties of this polynomial expression. - /// - public static class PolynomialProperties - { - /// - /// The polynomial itself. - /// - public static int Degree { get; set; } - /// - /// The polynomial roots. - /// - public static Complex[] Roots { get; set; } - /// - /// The derivative of the polynomial. - /// - public static Polynomial Derivative { get; set; } - } -} diff --git a/poly/poly.csproj b/poly/poly.csproj deleted file mode 100644 index 3c962de..0000000 --- a/poly/poly.csproj +++ /dev/null @@ -1,8 +0,0 @@ - - - - 1.2.0 - net6.0 - - - diff --git a/run/.vscode/launch.json b/run/.vscode/launch.json deleted file mode 100644 index c08e2c7..0000000 --- a/run/.vscode/launch.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - // Use IntelliSense to find out which attributes exist for C# debugging - // Use hover for the description of the existing attributes - // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "version": "0.2.0", - "configurations": [ - { - "name": ".NET Core Launch (console)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/container/run/bin/Debug/net.5.0/run.dll", - "args": [], - "cwd": "${workspaceFolder}", - // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console - "console": "internalConsole", - "stopAtEntry": false - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "processId": "${command:pickProcess}" - } - ] -} \ No newline at end of file diff --git a/run/.vscode/tasks.json b/run/.vscode/tasks.json deleted file mode 100644 index 8833a34..0000000 --- a/run/.vscode/tasks.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "label": "build", - "command": "dotnet", - "type": "process", - "args": [ - "build", - "${workspaceFolder}/run.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "publish", - "command": "dotnet", - "type": "process", - "args": [ - "publish", - "${workspaceFolder}/run.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - }, - { - "label": "watch", - "command": "dotnet", - "type": "process", - "args": [ - "watch", - "run", - "${workspaceFolder}/run.csproj", - "/property:GenerateFullPaths=true", - "/consoleloggerparameters:NoSummary" - ], - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file diff --git a/run/Program.cs b/run/Program.cs deleted file mode 100644 index 6bfc1b3..0000000 --- a/run/Program.cs +++ /dev/null @@ -1,1116 +0,0 @@ -// -// This autonomous intelligent system is the intellectual property of Christopher Allen Tucker and The Cartheur Company. Copyright 2006 - 2022, all rights reserved. -// -#define Linux -//#define LinuxVoice -using System; -using System.Collections.Specialized; -using System.Diagnostics; -using System.IO; -using System.Net; -using System.Reflection; -using System.Text; -using System.Threading; -using System.Timers; -using System.Xml; -//using NeSpeak; -using Cartheur.Animals.Core; -using Cartheur.Animals.Control; -using Cartheur.Animals.FileLogic; -using Cartheur.Animals.Personality; -using Cartheur.Animals.Utilities; - -namespace Cartheur.Huggable.Console -{ - /// - /// Application wrapper of the Aeon algorithm. A friendly dialogue you can take anywhere. - /// - /// Multiplatform code: Windows and Linux flavoured. - class Program - { - // The build configuration of the application. - public static DateTime BuildDate { get; set; } - public static LoaderPaths Configuration; - public static bool StartUpTheme { get; set; } - public static string StartUpThemeFile { get; set; } - public static bool TerminalMode { get; set; } - public static Process TerminalProcess { get; set; } - // Aeon's personal algorithmic items. - private static Aeon _thisAeon; - private static User _thisUser; - private static Request _thisRequest; - private static Result _thisResult; - private static DateTime _aeonChatStartedOn; - private static TimeSpan _aeonChatDuration; - private static Thread _aeonAloneThread; - // Aeon's status. - private static bool SettingsLoaded { get; set; } - private static bool AeonLoaded { get; set; } - private static DateTime AeonStartedOn { get; set; } - private static TimeSpan AeonSessionLifeDuration { get; set; } - public static string UserInput { get; set; } - public static string AeonOutputDialogue { get; set; } - public static string AeonOutputDebug { get; set; } - public static int AloneMessageOutput { get; set; } - public static int PreviousAloneMessageOutput { get; set; } - public static int AloneMessageVariety { get; set; } - public static string LastOutput { get; set; } - public bool EncryptionUsed { get; set; } - public int AeonSize { get; set; } - public static string AeonType { get; set; } - public static bool AeonIsAlone { get; set; } - public static string AloneTextCurrent { get; set; } - public static string XmsDirectoryPath { get; set; } - public static string NucodeDirectoryPath { get; set; } - public static string PythonLocation { get; set; } - // Aeon's mood, interaction, and manifest personality. - public static bool TestHardware { get; set; } - private static int SwitchMood { get; set; } - public static bool DetectUserEmotion { get; set; } - private static string EmotiveEquation { get; set; } - public static Mood AeonMood { get; set; } - public static string AeonCurrentMood { get; set; } - // Speech recognition and synthesizer engines. - public static bool SapiWindowsUsed { get; set; } - public static bool PocketSphinxUsed { get; set; } - // For RabbitMQ messaging on pocketsphinx output. -#if LinuxVoice - //public static ConnectionFactory Factory { get; set; } - //public static IModel Channel { get; private set; } - //public static EventingBasicConsumer Consumer { get; set; } -#endif - public static Process SphinxProcess { get; set; } - public static readonly string SphinxStartup = @"pocketsphinx_continuous -hmm /usr/share/pocketsphinx/model/hmm/en_US/en-us -dict /usr/share/pocketsphinx/model/lm/en_US/cmudict-en-us.dict -lm /usr/share/pocketsphinx/model/lm/en_US/en-us.lm.bin -inmic yes -backtrace yes -logfn /dev/null"; - // For remote puppeteering. - static readonly WebClient HenryClient = new WebClient(); - public static bool UsePythonBottle { get; set; } - // For voice synthetizer - public static bool SpeechSynthesizerUsed { get; set; } -#if LinuxVoice - static ESpeakLibrary PresenceSpeaker { get; set; } -#endif - public static string PresenceSpeakerVoice { get; set; } - // External hardware and libraries. - public static bool BottleServerConnected { get; private set; } - public static string SayParameter { get; set; } - public static string BottleIpAddress { get; set; } - public static Process RobotProcess { get; set; } - public static string RobotProcessOutput { get; set; } - public static int RobotProcessExitCode { get; set; } - public static bool CorrectExecution { get; set; } - // Facial movements in three-dimensions. - public static int NumberOfMotors { get; set; } - public static int EyesOpenGpio { get; set; } - public static int EyesCloseGpio { get; set; } - public static int NoseOpenGpio { get; set; } - public static int NoseCloseGpio { get; set; } - public static int MouthOpenGpio { get; set; } - public static int MouthCloseGpio { get; set; } - public static string EmotiveA { get; set; } - public static string EmotiveB { get; set; } - public static string EmotiveC { get; set; } - // Additive huggable feature-set. -#if Windows - private static SoundPlayer EmotiveResponse { get; set; } - private static SoundPlayer TonalResponse { get; set; } -#endif - public static string TonalRootPath { get; set; } - public static string TonalA { get; set; } - public static string TonalB { get; set; } - public static string TonalC { get; set; } - public static string TonalD { get; set; } - public static string TonalE { get; set; } - public static string TonalF { get; set; } - public static string TonalFs { get; set; } - public static string TonalG { get; set; } - public static string TonalAp { get; set; } - public static int TonalDelay { get; set; } - public static bool SpeechToTonal { get; set; } - public static bool TonalSpeechLimit { get; set; } - public static int TonalSpeechLimitValue { get; set; } - public static int Repetition { get; set; } - /// - /// Where the action takes place. - /// - static void Main() - { - // Set the build and load its configuration details. - System.Version BuildVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; - BuildDate = File.GetCreationTime(Assembly.GetExecutingAssembly().Location); - Build.LoadSettings(Build.PathToBuildSettings); - Configuration = new LoaderPaths(Build.BuildSettings.GrabSetting("configuration")); - Logging.ActiveConfiguration = Configuration.ActiveRuntime; - // Create the aeon and load its basic parameters from a config file. - _thisAeon = new Aeon(Build.BuildSettings.GrabSetting("aeon-algorithm")); - _thisAeon.LoadSettings(Configuration.PathToSettings); - SettingsLoaded = _thisAeon.LoadDictionaries(Configuration); - _thisUser = new User(_thisAeon.GlobalSettings.GrabSetting("username"), _thisAeon); - _thisAeon.Name = _thisAeon.GlobalSettings.GrabSetting("name"); - _thisAeon.EmotionUsed = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("emotionused")); - System.Console.WriteLine(_thisAeon.GlobalSettings.GrabSetting("product") + " - Aeon Algorithm: " + Build.BuildSettings.GrabSetting("aeon-algorithm") + "."); - System.Console.WriteLine("Build date: " + BuildDate + ". Assembly version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + "."); - //System.Console.WriteLine(_thisAeon.GlobalSettings.GrabSetting("ip")); - //System.Console.WriteLine(_thisAeon.GlobalSettings.GrabSetting("claim")); - //Thread.Sleep(700); - //System.Console.WriteLine(_thisAeon.GlobalSettings.GrabSetting("warning")); - //Thread.Sleep(700); - //System.Console.WriteLine("------ ******** ------"); - //System.Console.WriteLine("------ Build notes ------"); - //System.Console.WriteLine("------ ******** ------"); - //System.Console.WriteLine(" - - - This version has drawing 300 and 400 of USPTO US20180204107A1 implemented - - - " ); - //System.Console.WriteLine("------ ******** ------"); - //System.Console.WriteLine("------ End build notes ------"); - //System.Console.WriteLine("------ ******** ------"); - System.Console.WriteLine("------ ************ ------"); - System.Console.WriteLine("------ Agent help ------"); - System.Console.WriteLine("------ ************ ------"); - System.Console.WriteLine("The agent is auto-configured so that it is ready to respond to you at the terminal. Start by saying 'hello'."); - Thread.Sleep(700); - if (_thisAeon.EmotionUsed) - { - System.Console.WriteLine("The agent starts with a random emotions and will change its mood based on its experience with you."); - System.Console.WriteLine("If you leave the agent alone too long, it will influence its negative emotions."); - } - else - { - System.Console.WriteLine("The agent has its emotional capacity set to false."); - } - Thread.Sleep(700); - System.Console.WriteLine("While in terminal mode, type 'exit' to decompose and dissolve the agent."); - System.Console.WriteLine("------ ******** ------"); - System.Console.WriteLine("------ End help ------"); - System.Console.WriteLine("------ ******** ------"); - Thread.Sleep(700); - System.Console.WriteLine("Continuing to construct the personality..."); - // Check that the aeon launch is valid. - UserInput = ""; - DetectUserEmotion = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("emotiondetection")); - StartUpTheme = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("startuptheme")); - StartUpThemeFile = _thisAeon.GlobalSettings.GrabSetting("startupthemefile"); - EmotiveEquation = _thisAeon.GlobalSettings.GrabSetting("emotiveequation"); - // Initialize the alone feature, as well as other hardware. - _thisAeon.AeonAloneTimer = new System.Timers.Timer(); - _thisAeon.AeonAloneTimer.Elapsed += AloneEvent; - _thisAeon.AeonAloneTimer.Interval = Convert.ToDouble(_thisAeon.GlobalSettings.GrabSetting("alonetimecheck")); - _thisAeon.AeonAloneTimer.Enabled = false; - _aeonAloneThread = new Thread(AeonAloneText); -#if LinuxVoice - PresenceSpeaker = new ESpeakLibrary(NeSpeak.espeak_AUDIO_OUTPUT.AUDIO_OUTPUT_PLAYBACK); -#endif - SharedFunctions.ThisAeon = _thisAeon; - // Determine what external hardware is to be used. - SapiWindowsUsed = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("sapiwindowsused")); - PocketSphinxUsed = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("pocketsphinxused")); - SpeechSynthesizerUsed = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("speechsynthesizerused")); - UsePythonBottle = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("usepythonbottle")); - // Load any external interpreters for hardware control. - PythonLocation = _thisAeon.GlobalSettings.GrabSetting("pythonlocation"); - // Physical toy where code will be running hardware controllers. - TestHardware = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("testhardware")); - NumberOfMotors = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("numberofmotors")); - EyesOpenGpio = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("eyesopengpio")); - EyesCloseGpio = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("eyesclosegpio")); - NoseOpenGpio = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("noseopengpio")); - NoseCloseGpio = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("noseclosegpio")); - MouthOpenGpio = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("mouthopengpio")); - MouthCloseGpio = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("mouthclosegpio")); - TerminalMode = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("terminalmode")); - // Set the path for the emotive audio files. - EmotiveA = _thisAeon.GlobalSettings.GrabSetting("emotiveafile"); - EmotiveB = _thisAeon.GlobalSettings.GrabSetting("emotivebfile"); - EmotiveC = _thisAeon.GlobalSettings.GrabSetting("emotivecfile"); - TonalRootPath = Configuration.PathToTonalRoot; - TonalA = _thisAeon.GlobalSettings.GrabSetting("tonalafile"); - TonalB = _thisAeon.GlobalSettings.GrabSetting("tonalbfile"); - TonalC = _thisAeon.GlobalSettings.GrabSetting("tonalcfile"); - TonalD = _thisAeon.GlobalSettings.GrabSetting("tonaldfile"); - TonalE = _thisAeon.GlobalSettings.GrabSetting("tonalefile"); - TonalF = _thisAeon.GlobalSettings.GrabSetting("tonalffile"); - TonalFs = _thisAeon.GlobalSettings.GrabSetting("tonalfsfile"); - TonalG = _thisAeon.GlobalSettings.GrabSetting("tonalgfile"); - TonalAp = _thisAeon.GlobalSettings.GrabSetting("tonalapfile"); - TonalDelay = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("tonaldelay")); - SpeechToTonal = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("tonalspeech")); - TonalSpeechLimit = Convert.ToBoolean(_thisAeon.GlobalSettings.GrabSetting("tonalspeechlimit")); - TonalSpeechLimitValue = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("tonalspeechlimitvalue")); - Repetition = Convert.ToInt32(_thisAeon.GlobalSettings.GrabSetting("repetition")); - // Initialize the mood feature and set the display to the current mood. - if (_thisAeon.EmotionUsed) - { - // ToDo: Once a mood state is realized, how does it influence the conversation? - AeonMood = new Mood(StaticRandom.Next(0, 20), _thisAeon, _thisUser, EmotiveEquation, Extensions.Of()); - AeonCurrentMood = AeonMood.EmotionBias.ToString(); - //AeonCurrentMood = AeonMood.GetCurrentMood(); - AeonCurrentMood = AeonMood.Create().ToString(); // USPTO-400 - SwitchMood = 0; -#if Windows - // What happens next when the animal is to be emotional? - if (AeonCurrentMood == "Energized" | AeonCurrentMood == "Happy" | AeonCurrentMood == "Confident") - { - EmotiveResponse = new SoundPlayer(Configuration.ActiveRuntime + @"\emotive\tones\" + EmotiveA); - //for (int i = 0; i < Repetition; i++) // TODO: Needs queing but thinking creating longer *.wav a better idea. - EmotiveResponse.Play(); - Thread.Sleep(500); - // First draft of playing a tonal file sequence, based on the mood. - PlayTonalSequence("fun.txt"); - } - if (AeonCurrentMood == "Helped" | AeonCurrentMood == "Insecure") - { - EmotiveResponse = new SoundPlayer(Configuration.ActiveRuntime + @"\emotive\tones\" + EmotiveB); - EmotiveResponse.Play(); - Thread.Sleep(250); - PlayTonalSequence("okay.txt"); - } - if (AeonCurrentMood == "Hurt" | AeonCurrentMood == "Sad" | AeonCurrentMood == "Tired") - { - EmotiveResponse = new SoundPlayer(Configuration.ActiveRuntime + @"\emotive\tones\" + EmotiveC); - EmotiveResponse.Play(); - Thread.Sleep(250); - PlayTonalSequence("contemplate.txt"); - } -#endif - } - // Utilize the correct settings based on the aeon personality. - if (_thisAeon.Name == "Rhodo" && SettingsLoaded) - AeonLoaded = _thisAeon.LoadPersonality(Configuration); - if (_thisAeon.Name == "Henry" && SettingsLoaded) - AeonLoaded = _thisAeon.LoadPersonality(Configuration); - if (_thisAeon.Name == "Blank" && SettingsLoaded) - AeonLoaded = _thisAeon.LoadBlank(Configuration); - if (_thisAeon.Name == "Samantha" && SettingsLoaded) - AeonLoaded = _thisAeon.LoadPersonality(Configuration); - if (_thisAeon.Name == "Fred" && SettingsLoaded) - AeonLoaded = _thisAeon.LoadPersonality(Configuration); - if (_thisAeon.Name == "Aeon" && SettingsLoaded) - AeonLoaded = _thisAeon.LoadPersonality(Configuration); - if (_thisAeon.Name == "Mitsuku" && SettingsLoaded) - AeonLoaded = _thisAeon.LoadPersonality(Configuration); - // Attach logging, xms functionality, and spontaneous file generation. - Logging.LogModelFile = _thisAeon.GlobalSettings.GrabSetting("logmodelfile"); - Logging.TranscriptModelFile = _thisAeon.GlobalSettings.GrabSetting("transcriptmodelfile"); - // Determine whether to load the Linux or Windows speech synthesizer. -#if LinuxVoice - if (PocketSphinxUsed && AeonLoaded) - { - System.Console.WriteLine("Intializing the pocketsphinx interface with RabbitMQ..."); - InitializeMessageQueue(); - } -#endif - // Set the aeon type by personality. - switch (_thisAeon.Name) - { - case "Aeon": - AeonType = "Assistive"; - break; - case "Fred": - AeonType = "Toy"; - break; - case "Henry": - AeonType = "Toy"; - break; - case "Rhodo": - AeonType = "Default"; - break; - case "Samantha": - AeonType = "Friendly"; - break; - case "Blank": - AeonType = "Huggable"; - break; - } - System.Console.WriteLine("The agent type is " + AeonType.ToLower() + "."); - System.Console.WriteLine("Personality construction completed."); - System.Console.WriteLine("A presence named '" + _thisAeon.Name + "' has been initialized."); - System.Console.WriteLine("It has " + _thisAeon.Size + " categories available in its mind."); - AeonStartedOn = DateTime.Now; - // Set the runtime state. - if (_thisAeon.Name.ToLower() == "aeon") - System.Console.WriteLine("You have selected to load the aeon-assist variety."); - // Set final parameters and play the welcome message. -#if Windows - if (StartUpTheme) - { - try - { - AnimalActive = new SoundPlayer(Configuration.ActiveRuntime + @"\sounds\" + StartUpThemeFile); - AnimalActive.Play(); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.AeonRuntime); - } - } -#endif - System.Console.WriteLine("Your agent is ready for an interaction with you."); - if (_thisAeon.EmotionUsed) - { - System.Console.WriteLine("The agent's mood is " + AeonCurrentMood + "."); - System.Console.WriteLine("The mood polynomial is: " + AeonMood.ReturnMoodPolynomialProperties()); - System.Console.WriteLine("The polynomial properties are: Its roots " + AeonMood.PolynomialRoots[0] + ", " + AeonMood.PolynomialRoots[1] + ", " + AeonMood.PolynomialRoots[2] + " and derivative " + AeonMood.PolynomialDerivative + "."); - } - System.Console.WriteLine("Your transcript follows. Enjoy!"); - System.Console.WriteLine("**********************"); - if (TerminalMode) - { - System.Console.WriteLine("This version only operates in terminal mode."); - // Trigger the terminal for typing torch commands. - while (true && UserInput != "quit") - { - UserInput = ""; - UserInput = System.Console.ReadLine(); - if (UserInput != null) - ProcessTerminal(); - if (UserInput == "quit") - { - System.Console.WriteLine("Leaving terminal mode and starting a conversational aeon."); - Thread.Sleep(2000); - break; - } - if (UserInput == "exit") - { - System.Console.WriteLine("Leaving terminal mode and exiting the application."); - Thread.Sleep(2000); - Environment.Exit(0); - break; - } - } - } - if (_thisAeon.EmotionUsed) - System.Console.WriteLine("The agent's current mood is: " + Mood.CurrentMood + "."); - - if (TestHardware && AeonLoaded) - { - BlinkRoutine(7); - } - // Initialize the queue/pocketsphinx code. -#if LinuxVoice - if (PocketSphinxUsed && AeonLoaded) - { - try - { - ExecuteSphinxProcessToQueue(); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.AeonRuntime); - System.Console.WriteLine("Pocketsphinx interface error. " + ex.Message); - } - } -#endif - while (true) - { - UserInput = System.Console.ReadLine(); - if (UserInput != null) - ProcessInput(); - if (UserInput == "aeon quit") - break; - } - - System.Console.WriteLine(_thisAeon.GlobalSettings.GrabSetting("product") + " is closing in ten seconds."); - Thread.Sleep(10000); - Logging.WriteLog("Companion shut down at " + DateTime.Now, Logging.LogType.Information, Logging.LogCaller.AeonRuntime); - Environment.Exit(0); - } - public static bool ProcessTerminal() - { - //System.Console.WriteLine("Processing terminal command: " + UserInput); - // For now, pass to the input-processing engine. - ProcessInput(); - return true; - } - /// - /// The main input method to pass an enquiry to the system, yielding a reaction/response behavior to the user. - /// - /// Once a mood state is realized, how does it influence the conversation? - public static bool ProcessInput(string returnFromProcess = "") - { - if (DetectUserEmotion) - { - //CorrectExecution = Gpio.RunPythonScript("detectemotion.py", "", Configuration); - // Will need to return the emotion detected by the script. - } - Syntax.CommandReceived = false; - if (_thisAeon.IsAcceptingUserInput) - { - _aeonChatStartedOn = DateTime.Now; - Thread.Sleep(250); - var rawInput = UserInput; - if (rawInput.Contains("\n")) - { - rawInput = rawInput.TrimEnd('\n'); - } - System.Console.WriteLine(_thisUser.UserName + ": " + rawInput); - _thisRequest = new Request(rawInput, _thisUser, _thisAeon); - _thisResult = _thisAeon.Chat(_thisRequest); - Thread.Sleep(200); - System.Console.WriteLine(_thisAeon.Name + ": " + _thisResult.Output); - Logging.RecordTranscript(_thisUser.UserName + ": " + rawInput); - Logging.RecordTranscript(_thisAeon.Name + ": " + _thisResult.Output); - // Record performance vectors for the result. - _aeonChatDuration = DateTime.Now - _aeonChatStartedOn; - Logging.WriteLog("Result search was conducted in: " + _aeonChatDuration.Seconds + @"." + _aeonChatDuration.Milliseconds + " seconds", Logging.LogType.Information, Logging.LogCaller.AeonRuntime); - // Learning: Send the result to the learning algorithm. For v.1.2. - //AeonFive = new MeaningFive(_thisResult); - if (!UsePythonBottle && SpeechSynthesizerUsed) - Speak(_thisResult.Output); - if (SpeechToTonal) -#if Windows - TransposeTonalSpeech(_thisResult.Output); -#endif - if (UsePythonBottle) - { - var message = new NameValueCollection - { - ["speech"] = _thisResult.Output - }; - - try - { - HenryClient.UploadValues(_thisAeon.GlobalSettings.GrabSetting("bottleipaddress"), "POST", message); - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.AeonRuntime); - System.Console.WriteLine("No response from the emotional toy."); - } - } - if (TestHardware && NumberOfMotors == 2) - { - CorrectExecution = Gpio.RunPythonScript("emu1.py", "1", Configuration); - } - if (TestHardware && NumberOfMotors == 3) - { - CorrectExecution = Gpio.RunPythonScript("emu2.py", "1", Configuration); - } - AeonOutputDebug = GenerateAeonOutputDebug(); - AeonOutputDialogue = _thisResult.Output; - if (UserInput == "exit") - { - System.Console.WriteLine("The console has detected the 'exit' command: Dissolving this agent."); - // Print to the console the duration that the aeon has been active. - AeonSessionLifeDuration = DateTime.Now - AeonStartedOn; - System.Console.WriteLine("This agent has been active for: " + AeonSessionLifeDuration.Hours + " hours, " + AeonSessionLifeDuration.Minutes + " minutes and " + AeonSessionLifeDuration.Seconds + " seconds."); - Thread.Sleep(3000); - if (_thisAeon.AeonAloneTimer.Enabled == false) - System.Console.WriteLine("This agent has not been conversed with."); - if(_thisAeon.AeonAloneTimer.Enabled == true) - System.Console.WriteLine("This agent has enjoyed your company."); - Thread.Sleep(700); - System.Console.WriteLine("We hope you have enjoyed your experience -- The Cartheur Dev Team."); - Thread.Sleep(1500); - System.Console.WriteLine("Goodbye."); - Environment.Exit(0); - } - _thisAeon.AeonAloneTimer.Enabled = true; - _thisAeon.AeonAloneStartedOn = DateTime.Now; - AeonIsAlone = false; - } - else - { - UserInput = string.Empty; - System.Console.WriteLine("Aeon is not accepting user input." + Environment.NewLine); - } - return true; - } - - #region Terminal process - public static bool ExecuteTerminalProcess(string terminalCommand) - { - TerminalProcess = new Process(); - TerminalProcess.StartInfo.FileName = "th"; - TerminalProcess.StartInfo.Arguments = " " + terminalCommand; - TerminalProcess.StartInfo.UseShellExecute = false; - TerminalProcess.StartInfo.RedirectStandardOutput = true; - - try - { - TerminalProcess.Start(); - System.Console.WriteLine(TerminalProcess.StandardOutput.ReadToEnd()); - TerminalProcess.WaitForExit(); - return true; - } - catch (Exception ex) - { - Logging.WriteLog(ex.Message, Logging.LogType.Error, Logging.LogCaller.AeonRuntime); - System.Console.WriteLine("An error ocurred in the terminal process."); - return false; - } - - } - #endregion -#if LinuxVoice - #region Pocketsphinx process - /// - /// Execute the pocketsphinx process. Connect to the engine. - /// - /// Standard output and standard error from the process. - public static void ExecuteSphinxProcessToQueue() - { - SphinxProcess = new Process(); - SphinxProcess.StartInfo.FileName = "/bin/bash"; - SphinxProcess.StartInfo.Arguments = "-c \" " + SphinxStartup + " \""; - SphinxProcess.StartInfo.UseShellExecute = false; - SphinxProcess.StartInfo.RedirectStandardOutput = true; - SphinxProcess.Start(); - - while (!SphinxProcess.StandardOutput.EndOfStream) - { - // Send the output to the MQ. - var body = Encoding.UTF8.GetBytes(SphinxProcess.StandardOutput.ReadLine()); - Channel.BasicPublish(exchange: "", - routingKey: "speech", - basicProperties: null, - body: body); - } - } - #endregion -#endif - #region Learning by my own design - - // When learning, create a new *.aeon file. - public void PositData(Characteristic local, string pattern, string template) - { - // Save current state data to the xms system (overwrites in filesystem but only