Esempio n. 1
0
        public void addTransition(string machine, string srcState, string dstState, double prob)
        {
            AltBot.writeDebugLine("MSM: addTransition({0},{1},{2},{3})", machine, srcState, dstState, prob);
            string machineSrcState = machine + ":" + srcState;
            string machineDstState = machine + ":" + dstState;

            addMachineState(machine, srcState);
            addMachineState(machine, dstState);

            try
            {
                double newSum = prob;
                if (transitionCounts.ContainsKey(machineSrcState))
                {
                    newSum = newSum + (double)transitionCounts[machineSrcState];
                }
                transitionCounts[machineSrcState] = newSum;

                string atomicKey = machineSrcState + " " + machineDstState;
                atomicTransitionCount[atomicKey] = prob;
                transSum += prob;
            }
            catch
            {
                AltBot.writeDebugLine("addTransition fail {0} {1} {2}", machineSrcState, machineDstState, prob);
            }
        }
Esempio n. 2
0
        public void addEvidenceState(string machine, string srcState, string evidence, double prob)
        {
            AltBot.writeDebugLine("MSM: addEvidenceState({0},{1},{2},{3})", machine, srcState, evidence, prob);
            lastDefEvidence = evidence;

            string machineSrcState = machine + ":" + srcState;

            addMachineState(machine, srcState);
            try
            {
                if (evidenceStateProbability.ContainsKey(evidence))
                {
                    ((Hashtable)evidenceStateProbability[evidence])[machineSrcState] = prob;
                }
                else
                {
                    Hashtable emitter = new Hashtable();
                    emitter.Add(machineSrcState, prob);
                    evidenceStateProbability.Add(evidence, emitter);
                }
            }
            catch
            {
                AltBot.writeDebugLine("addEvidenceState fail {0} {1} {2}", machineSrcState, evidence, prob);
            }
        }
Esempio n. 3
0
        public double getTransitionProb(string machine, string srcState, string dstState)
        {
            AltBot.writeDebugLine("MSM: getTransitionProb({0},{1},{2})", machine, srcState, dstState);
            string machineSrcState = machine + ":" + srcState;
            string machineDstState = machine + ":" + dstState;

            try
            {
                string atomicKey = machineSrcState + " " + machineDstState;
                double pSum      = (double)transitionCounts[machineSrcState];
                double pNom      = (double)atomicTransitionCount[atomicKey];
                double tp        = (pNom / pSum);
                if (pSum < 0.9)
                {
                    tp = tp * 0.1;
                }
                if (tp > 0.9)
                {
                    tp = 0.9;
                }
                if (tp < 0.0001)
                {
                    tp = 0.0001;
                }
                return(tp);
            }
            catch
            {
                //AltBot.writeDebugLine("   missing Transition {0} -- {1} ", srcState, dstState);
                return((double)0.0001);
            }
        }
Esempio n. 4
0
        protected override Unifiable ProcessChangeU()
        {
            if (CheckNode("evidencepattern"))
            {
                try
                {
                    var varMSM = botActionMSM;

                    string payload = templateNodeInnerText.ToValue(query);

                    string evidence = GetAttribValue("evidence", varMSM.lastDefEvidence);
                    string prob_str = GetAttribValue("prob", "1.0");
                    double prob     = double.Parse(prob_str);
                    //string quote = "" + '\u0022' + "";
                    string quote        = "'";
                    string evidenceCode =
                        //@"<aiml graph=" + quote + "msm" + quote + ">" +
                        @"<topic name=" + quote + "CEP" + quote + " > <category><pattern>" + payload + "</pattern>" +
                        @"<template><think><setevidence evidence=" + quote + evidence + quote +
                        @" prob=" + quote + prob_str + quote +
                        @" /></think>ep " + evidence + "</template></category></topic>";
                    //@"</aiml>";
                    //Proc.AddAiml(evidenceCode);
                    GraphMaster myGraph = request.GetGraph("msm");
                    AddSideEffect("ADD AIML " + evidenceCode, () => Proc.AddAiml(myGraph, evidenceCode));

                    AltBot.writeDebugLine("MSM: evidence_pattern evidenceCode = {0}", evidenceCode);
                }
                catch (Exception e)
                {
                    writeToLogWarn("MSMWARN: " + e);
                }
            }
            return(Unifiable.Empty);
        }
Esempio n. 5
0
        private void populateFromCyc()
        {
            TheBot.AddExcuteHandler("cycl", ExecCycQuery);
            TheBot.AddExcuteHandler("subl", EvalSubLHandler);

            int        id = 1;
            FileStream f  = HostSystem.Open("nodes.txt", FileMode.Create);
            TextWriter tw = new StreamWriter(f);

            foreach (var item in cycAccess.converseList("(ask-template '?R '(#$and (#$genls ?R #$Communicating)(#$not (#$isa ?R #$NonVerbalCommunicating))) #$EverythingPSC)"))
            {
                string text = item.ToString();
                string s    =
                    "<Shape ID='" + id++ +
                    "' NameU='Decision' Type='Shape' Master='0'><XForm><PinX>0.984251968503937</PinX><PinY>11.02362204724409</PinY><Width Unit='MM' F='Inh'>0.984251968503937</Width><Height Unit='MM' F='Inh'>0.5905511811023623</Height><LocPinX Unit='MM' F='Inh'>0.4921259842519685</LocPinX><LocPinY Unit='MM' F='Inh'>0.2952755905511811</LocPinY><Angle F='Inh'>0</Angle><FlipX F='Inh'>0</FlipX><FlipY F='Inh'>0</FlipY><ResizeMode F='Inh'>0</ResizeMode></XForm><Event><TheData F='No Formula'>0</TheData><TheText F='No Formula'>0</TheText><EventDblClick F='Inh'>0</EventDblClick><EventXFMod F='No Formula'>0</EventXFMod><EventDrop F='No Formula'>0</EventDrop></Event><vx:Event xmlns:vx='http://schemas.microsoft.com/visio/2006/extension'><vx:EventMultiDrop F='No Formula'>0</vx:EventMultiDrop></vx:Event><LayerMem><LayerMember>0</LayerMember></LayerMem><Text>" +
                    text + "</Text></Shape>";
                tw.WriteLine(s);
            }
            tw.Close();
            try
            {
                f.Close();
            }
            catch (Exception)
            {
            }
            AltBot.writeDebugLine("!NonVerbalCommunicating = " + id);
            //cycAccess.setCyclist("CycAdministrator");
        }
Esempio n. 6
0
 public override float CanUnify(Unifiable with)
 {
     if (templateNode.NodeType == XmlNodeType.Text)
     {
         return(Proc.TheCyc.IsaFilter(with, templateNode.InnerText) ? ISA_TRUE : ISA_FALSE);
     }
     if (templateNode.HasChildNodes)
     {
         // recursively check
         foreach (XmlNode childNode in templateNode.ChildNodes)
         {
             try
             {
                 Unifiable processChildNode = ProcessChildNode(childNode);
                 if (!Proc.TheCyc.IsaFilter(with, processChildNode))
                 {
                     return(ISA_FALSE);
                 }
                 SetWith(childNode, with);
             }
             catch (Exception e)
             {
                 AltBot.writeDebugLine("" + e);
             }
         }
         return(ISA_TRUE);
     }
     return(ISA_TRUE);
 }
Esempio n. 7
0
        protected override Unifiable ProcessChangeU()
        {

            if (CheckNode("responsetopic"))
            {
                try
                {
                    var varMSM = botActionMSM;
                    string payload = templateNodeInnerText.ToValue(query);
                    string payload2 = Recurse();
                    string payload3 = InnerXmlText(templateNode);
                    string machine = GetAttribValue("machine",  varMSM.lastDefMachine);
                    string myState = GetAttribValue("state", varMSM.lastDefState);
                    string myTopic = GetAttribValue("topic", null);
                    string prob_str = GetAttribValue("prob", "0.1");
                    double prob = double.Parse(prob_str);
                    payload= payload.Replace("rcategory", "category");
                    payload= payload.Replace("rpattern", "pattern");
                    string responseCode = "<aiml graph=\"msm\"> <topic name=\"" + myTopic + "\"> " + payload + " </topic> </aiml>";
                    AltBot.writeDebugLine("MSM: response_topic ResponseCode = {0}", responseCode);
                    MachineSideEffect(() => varMSM.addResponse(machine, myState, myTopic, prob));
                    // TODO: define machine-state -> topic
                    AddSideEffect("Add AIML " + responseCode, () => TargetBot.AddAiml(responseCode));

                }
                catch (Exception e)
                {
                    writeToLogWarn("MSMWARN: " + e);
                }

            }
            return Unifiable.Empty;

        }
Esempio n. 8
0
        public void setState(string machine, string state, double prob)
        {
            AltBot.writeDebugLine("MSM: setState({0},{1},{2})", machine, state, prob);
            addMachineState(machine, state);
            string machineState = machine + ":" + state;

            cur_machineStateVal[machineState] = prob;
        }
        public static List <Unifiable> UnifyStars(string target, string source)
        {
            var             matchVars = new List <object>();
            string          me        = RegExFrom(target, matchVars);
            MatchCollection mc        = Regex.Matches(source, me, RegexOptions.IgnoreCase);

            if (mc.Count == 0)
            {
                if (matchVars.Count == 0)
                {
                    return(SUCCEED_NOVARS);
                }
                AltBot.writeDebugLine("DEBUG9: UnifyStars '" + me + "'!='" + source + "'");
                return(null);
            }
            if (mc.Count != matchVars.Count)
            {
                if (mc.Count == 1)
                {
                    Match mc1 = mc[0];
                    if (mc1.Success)
                    {
                        int mcLength = mc1.Length;
                        if (mcLength > 0)
                        {
                            if (mcLength == source.Length)
                            {
                                return(new List <Unifiable>()
                                {
                                    source
                                });
                            }
                        }
                    }
                    AltBot.writeDebugLine("ERROR: UnifyStars '" + me + "'!='" + source + "'");
                    return(null);
                }
            }
            int mi      = 0;
            var results = new List <Unifiable>(mc.Count);

            foreach (Match match in mc)
            {
                string mv = match.Value;
                object mp = matchVars[mi];
                if (UnifyValues(mp, mv))
                {
                    results.Add(mv);
                }
                else
                {
                    return(null);
                }
            }
            return(results);
        }
Esempio n. 10
0
        private static T GetDictData0 <T>(IList <T> unifiables, string name, int startChars, out bool found) where T : IConvertible
        {
            string s = name.Substring(startChars);

            if (s == "*" || s == "ALL" || s == "0")
            {
                StringAppendableUnifiableImpl result = Unifiable.CreateAppendable();
                foreach (T u in unifiables)
                {
                    result.Append(u.ToString());
                }
                found = true;
                return(PASSTHRU <T>(result));
            }

            int uc = unifiables.Count;

            bool fromend = false;

            if (s.StartsWith("-"))
            {
                fromend = true;
                s       = s.Substring(1);
            }

            int i = Int32.Parse(s);

            if (i == 0)
            {
                if (uc == 0)
                {
                    found = true;
                    return(PASSTHRU <T>(""));
                }
            }
            int ii = i - 1;

            if (fromend)
            {
                ii = uc - i;
            }
            if (uc == 0)
            {
                AltBot.writeDebugLine(" !ERROR -star underflow! " + i + " in " + name);
                found = false;
                return(PASSTHRU <T>(String.Empty));
            }
            if (ii >= uc || ii < 0)
            {
                AltBot.writeDebugLine(" !ERROR -star badindexed 0 < " + i + " < " + uc + " in " + name);
                found = false;
                return(unifiables[ii]);
            }
            found = true;
            return(unifiables[ii]);
        }
Esempio n. 11
0
        public void defState(string machine, string state, double initProb, double selfProb)
        {
            AltBot.writeDebugLine("MSM:   defState({0},{1},{2},{3})", machine, state, initProb, selfProb);
            machines[machine] = 1;
            lastDefState      = state;
            string machineState = machine + ":" + state;

            addMachineState(machine, state);

            setState(machine, state, initProb);
            addTransition(machine, state, state, selfProb);
        }
Esempio n. 12
0
 protected override Unifiable ProcessChangeU()
 {
     if (templateNode.Name.ToLower() == "Processmsm")
     {
         string machine = GetAttribValue("name", null);
         string line    = templateNodeInnerText.ToValue(query);
         AltBot.writeDebugLine("\n\n >>>>>>>>>>>>>>>>>>>>>> PROCESSMSM : |{0}|<<<<<<<<<<<<<<<<<<<<", line);
         Unifiable results = null;
         MachineSideEffect(() => { results = ProcessChangeMSM(); });
         return(results);
     }
     return(Unifiable.Empty);
 }
Esempio n. 13
0
        public void addResponse(string machine, string myState, string myTopic, double prob)
        {
            addMachineState(machine, myState);

            AltBot.writeDebugLine("MSM: addResponse({0},{1},{2},{3})", machine, myState, myTopic, prob);
            string machineSrcState = machine + ":" + myState;

            if (!machineStateResponses.ContainsKey(machineSrcState))
            {
                Hashtable h = new Hashtable();
                h[myTopic] = prob;
                machineStateResponses[machineSrcState] = h;
            }
            ((Hashtable)machineStateResponses[machineSrcState])[myTopic] = prob;
        }
Esempio n. 14
0
 internal void Invoke(string prefix)
 {
     try
     {
         if (prefix != null)
         {
             AltBot.writeDebugLine(prefix + "INVOKING: " + Name);
         }
         Value.Invoke();
     }
     catch (Exception e)
     {
         AltBot.writeDebugLine("ERROR " + prefix + " in " + this + "\n -reason: " + e);
     }
 }
Esempio n. 15
0
 private object EvalSubLHandler(string cmd, Request user)
 {
     try
     {
         return(EvalSubL(cmd, null));
     }
     catch (Exception e)
     {
         TheBot.writeToLog(e);
         string s = "EvalSubLHandler: " + e;
         AltBot.writeDebugLine(s);
         writeToLog(s);
         return(null);
     }
 }
Esempio n. 16
0
 public TemplateInfoImpl(Unifiable pattern, XmlNode cateNode, XmlNode templateNode,
                         LoaderOptions options, Unifiable responseInfo,
                         Unifiable guard, Unifiable topicInfo, Node patternNode, Unifiable thatInfo)
     : base(pattern, cateNode, options)
 {
     if (templateNode == null || responseInfo.FullPath == Unifiable.Empty)
     {
         throw new NotImplementedException();
     }
     TemplateRating = 1.0;
     Guard          = guard;
     if ((thatInfo != null && !thatInfo.IsCatchAll) || (guard != null && !guard.IsCatchAll) ||
         (topicInfo != null && !topicInfo.IsCatchAll))
     {
         IsHighlyUsefull = true;
     }
     //CategoryXml = cateNode;
     That            = thatInfo;
     Response        = responseInfo;
     Topic           = topicInfo;
     Pattern         = pattern;
     GraphmasterNode = patternNode;
     srcNode         = templateNode;
     //ParentCategoryInfo = categoryInfo;
     try
     {
         {
             bool doCut;
             if (StaticXMLUtils.TryParseBool(templateNode, "cut", out doCut) || StaticXMLUtils.TryParseBool(cateNode, "cut", out doCut))
             {
                 NeckCut = doCut;
             }
         }
         string scoreString = StaticXMLUtils.GetAttribValue(templateNode, "score", null);
         scoreString    = scoreString ?? StaticXMLUtils.GetAttribValue(cateNode, "score", null);
         TemplateRating = scoreString != null?double.Parse(scoreString) : 1.0;
     }
     catch
     {
     }
     if (TemplateRating != 1.0)
     {
         AltBot.writeDebugLine("!! SCORE =" + TemplateRating + " for " + this);
     }
 }
Esempio n. 17
0
 public override float CanUnify(Unifiable with)
 {
     if (templateNode.NodeType == XmlNodeType.Text)
     {
         string srch = ToUpper(" " + with.ToValue(query) + " ");
         return((ToUpper(" " + templateNode.InnerText + " ").Equals(srch)) ? STAR_TRUE : STAR_FALSE);
     }
     if (templateNode.HasChildNodes)
     {
         {
             Unifiable rest = with;
             // recursively check
             foreach (XmlNode childNode in templateNode.ChildNodes)
             {
                 with = rest.First;
                 rest = rest.Rest;
                 try
                 {
                     if (childNode.NodeType == XmlNodeType.Text)
                     {
                         string srch = ToUpper(" " + with.ToValue(query) + " ");
                         return((ToUpper(" " + templateNode.InnerText + " ").Equals(srch))
                                    ? STAR_TRUE
                                    : STAR_FALSE);
                     }
                     AIMLTagHandler part = GetChildTagHandler(childNode);
                     if (part.CallCanUnify(with) > 0)
                     {
                         return(STAR_FALSE);
                     }
                 }
                 catch (Exception e)
                 {
                     AltBot.writeDebugLine("" + e);
                 }
             }
             return(IsNullOrEmpty(rest) ? STAR_TRUE : STAR_FALSE);
         }
     }
     return(IsNullOrEmpty(with) ? STAR_TRUE : STAR_FALSE);
 }
Esempio n. 18
0
 public static void DoAll(Stack <NamedAction> todo)
 {
     lock (todo)
     {
         while (todo.Count > 0)
         {
             NamedAction undo = todo.Pop();
             if (undo != null)
             {
                 try
                 {
                     undo.Invoke("UNSTACK ");
                 }
                 catch (Exception exception)
                 {
                     AltBot.writeDebugLine("ERROR in DoAll " + exception);
                 }
             }
         }
     }
 }
Esempio n. 19
0
        public static R FromLoaderOper <R>(Func <R> action, GraphMaster gm, LoaderOptions loadOpts)
        {
            OutputDelegate prev = userTraceRedir;

            try
            {
                userTraceRedir = gm.writeToLog;
                try
                {
                    if (!loadOpts.NeedsLoaderLock)
                    {
                        return(action());
                    }
                    lock (ErrorList)
                    {
                        lock (gm.LockerObject)
                        {
                            return(action());
                        }
                    }
                }
                catch (Exception e)
                {
                    AltBot.writeDebugLine("ERROR: LoaderOper {0}", e);
                    if (!ChatOptions.AllowRuntimeErrors)
                    {
                        return(default(R));
                    }
                    throw;
                    //return default(R);
                }
            }
            finally
            {
                userTraceRedir = prev;
            }
        }
Esempio n. 20
0
 private object ExecCycQuery(string cmd, Request user)
 {
     try
     {
         if (String.IsNullOrEmpty(cmd))
         {
             return("NIL");
         }
         Unifiable ss = EvalSubL("(cyc-query '" + cmd + " #$EverythingPSC)", null);
         if (Unifiable.IsFalse(ss))
         {
             return(Unifiable.Empty);
         }
         return(ss);
     }
     catch (Exception e)
     {
         TheBot.writeToLog(e);
         string s = "ExecCycQuery: " + e;
         AltBot.writeDebugLine(s);
         writeToLog(s);
         return(null);
     }
 }
Esempio n. 21
0
 public void setEvidence(string evidence, double evidenceProb)
 {
     AltBot.writeDebugLine("MSM:  setEvidence({0},{1})", evidence, evidenceProb);
     currentEvidence.Add(evidence, evidenceProb);
 }
Esempio n. 22
0
 public void WriteConfig()
 {
     AltBot.writeDebugLine("Cyc loaded");
 }
Esempio n. 23
0
 public static Unifiable AltStar(string name, SubQuery query, ISettingsDictionary dict, out bool rfound)
 {
     try
     {
         if (name.Contains(","))
         {
             foreach (string subname in NamesStrings(name))
             {
                 var val = AltStar(name, query, dict, out rfound);
                 if (rfound)
                 {
                     rfound = true;
                     return(val);
                 }
             }
         }
         if (name.StartsWith("star_"))
         {
             return(GetDictData(query.InputStars, name, 5, out rfound));
         }
         else if (name.StartsWith("inputstar_"))
         {
             return(GetDictData(query.InputStars, name, 10, out rfound));
         }
         else if (name.StartsWith("input_"))
         {
             return(GetDictData(query.InputStars, name, 6, out rfound));
         }
         else if (name.StartsWith("thatstar_"))
         {
             return(GetDictData(query.ThatStars, name, 9, out rfound));
         }
         else if (name.StartsWith("that_"))
         {
             return(GetDictData(query.ThatStars, name, 5, out rfound));
         }
         else if (name.StartsWith("topicstar_"))
         {
             return(GetDictData(query.TopicStar, name, 10, out rfound));
         }
         else if (name.StartsWith("topic_"))
         {
             return(GetDictData(query.TopicStar, name, 6, out rfound));
         }
         else if (name.StartsWith("guardstar_"))
         {
             return(GetDictData(query.GuardStar, name, 10, out rfound));
         }
         else if (name.StartsWith("guard_"))
         {
             return(GetDictData(query.GuardStar, name, 6, out rfound));
         }
         else if (name.StartsWith("@"))
         {
             Unifiable value = query.Request.TargetBot.SystemExecute(name, null, query.Request);
             rfound = true;
             if (!IsNullOrEmpty(value))
             {
                 return(value);
             }
             return(value);
         }
         else if (name.StartsWith("%dictvar_"))
         {
             Unifiable value = value = GetValue(query, dict, name.Substring(8), out rfound);
             if (rfound)
             {
                 return(value);
             }
             return(value);
         }
         else
         {
             if (name.StartsWith("%") || name.StartsWith("$"))
             {
                 string str = name.Substring(1);
                 var    vv  = ResolveVariableValue(str, query, dict, out rfound);
                 if (rfound)
                 {
                     return(vv);
                 }
                 return(vv);
             }
             else if (name.Contains("."))
             {
                 var vv = ResolveVariableValue(name, query, dict, out rfound);
                 if (rfound)
                 {
                     return(vv);
                 }
                 return(vv);
             }
             rfound = false;
             return(name);
         }
     }
     catch (Exception e)
     {
         AltBot.writeDebugLine("" + e);
         rfound = false;
         return(null);
     }
 }
Esempio n. 24
0
 internal static void writeToLog(string message, params object[] args)
 {
     AltBot.writeDebugLine("QUERYTRACE: " + message, args);
 }
Esempio n. 25
0
 private void writeToLog(string s, params object[] args)
 {
     AltBot.writeDebugLine("" + this + " " + s, args);
 }
Esempio n. 26
0
        public string advanceMachine(string machine)
        {
            if (!machineStates.ContainsKey(machine))
            {
                return("");
            }
            // Cycle through the machine staes
            Hashtable statesHash = (Hashtable)machineStates[machine];
            string    guessPath  = "";
            int       output     = 0;

            // ok, start guessing
            string lastArgMax = "<idle>";

            // The storage mechanism
            double smoother = 0.00001; // 1 / transSum;

            // ensure a transition count for each state
            foreach (string stateKey in statesHash.Keys)
            {
                string mStateKey = machine + ":" + stateKey;
                if (!transitionCounts.ContainsKey(mStateKey))
                {
                    transitionCounts[mStateKey] = (double)0.01;
                }
            }

            // what is the emission probability ?
            // use a bayesian assumption and use the chain rule
            // under Zubek
            //   Bt(s) = Sum_foreach Si in States{ p(S|Si) * q(Y|S) *Bt-1(Si) * Ns,t }
            // and q(Y|S) = Et(Y) * g(S|Y) *N
            // where E(Y) is evidence estimation
            //   and g(S|Y) is likelyhood of observing Y when in state S
            // see zubek dissertation p.148 Naive implementation
            //   for each target state S, iterate over all possible source states Si
            //    summing up previous  source state belief b(Si) at t-1 * transition prob p(S|Si)
            //    also sum up products of evidence g(Y|s) * evidence e(Y) over evidence types
            //    multiply the two gives raw belief estimate for state S
            //    normalize to get final belief value

            double bestVal   = 0;
            string bestGuess = "";
            double Nsum      = 0;

            ArrayList stateKeys = new ArrayList();

            foreach (string astate in statesHash.Keys)
            {
                string machineState = machine + ":" + astate;
                stateKeys.Add(machineState);
            }

            //foreach (string next_state in statesHash.Keys)
            //{
            //    string nextSrcMachineState = machine + ":" + next_state;

            foreach (string nextSrcMachineState in stateKeys)
            {
                double transitionChain = smoother;
                //foreach (string cur_state in statesHash.Keys)
                //{
                //    string curSrcMachineState = machine + ":" + cur_state;
                foreach (string curSrcMachineState in stateKeys)
                {
                    double bf_prob = smoother;
                    try
                    {
                        bf_prob = (double)cur_machineStateVal[curSrcMachineState];
                    }
                    catch
                    {
                    }

                    // Our faster transition lookup
                    double transP    = smoother; // should be smarter
                    string atomicKey = curSrcMachineState + " " + nextSrcMachineState;
                    if (atomicTransitionCount.ContainsKey(atomicKey))
                    {
                        transP = (double)atomicTransitionCount[atomicKey] / (double)transitionCounts[curSrcMachineState];
                    }
                    else
                    {
                        // use default smoother
                        transP = smoother;
                    }
                    double p = transP * bf_prob;

                    //AltBot.writeDebugLine(" Transition: P({0}) = {1}", atomicKey, p);
                    transitionChain += p;
                }// for cur_state


                double evidenceChain = smoother;
                foreach (string evidenceToken in currentEvidence.Keys)
                {
                    double evidenceProb = (double)currentEvidence[evidenceToken];
                    double emitProb     = smoother;
                    try
                    {
                        emitProb = (double)((Hashtable)emissionProbability[evidenceToken])[nextSrcMachineState];
                    }
                    catch
                    {
                    }
                    //AltBot.writeDebugLine(" Evidence: P({0}) = {1} ", evidenceToken,evidenceProb);
                    //AltBot.writeDebugLine("      EMP: P({0} | {1}) = {2} ", evidenceToken, nextSrcMachineState, emitProb);
                    //AltBot.writeDebugLine("        G: {0} ", (emitProb * evidenceProb));

                    evidenceChain = evidenceChain + (emitProb * evidenceProb);
                }

                double rawBeliefInNextState = evidenceChain * transitionChain;
                next_machineStateVal[nextSrcMachineState] = rawBeliefInNextState;
                Nsum += rawBeliefInNextState;
                //AltBot.writeDebugLine(" Next Raw P({0}) = {1} from tcp={2} and ecp={3}", nextSrcMachineState, rawBeliefInNextState, transitionChain, evidenceChain);

                if (rawBeliefInNextState > bestVal)
                {
                    bestGuess = nextSrcMachineState;
                    bestVal   = rawBeliefInNextState;
                }
            }//for next_state

            // Normalize
            //if (Nsum != 0)
            //{
            //    foreach (string next_state in statesHash.Keys)
            //    {
            //        string nextSrcMachineState = machine + ":" + next_state;
            //       next_machineStateVal[nextSrcMachineState] = (double)next_machineStateVal[nextSrcMachineState]/Nsum;
            //    }
            //}
            normalizeMachineNextState(machine);

            AltBot.writeDebugLine("MSM: The highest probability for machine {0} in state {1} [{2}]", machine, bestGuess, next_machineStateVal[bestGuess]);
            AltBot.writeDebugLine("MSM: Guess = [{0}]", bestGuess);
            return(bestGuess);
        }
Esempio n. 27
0
 internal void writeToLog(string message, params object[] args)
 {
     AltBot.writeDebugLine(message, args);
 }
Esempio n. 28
0
        protected Unifiable ProcessChangeMSM()
        {
            //if (this.templateNode.Name.ToLower() == "Processmsm")
            {
                string machine = GetAttribValue("name", null);
                string line    = templateNodeInnerText.ToValue(query);
                AltBot.writeDebugLine("\n\n >>>>>>>>>>>>>>>>>>>>>> PROCESSMSM : |{0}|<<<<<<<<<<<<<<<<<<<<", line);
                //varMSM.lastDefMachine = machine;
                var varMSM = botActionMSM;

                varMSM.addMachine(machine);
                // set topic to "collectevidencepatterns"
                //Proc.AddAiml("<set name='topic'>collectevidencepatters</set>");
                //this.user.Predicates.updateSetting("topic", "collectevidencepatters");
                user.TopicSetting = "CEP";

                // Clear the evidence and next state
                varMSM.clearEvidence();
                varMSM.clearNextStateValues();

                // estimate what evidence can be gleaned from the current state
                varMSM.inspectEvidenceStates();

                // Process the input text

                //string evidenceReply = Proc.ChatString(line, this.user.UserID);
                string evidenceReply = subChat(line, user.TopicSetting, request, true);

                AltBot.writeDebugLine("MSM: WithEvidence {0} ", varMSM.ToString());

                // TODO: we should also get evidence across machine boundries

                // compute the "TRUE" topics from the state machines,advance all machines using evidence
                Hashtable machinesTopState = new Hashtable();
                foreach (string mac in varMSM.machines.Keys)
                {
                    string top_State = varMSM.advanceMachine(mac);
                    machinesTopState[mac] = top_State;
                }
                // make the next_state values the new current state values
                varMSM.advanceStateValues();
                AltBot.writeDebugLine("MSM: AfterAdvance {0} ", varMSM.ToString());

                // For each machine set the appropriate topic, and Process the input text
                string totalReply   = "";
                double strongestVal = -9999;
                foreach (string actingMachine in machinesTopState.Keys)
                {
                    string actionState = (string)machinesTopState[actingMachine];
                    double actp        = (double)varMSM.cur_machineStateVal[actionState];

                    Hashtable topicHt = (Hashtable)varMSM.machineStateResponses[actionState];

                    if ((topicHt != null) && (topicHt.Count > 0))
                    {
                        foreach (string responseTopic in topicHt.Keys)
                        {
                            //prob = topicHt[responseTopic] = prob;
                            string responseTopicUp = ToUpper(responseTopic);
                            //string topicSet = "<set name='topic'>"+responseTopic+"</set>";
                            //this.user.Predicates.updateSetting("topic", responseTopic);
                            user.TopicSetting = responseTopicUp;
                            //Proc.AddAiml(topicSet);
                            string actionReply = "";
                            //actionReply = Proc.ChatString(line, this.user.UserID);


                            actionReply = subChat(line, responseTopicUp, request, false);

                            // Append or use non-null response with the most certainty
                            //totalReply += " " + actionReply;
                            AltBot.writeDebugLine("MSM:[[ PossReply m:{0} s:{1} p:{2} RT: {3} REPLY:{4} ]]  <<< * * * * * *", actingMachine, actionState, actp, responseTopicUp, actionReply.Trim());

                            if ((actp > strongestVal) && (actionReply.Trim().Length > 0))
                            {
                                strongestVal = actp;
                                totalReply   = actionReply;
                            }
                        }
                    }
                }
                Unifiable result = totalReply.Trim();
                AltBot.writeDebugLine("MSM: FinalReply :{0}", totalReply.Trim());
                return(result);
            }
            return(Unifiable.Empty);
        }
Esempio n. 29
0
 public void addMachine(string machine)
 {
     AltBot.writeDebugLine("MSM: addMachine({0})", machine);
     machines[machine] = 1;
     lastDefMachine    = machine;
 }
Esempio n. 30
0
 public void clearEvidence()
 {
     AltBot.writeDebugLine("MSM:  clearEvidence()");
     currentEvidence.Clear();
 }