public static MarkovChain BuildChain()
        {
            var sm = new MarkovChain ();

            var s1 = sm.Add (new State ("s1", true));
            var s2 = sm.Add (new State ("s2"));

            sm.Add (new Transition ("t1", 1, s1, s2));
            sm.Add (new Transition ("t2", 1, s2, s2));

            return sm;
        }
Beispiel #2
0
        public void Add_WithOppositeWeight_ResetsInternalsToInitialState(string sample)
        {
            var chain = new MarkovChain <char>(1);

            chain.Add(sample, 1);

            chain.Add(sample, -1);

            var result = Serialize(chain);

            Assert.Equal(EmptySample, result);
        }
Beispiel #3
0
        public static void InitializeChain()
        {
            if (!File.Exists(FilePath))
            {
                File.CreateText(FilePath);
            }
            else
            {
                string[] TextLines = System.IO.File.ReadAllLines(FilePath);

                Chain.Add(TextLines);
            }
        }
Beispiel #4
0
        public MarkoVerse(bool country)
        {
            MarkovChain <string> chain   = new MarkovChain <string>(2);
            List <string>        allBars = new List <string> {
            };

            foreach (Song song in Song.GetAll())
            {
                string withoutBracketedText = Regex.Replace(song.Lyrics, @"\[.*?\]", "");
                string withoutPunctuation   = Regex.Replace(withoutBracketedText, @"[^a-zA-Z' \-.\r\n]", " ");
                string nWordRemoved         = Regex.Replace(withoutPunctuation, "(N|n)igg", "fell");
                string sWordRemoved         = Regex.Replace(nWordRemoved, "(S|s)hit", "toot");
                string fWordRemoved         = Regex.Replace(sWordRemoved, "(F|f)uck", "hoot");
                string pWordRemoved         = Regex.Replace(fWordRemoved, "(P|p)ussy", "truck");
                string dWordRemoved         = Regex.Replace(pWordRemoved, "(D|d)ick", "dog");
                string bWordPluralsRemoved  = Regex.Replace(dWordRemoved, "(B|b)itches", "hussies");
                string bWordRemoved         = Regex.Replace(bWordPluralsRemoved, "(B|b)itch", "hussy");
                string girlGal  = Regex.Replace(bWordRemoved, "(G|g)irl", "gal");
                string youYall  = Regex.Replace(girlGal, "(Y|y)ou ", "y'all ");
                string goneDone = Regex.Replace(youYall, "(G|g)one", "done gone");
                string ingIn    = Regex.Replace(goneDone, "ing ", "in' ");
                string fixIm    = Regex.Replace(ingIn, "(I|i) m", "I'm");
                string fixCant  = Regex.Replace(fixIm, "n t ", "n't ");
                string noMun    = Regex.Replace(fixCant, "(M|m)un", "YEEHAW");

                string[] lyricSplit = noMun.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in lyricSplit)
                {
                    allBars.Add(line);
                    chain.Add(line.Split(new string[] { " ", "—" }, StringSplitOptions.RemoveEmptyEntries), 1);
                }
            }
            AllBars = allBars;
            Corpus  = chain;
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            var docs      = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var dir       = new DirectoryInfo(docs);
            var chain     = new MarkovChain <string>(3);
            var nameChain = new MarkovChain <char>(3);

            foreach (var file in dir.EnumerateFiles())
            {
                chain.Add(File.ReadAllText(file.FullName).Split(' '));
                nameChain.Add(file.Name);
            }

            var rand = new Random();

            Directory.CreateDirectory(docs + "\\ImportantFiles");

            for (int i = 0; i < 10; i++)
            {
                var filePath = (docs + "\\ImportantFiles\\" + new String(nameChain.Chain(rand).ToArray()));

                Console.WriteLine(filePath);

                using (FileStream fs = File.Create(filePath))
                {
                    Byte[] info = new UTF8Encoding(true).GetBytes(chain.Chain(rand).Aggregate((a, b) => a + " " + b));
                    // Add some information to the file.
                    fs.Write(info, 0, info.Length);
                }
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Beispiel #6
0
        public MarkoVerse()
        {
            MarkovChain <string> chain   = new MarkovChain <string>(2);
            List <string>        allBars = new List <string> {
            };

            foreach (Song song in Song.GetAll())
            {
                string withoutBracketedText = Regex.Replace(song.Lyrics, @"\[.*?\]", "");
                string withoutPunctuation   = Regex.Replace(withoutBracketedText, @"[^a-zA-Z' \-.\r\n]", " ");
                string nWordRemoved         = Regex.Replace(withoutPunctuation, "(N|n)igg", "n*gg");
                string sWordRemoved         = Regex.Replace(nWordRemoved, "(S|s)hit", "sh*t");
                string fWordRemoved         = Regex.Replace(sWordRemoved, "(F|f)uck", "f*ck");
                string pWordRemoved         = Regex.Replace(fWordRemoved, "(P|p)uss", "p*ss");
                string dWordRemoved         = Regex.Replace(pWordRemoved, "(D|d)ick", "d*ck");
                string bWordRemoved         = Regex.Replace(dWordRemoved, "(B|b)itch", "b*tch");
                string fixIm   = Regex.Replace(bWordRemoved, "(I|i) m", "I'm");
                string fixCant = Regex.Replace(fixIm, "n t ", "n't ");

                string[] lyricSplit = fixCant.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string line in lyricSplit)
                {
                    allBars.Add(line);
                    chain.Add(line.Split(new string[] { " ", "—" }, StringSplitOptions.RemoveEmptyEntries), 1);
                }
            }
            AllBars = allBars;
            Corpus  = chain;
        }
Beispiel #7
0
        public async Task TalkAsync([Summary("The user to make talk")] string user)
        {
            var messages = _messageRepository
                           .Where(x => x.User.ToLower() == user.ToLower())
                           .ToArray();

            if (messages.Length < 25)
            {
                await ReplyAsync($"{user} hasn't said enough to make them talk yet");

                return;
            }

            var chain = new MarkovChain <string>(1);

            foreach (var message in messages)
            {
                var split = message.Content.Split(' ');

                if (split.Length >= 5)
                {
                    chain.Add(split);
                }
            }

            await ReplyAsync(string.Join(" ", chain.Chain()));
        }
        public async Task LoadSeeds(string fileName, bool forceLoad = false)
        {
            if (forceLoad || !fileSeeds.ContainsKey(fileName))
            {
                await seedLock.WaitAsync();

                try
                {
                    if (forceLoad || !fileSeeds.ContainsKey(fileName))
                    {
                        var chain = new MarkovChain <Char>(Order);
                        var seeds = await this.ReadSeedsFromFile(fileName);

                        foreach (var seed in seeds)
                        {
                            chain.Add(seed);
                        }
                        fileSeeds[fileName] = chain;
                    }
                }
                finally
                {
                    seedLock.Release();
                }
            }
        }
 public void GenerateChain(List <String> nameList)
 {
     foreach (var name in nameList)
     {
         _chain.Add(name, 1);
     }
 }
Beispiel #10
0
        private static string MarkovResponse(int order, IEnumerable <string> lines)
        {
            var chain = new MarkovChain <string>(order);

            foreach (var line in lines)
            {
                chain.Add(line.Split());
            }

            var response = string.Join(" ", chain.Chain());

            if (response != "")
            {
                return(response);
            }
            var count = 0;

            while (response == "")
            {
                response = string.Join(" ", chain.Chain());
                if (count++ > 10)
                {
                    return("Chaining failed!");
                }
            }
            return(response);
        }
Beispiel #11
0
        async Task <MarkovChain <string> > GenerateChainFromChannels(IEnumerable <IMessageChannel> channels, int messagesFromEach)
        {
            var chain     = new MarkovChain <string>(1);
            int totalUsed = 0;

            foreach (var channel in channels)
            {
                Console.WriteLine($"Loading {messagesFromEach} messages from #{channel.Name}");

                int channelWeight = 2019 - channel.CreatedAt.Year;

                var messages =
                    (await channel.GetMessagesAsync(messagesFromEach).FlattenAsync())
                    .Where(m => string.IsNullOrWhiteSpace(m.Content) == false);

                int used = 0;
                foreach (var msg in messages)
                {
                    var parts = msg.Content
                                .Split(' ')
                                .Where(d => !d.Contains('<'));

                    chain.Add(parts, channelWeight);

                    used++;
                }

                Console.WriteLine($"Added {used} messages from #{channel.Name} to the corpus, at weight {channelWeight}");
                totalUsed += used;
            }

            Console.WriteLine($"Done loading corpus. Total corpus size: {totalUsed} messages.");

            return(chain);
        }
Beispiel #12
0
        static void PopulateChain(MarkovChain <string> chain)
        {
            var handler = new HttpClientHandler
            {
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.GZip
            };

            using (var httpClient = new HttpClient(handler))
            {
                var watch     = new Stopwatch();
                var downloads = 0;

                urls
                .AsParallel()
                .Select(url => httpClient.GetStreamAsync(url))
                .Select(stream => AliveChat(stream.Result))
                .ForAll(result =>
                {
                    Console.Clear();
                    Console.WriteLine($"Download Complete: {++downloads}/{urls.Length}");                     //Not thread safe, i know
                    foreach (var sentence in result)
                    {
                        watch.Start();
                        chain.Add(sentence);
                        watch.Stop();
                    }
                });
                Console.WriteLine($"Creating the chain took: {watch.ElapsedMilliseconds}ms");
            }
        }
        public SamplingWithReplacement(CompositionCategory cat, PatchNames instrument)
        {
            this.MaxIterations = 200;
            this.MaxLength = 100;
            this.instrument = instrument;
            this.category = cat;
            random = new SimpleRNG();
            random.SetSeedFromSystemTime();
            model = new MarkovChain<Note>(1);
            foreach(var comp in cat.Compositions)
            {
                foreach(var track in comp.Tracks)
                {
                    if (!IsValidTrack(track))
                        continue;

                    var mel = (track.GetMainSequence() as MelodySequence).Clone() as MelodySequence;
                    mel.StandardizeDuration();
                    model.Add(mel.ToArray());

                    break;//only first track
                }
            }

            CalculateStats();
        }
Beispiel #14
0
        public async Task InitTweetViewModel()
        {
            _auth = _linqToTwitterAuthorizer.GetAuthorizer(consumerKey, consumerSecret);
            await _auth.AuthorizeAsync();

            //ht--tps://github.com/JoeMayo/LinqToTwitter/wiki/Querying-the-User-Timeline
            using (var ctx = new TwitterContext(_auth))
            {
                List <Status> tweets =
                    await
                        (from tweet in ctx.Status
                        where tweet.Type == StatusType.User &&
                        tweet.ScreenName == "realDonaldTrump" &&
                        tweet.Count == 200 /*MaxTweetsToReturn*/ &&
                        tweet.SinceID == 1 /*sinceID*/ &&
                        tweet.TweetMode == TweetMode.Extended
                        select tweet)
                    .ToListAsync();

                Tweets =
                    (from tweet in tweets
                     select new Tweet
                {
                    StatusID = tweet.StatusID,
                    ScreenName = tweet.User.ScreenNameResponse,
                    Text = tweet.FullText,
                    ImageUrl = tweet.User.ProfileImageUrl
                })
                    .ToList();
            }
            var chain = new MarkovChain <string>(1);

            foreach (var t in Tweets)
            {
                chain.Add(t.Text.Split(' '), 1);
                //foreach(var s in t.Text.Split(' '))
                //{
                //    chain.Add(s, 1);
                //}
            }
            Tweets.Add(new Tweet()
            {
                Text = "--------------"
            });
            //String testOutput = String.Empty;
            var rand = new Random();

            for (int i = 0; i < 10; i++)
            {
                //var word = new string(chain.Chain(rand).ToArray());
                //testOutput += " " + word;
                var sentence = string.Join(" ", chain.Chain(rand));
                Tweets.Add(new Tweet()
                {
                    Text = sentence
                });
            }
            //Tweets.Add(new Tweet() { Text = testOutput });
        }
Beispiel #15
0
 public void InitializeChain()
 {
     _chain = new MarkovChain <string>(1);
     foreach (var t in Tweets)
     {
         _chain.Add(t.Text.Split(' '), 1);
     }
 }
Beispiel #16
0
        public SentenceGenerator()
        {
            _chain = new MarkovChain <string>(1);

            foreach (var sentence in _sentenceBase.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries))
            {
                _chain.Add((sentence + ".").Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToArray(), 1);
            }
        }
Beispiel #17
0
        public void Add_WhenEmpty_AddsTheValuesToTheState(string sample, string serialized)
        {
            var chain = new MarkovChain <char>(1);

            chain.Add(sample);

            var result = Serialize(chain);

            Assert.Equal(serialized, result);
        }
        static MarkovChain <char> GetChain()
        {
            MarkovChain <char> chain = new MarkovChain <char>(2);

            foreach (string name in names)
            {
                chain.Add(name);
            }
            return(chain);
        }
        void Start()
        {
            // POPULATE POLL DATA
            if (livePoll == null)
            {
                livePoll = new LivePoll();
                StartCoroutine(livePoll.GetText());
                for (int i = 0; i < 50; i++)
                {
                    Debug.Log("K");
                    livePoll.Step();
                }
            }

            // POPULATE CORPUS WITH COMPLIANT RULES
            for (int i = 0; i < 100; i++)
            {
                string[] corpus = new string[10];
                for (int b = 0; b < livePoll.probabilities.Count; b++)
                {
                    float p = UnityEngine.Random.Range(0.0F, 1.0F);

                    if (b == 0)
                    {
                        corpus[0] = "DOWN";
                    }
                    else
                    if (corpus[b - 1] == "DOWN")
                    {
                        if (p > livePoll.probabilities[b].p_Down)
                        {
                            corpus[b] = "DOWN";
                        }
                        else
                        {
                            corpus[b] = "UP";
                        }
                    }
                    else
                    if (p > livePoll.probabilities[b].p_Up)
                    {
                        corpus[b] = "UP";
                    }
                    else
                    {
                        corpus[b] = "DOWN";
                    }

                    Debug.Log(p);

                    corpuses.Add(corpus);
                }
                markov.Add(corpus);
            }
        }
Beispiel #20
0
        public Generator(IEnumerable <string> corpus)
        {
            _random      = new Random();
            _markovChain = new MarkovChain <string>(3);

            foreach (var line in corpus)
            {
                var words = SplitLineToWords(line);
                _markovChain.Add(words, 1);
            }
        }
Beispiel #21
0
        static MarkovChain <string> GetChain(int order)
        {
            MarkovChain <string> chain = new MarkovChain <string>(order);

            foreach (string sourceQuote in GetQuotes())
            {
                string[] words = sourceQuote.Split(' ');
                chain.Add(words);
            }

            return(chain);
        }
Beispiel #22
0
        public Task Execute(ITriggerArguments arguments, ISlackConnection connection, SlackChatHub chatHub, SlackerContext context)
        {
            if (arguments == null || arguments.Arguments.Length != 1)
            {
                connection.Say(new BotMessage
                {
                    ChatHub = chatHub,
                    Text    = "Usage: !talk <user>"
                });

                return(Task.CompletedTask);
            }

            var user     = arguments.Arguments[0];
            var messages = context.Messages.Where(x => x.User == user && x.Content.Length > 10);

            if (!messages.Any())
            {
                connection.Say(new BotMessage
                {
                    ChatHub = chatHub,
                    Text    = $"There aren't enough messages by {arguments.Arguments[0]} to go on"
                });

                return(Task.CompletedTask);
            }

            var chain = new MarkovChain <string>(1);

            foreach (var message in messages)
            {
                chain.Add(message.Content.Split(new[] { ' ' }), 1);
            }

            var random = new Random(DateTime.UtcNow.Millisecond);

            var stringBuilder = new StringBuilder(GetRandomMessageStart(user, random));

            stringBuilder.Append(">" + string.Join(" ", chain.Chain(random)));

            connection.Say(new BotMessage
            {
                ChatHub = chatHub,
                Text    = stringBuilder.ToString()
            });

            return(Task.CompletedTask);
        }
        private async Task AddOrUpdateChainForChannelAsync(uint channelId)
        {
            var context  = _contextFactory.CreateDbContext();
            var messages = context.Messages.Where(m => m.ChannelId == channelId).AsAsyncEnumerable();

            _logger.LogInformation("Creating chain for channel {ChannelId}...", channelId);
            var stopwatch = Stopwatch.StartNew();
            var chain     = new MarkovChain <string>(1);

            await foreach (var message in messages)
            {
                chain.Add(message.Message.Split(' '));
            }

            _channelChains[channelId] = chain;
            stopwatch.Stop();
            _logger.LogInformation("Chain for channel {ChannelId} created. ({Elapsed} ms)", channelId, stopwatch.ElapsedMilliseconds);
        }
Beispiel #24
0
    private static void GenerateChain(string text)
    {
        Regex rgx0 = new Regex(@"[^\w 0-9 - ']");
        Regex rgx1 = new Regex("[ ]{2,}");

        string finalString = rgx1.Replace( // Removes double spaces
            rgx0.Replace(text, ""),        // Removes all junk
            " ");

        _chain.Add(finalString.Split(' ').ToList(), 1);
        currentGeneration++;

        if (currentGeneration == 5000)
        {
            SerializeChain();
        }

        StartGeneration();
    }
Beispiel #25
0
 private void Feed(string txt)
 {
     string[] lines = txt.Split(_newlineArray, StringSplitOptions.RemoveEmptyEntries);
     foreach (string line in lines)
     {
         string lin = line;
         Format(ref lin);
         string[]      words     = lin.Split(_splitterChars, StringSplitOptions.RemoveEmptyEntries);
         List <string> goodWords = new List <string>();
         foreach (string word in words)
         {
             if (CheckForLink(word) == false)
             {
                 goodWords.Add(word);
             }
         }
         _chain.Add(goodWords);
     }
 }
Beispiel #26
0
        private async Task <MarkovChain <char> > GetChainAsync(AliasKind kind)
        {
            if (this.chainCache.ContainsKey(kind))
            {
                return(this.chainCache[kind]);
            }

            var chain = new MarkovChain <char>(KindOrder[kind]);

            foreach (var item in await GetSourceAsync(kind))
            {
                chain.Add(item);
            }

            if (!this.chainCache.ContainsKey(kind))
            {
                this.chainCache.Add(kind, chain);
            }

            return(chain);
        }
Beispiel #27
0
        // в ответе должно быть # + Hexagram + The Name + The Judgment (прямо из соотв колонок включая значок из колонки Hexagram)

        public static void generateRandomDailyPhraseUsingMarkov()
        {
            var json = File.ReadAllText("C:\\Files\\Dev\\Twittor\\Twittor\\Twittor\\dbSimple.json");

            Rootobject divination = JsonConvert.DeserializeObject <Rootobject>(json);

            var chain = new MarkovChain <string>(1);

            for (int i = 1; i < 4; i++)
            {
                chain.Add(new[] { divination.Divinations[i].Id, divination.Divinations[i].Hexagram }, 1);
            }

            var rand = new Random();

            for (int i = 0; i < 20; i++)
            {
                var sentence = string.Join(" ", chain.Chain(rand));
                Console.WriteLine("Sentence#" + i + " " + sentence);
            }
        }
Beispiel #28
0
        public async Task Hey([Remainder] string message = "hey")
        {
            var messages = new List <string>();

            // If sentences for fred do not exist for the server, generate them
            if (!File.Exists($@"{Context.Guild.Id}\{FredID}.txt"))
            {
                messages = await GenerateSentenceFile(FredID);
            }
            else
            {
                messages = File.ReadAllLines($@"{Context.Guild.Id}\{FredID}.txt").ToList();
            }

            var chain            = new MarkovChain <string>(3);
            var tokenizer        = new EnglishRuleBasedTokenizer(false);
            var sentenceDetector = new EnglishMaximumEntropySentenceDetector("EnglishSD.nbin");

            messages.ForEach(msg =>
            {
                var sentences = sentenceDetector.SentenceDetect(msg);
                foreach (var sentence in sentences)
                {
                    var tokens = tokenizer.Tokenize(sentence);
                    chain.Add(tokens, tokens.Length);
                }
            });

            var rand = new Random();

            var reply = string.Join(" ", chain.Chain(rand));

            if (string.IsNullOrWhiteSpace(reply))
            {
                return;
            }

            await Context.Channel.SendMessageAsync(reply);
        }
Beispiel #29
0
        public async Task ImpersonateMarkov(CommandContext ctx, DiscordMember member, string[] usertext)
        {
            // Start the markov chains
            var chain = new MarkovChain <string>(1);

            foreach (var entry in usertext)
            {
                var splitentry = entry.Split(" ");
                int currWeight = 1;
                for (double i = 0; i < splitentry.Length; i += 1)
                {
                    currWeight++;
                }
                if (currWeight > 10)
                {
                    currWeight = 10;
                }
                chain.Add(splitentry, currWeight);
            }
            var rand = new Random();

            string sentences = "";

            for (int i = 0; i < 5; i++)
            {
                sentences += "```\n" + string.Join(" ", chain.Chain(rand)).Replace('`', ' ').Replace('\n', ' ') + "```";
            }
            if (member == null)
            {
                await ctx.RespondAsync($"`These messages were generated by Markov Chains`\nHere are some examples of what all collected data sounds like ({usertext.Length} data points):\n{sentences}");
            }
            else
            {
                await ctx.RespondAsync($"`These messages were generated by Markov Chains`\nHere are some examples of what {member.Username} sounds like ({usertext.Length} data points):\n{sentences}");
            }
            return;
        }
 private async Task LoadGraph(MarkovChain <string> markov, string path, ulong guild)
 {
     try
     {
         /*
          * Unforunately with huge files, using StreamReader alone is too slow,
          * so we use BufferedStream to speed things up a bit.
          */
         using (FileStream fileStream = File.Open(path, FileMode.Open))
         {
             using (BufferedStream bufferedStream = new BufferedStream(fileStream))
                 using (StreamReader reader = new StreamReader(bufferedStream))
                 {
                     string line;
                     while ((line = await reader.ReadLineAsync()) != null)
                     {
                         string[] pieces = line.ToLower().Split(' ');
                         markov.Add(pieces, 1);
                     }
                 }
         }
     }
     catch { }
 }
Beispiel #31
0
        public async Task Generate(IGuildUser user, int count = 1, string language = "eng", int depth = 2)
        {
            if (!File.Exists($"{user.Id}_{language}.txt"))
            {
                return;
            }

            var messages = File.ReadAllLines($"{user.Id}_{language}.txt").ToList();

            var chain            = new MarkovChain <string>(depth);
            var tokenizer        = new EnglishRuleBasedTokenizer(false);
            var sentenceDetector = new EnglishMaximumEntropySentenceDetector("EnglishSD.nbin");

            messages.ForEach(msg =>
            {
                var sentences = sentenceDetector.SentenceDetect(msg);
                foreach (var sentence in sentences)
                {
                    var tokens = tokenizer.Tokenize(sentence);
                    chain.Add(tokens, tokens.Length);
                }
            });
            var rand          = new Random();
            var messageString = "";

            for (int i = 0; i < count; i++)
            {
                var c = chain.Chain(rand);
                messageString += ">> " + string.Join(" ", c);
                if (count > 1 && i < count - 1)
                {
                    messageString += "\n";
                }
            }
            await Context.Channel.SendMessageAsync(messageString);
        }
        public async Task Markov(AdaCommandContext ctx)
        {
            var gld = ctx.Guild;
            var chn = ctx.Channel;
            var msg = ctx.Message;
            var usr = ctx.User;

            var chain = new MarkovChain <string>(1);
            var rnd   = new Random();
            var mnt   = (string)null;

            var xmu = msg.MentionedUserIds.Select(xid => gld.GetUserAsync(xid).GetAwaiter().GetResult());
            var xmr = msg.MentionedRoleIds.Select(xid => gld.GetRole(xid));
            var xmc = msg.MentionedChannelIds.Select(xid => gld.GetChannelAsync(xid).GetAwaiter().GetResult());

            if (xmu.Count() == 0 && xmr.Count() == 0 && xmc.Count() == 0)
            {
                throw new ArgumentException("Missing mention.");
            }
            else if (xmu.Count() > 0)
            {
                var mus = xmu.First();
                mnt = mus.Mention;
                var chs  = xmc;
                var maxm = 100;
                var lstm = -1;
                var msgs = new List <IMessage>(maxm);
                var msgt = (IEnumerable <IMessage>)null;
                while (msgs.Count < maxm && lstm != 0)
                {
                    foreach (var xch in chs)
                    {
                        var xcn = xch as SocketTextChannel;
                        if (msgs.Count == 0)
                        {
                            msgt = await xcn.GetMessagesAsync(100).Flatten();

                            msgs.AddRange(msgt.Where(xmsg => xmsg.Author != null && xmsg.Author.Id == mus.Id));
                        }
                        if ((await xcn.GetMessagesAsync(msgs.OrderByDescending(xm => xm != null ? xm.Timestamp : DateTimeOffset.MinValue).FirstOrDefault(), Direction.Before, Math.Min(100, maxm - msgs.Count)).Flatten()).Count() > 0)
                        {
                            lstm = Math.Max(msgt.Count(), lstm);
                            msgs.AddRange(msgt.Where(xmsg => xmsg.Author != null && xmsg.Author.Id == mus.Id));
                        }
                    }
                }
                foreach (var xmsg in msgs)
                {
                    chain.Add(xmsg.Content.Split(' '), 1);
                }
            }
            else if (xmr.Count() > 0)
            {
                var mrl = xmr.First();
                mnt = mrl.Mention;
                var chs  = xmc;
                var maxm = 100;
                var lstm = -1;
                var msgs = new List <IMessage>(maxm);
                var msgt = (IEnumerable <IMessage>)null;
                while (msgs.Count < maxm && lstm != 0)
                {
                    foreach (var xch in chs)
                    {
                        var xcn = xch as SocketTextChannel;
                        if (msgs.Count == 0)
                        {
                            msgt = await xcn.GetMessagesAsync(100).Flatten();

                            msgs.AddRange(msgt.Where(xmsg => xmsg.Author as SocketGuildUser != null && (xmsg.Author as SocketGuildUser).RoleIds.Contains(mrl.Id)));
                        }
                        if ((await xcn.GetMessagesAsync(msgs.OrderByDescending(xm => xm != null ? xm.Timestamp : DateTimeOffset.MinValue).FirstOrDefault(), Direction.Before, Math.Min(100, maxm - msgs.Count)).Flatten()).Count() > 0)
                        {
                            lstm = Math.Max(msgt.Count(), lstm);
                            msgs.AddRange(msgt.Where(xmsg => xmsg.Author as SocketGuildUser != null && (xmsg.Author as SocketGuildUser).RoleIds.Contains(mrl.Id)));
                        }
                    }
                }
                foreach (var xmsg in msgs)
                {
                    chain.Add(xmsg.Content.Split(' '), 1);
                }
            }
            else if (xmc.Count() > 0)
            {
                var mch = xmc.First() as SocketTextChannel;
                mnt = mch.Mention;
                var maxm = 500;
                var msgs = new IMessage[maxm];
                var msgi = 0;
                var msgt = (IEnumerable <IMessage>)null;
                msgt = await mch.GetMessagesAsync(100).Flatten();

                Array.Copy(msgt.ToArray(), 0, msgs, msgi, msgt.Count());
                while (msgi < maxm && (msgt = await mch.GetMessagesAsync(msgs.OrderByDescending(xm => xm != null ? xm.Timestamp : DateTimeOffset.MinValue).FirstOrDefault(), Direction.Before, Math.Min(100, maxm - msgi)).Flatten()).Count() > 0)
                {
                    Array.Copy(msgt.ToArray(), 0, msgs, msgi, msgt.Count());
                    msgi += msgt.Count();
                }
                foreach (var xmsg in msgs)
                {
                    chain.Add(xmsg.Content.Split(' '), 1);
                }
            }

            var sentence = string.Join(" ", chain.Chain(rnd));
            var embed    = this.PrepareEmbed("Markov Chain", string.Concat("Markov chain of ", mnt, ": ", sentence), EmbedType.Info);
            await chn.SendMessageAsync("", false, embed);
        }
Beispiel #33
0
        public static MarkovChain BuildSimpleCommunicationProtocol()
        {
            var sm = new MarkovChain ();

            var start     = sm.Add (new State ("start", true));
            var @try      = sm.Add (new State ("try"));
            var delivered = sm.Add (new State ("delivered"));
            var lost      = sm.Add (new State ("lost"));

            start.ValidPropositions.Add (new Proposition ("start"));
            @try.ValidPropositions.Add (new Proposition ("try"));
            delivered.ValidPropositions.Add (new Proposition ("delivered"));
            lost.ValidPropositions.Add (new Proposition ("lost"));

            sm.Add (new Transition (1, start, @try));
            sm.Add (new Transition (.9, @try, delivered));
            sm.Add (new Transition (.1, @try, lost));
            sm.Add (new Transition (1, lost, @try));
            sm.Add (new Transition (1, delivered, start));

            return sm;
        }
Beispiel #34
0
 public double Satisfy (State currentState, Until until)
 {
     if (caching.ContainsKey (until)) {
         return caching[until][currentState];
     }
     
     caching[until] = new Dictionary<State, double> ();
     
     var B = until.Left;
     var C = until.Right;
     
     // Compute SO
     var s0 = States.Except (ComputeNotS0 (States.Where (s => Satisfy (s, B) == 1), C));
     Console.WriteLine ("S0 : " + string.Join (",", s0.Select (s => s.Identifier)));
     
     foreach (var s in s0) 
         caching[until].Add (s, 0);
     
     // Compute S1
     var s1 = ComputeS1 (B, C);
     Console.WriteLine ("S1 : " + string.Join (",", s1.Select (s => s.Identifier)));
     
     foreach (var s in s1) 
         caching[until].Add (s, 1);
     
     // Compute S?
     var spending = States.Except (s0.Union(s1));
     Console.WriteLine ("S? : " + string.Join (",", spending.Select (s => s.Identifier)));
     
     if (spending.Count() > 0) {
         // Build a SM with only states from S?
         var sm = new MarkovChain ();
         foreach (var s in spending) {
             sm.Add (s);
             foreach (var t in spending) {
                 var transition = Transitions.Where (trans => trans.From.Equals (s)
                                                     & trans.To.Equals (t)).SingleOrDefault ();
                 if (transition != null) 
                     sm.Add (transition);
             }
         }
         
         var table = sm.BuildConversionTable ();
         var A = sm.GetTransitionMatrix (table);
         var b = new DenseVector (
             sm.States.Select (x => 
                           Transitions.Where (y => y.From.Equals (x))
                           .Where (y => s1.Contains (y.To))
                           .Select (y => y.Probability).Sum ()
                           ).ToArray ()
             );
         
         Console.WriteLine ("---------- [Conversion Table]");
         Console.WriteLine (string.Join ("\n", table.Select (x => x.Key + ":" + x.Value)));
         Console.WriteLine ("----------");
         
         Console.WriteLine ("---------- [A]");
         Console.WriteLine (A);
         Console.WriteLine ("----------");
         
         Console.WriteLine ("---------- [b]");
         Console.WriteLine (b);
         Console.WriteLine ("----------");
         
         var epsilon = 0.001;
         
         MathNet.Numerics.LinearAlgebra.Generic.Vector<double> prevsol = new DenseVector (b.Count, 0);
         MathNet.Numerics.LinearAlgebra.Generic.Vector<double> currentsol = new DenseVector (b.Count, 0);
         do {
             prevsol = currentsol;
             currentsol = A.Multiply (prevsol) + b;
             
         } while ((prevsol - currentsol).AbsoluteMaximum() > epsilon);
         
         Console.WriteLine ("---------- [solution]");
         Console.WriteLine (currentsol);
         Console.WriteLine ("----------");
         
         foreach (var s in spending) 
             caching[until].Add(s, currentsol[table[s.Identifier]]);
         
         
         Console.WriteLine ("---------- [Final result]");
         Console.WriteLine (string.Join ("\n", caching[until].Select (x => x.Key.Identifier + " : " + x.Value)));
         Console.WriteLine ("----------");
     }
     
     return caching[until][currentState];
 }
Beispiel #35
0
        public static MarkovChain BuildCrapsGame()
        {
            var sm = new MarkovChain ();

            var start     = sm.Add (new State ("start", true));
            var won       = sm.Add (new State ("won"));
            var lost      = sm.Add (new State ("lost"));

            var s4        = sm.Add (new State ("4"));
            var s10       = sm.Add (new State ("10"));
            var s5        = sm.Add (new State ("5"));
            var s9        = sm.Add (new State ("9"));
            var s6        = sm.Add (new State ("6"));
            var s8        = sm.Add (new State ("8"));

            won.ValidPropositions.Add (new Proposition ("b"));

            start.ValidPropositions.Add (new Proposition ("c"));
            s4.ValidPropositions.Add (new Proposition ("c"));
            s5.ValidPropositions.Add (new Proposition ("c"));
            s6.ValidPropositions.Add (new Proposition ("c"));

            sm.Add (new Transition (2d/9, start, won));
            sm.Add (new Transition (1d/12, start, s4));
            sm.Add (new Transition (1d/12, start, s10));
            sm.Add (new Transition (1d/9, start, s5));
            sm.Add (new Transition (1d/9, start, s9));
            sm.Add (new Transition (5d/36, start, s6));
            sm.Add (new Transition (5d/36, start, s8));
            sm.Add (new Transition (1d/9, start, lost));

            sm.Add (new Transition (3d/4, s4, s4));
            sm.Add (new Transition (1d/12, s4, won));
            sm.Add (new Transition (1d/6, s4, lost));

            sm.Add (new Transition (3d/4, s10, s10));
            sm.Add (new Transition (1d/12, s10, won));
            sm.Add (new Transition (1d/6, s10, lost));

            sm.Add (new Transition (13d/18, s5, s5));
            sm.Add (new Transition (1d/9, s5, won));
            sm.Add (new Transition (1d/6, s5, lost));

            sm.Add (new Transition (13d/18, s9, s9));
            sm.Add (new Transition (1d/9, s9, won));
            sm.Add (new Transition (1d/6, s9, lost));

            sm.Add (new Transition (25d/36, s6, s6));
            sm.Add (new Transition (5d/36, s6, won));
            sm.Add (new Transition (1d/6, s6, lost));

            sm.Add (new Transition (25d/36, s8, s8));
            sm.Add (new Transition (5d/36, s8, won));
            sm.Add (new Transition (1d/6, s8, lost));

            sm.Add (new Transition (1d, won, won));
            sm.Add (new Transition (1d, lost, lost));

            return sm;
        }
Beispiel #36
0
        public static MarkovChain BuildTwoStatesSMWithSelfLoop()
        {
            var sm = new MarkovChain ();

            var s1 = sm.Add (new State ("s1", true));
            var s2 = sm.Add (new State ("s2"));

            s1.ValidPropositions.Add (new Predicate { Name = "state_one" });
            s2.ValidPropositions.Add (new Predicate { Name = "state_two" });

            sm.Add (new Transition ("t1", .5, s1, s2));
            sm.Add (new Transition ("t2", .5, s1, s1));

            sm.Add (new Transition ("t3", 1, s2, s1));

            return sm;
        }
Beispiel #37
0
        public static MarkovChain BuildThreeStatesSM()
        {
            var sm = new MarkovChain ();

            var s1 = sm.Add (new State ("s1", true));
            var s2 = sm.Add (new State ("s2"));
            var s3 = sm.Add (new State ("s3"));

            s1.ValidPropositions.Add (new Proposition ("state_one"));
            s2.ValidPropositions.Add (new Proposition ("state_two"));
            s3.ValidPropositions.Add (new Proposition ("state_three"));

            sm.Add (new Transition ("t12", .5, s1, s2));
            sm.Add (new Transition ("t13", .5, s1, s3));

            sm.Add (new Transition ("t21", .7, s2, s1));
            sm.Add (new Transition ("t23", .3, s2, s3));

            sm.Add (new Transition ("t31", .9, s3, s1));
            sm.Add (new Transition ("t32", .1, s3, s2));

            return sm;
        }
Beispiel #38
0
        public static MarkovChain BuildSingleStateSM()
        {
            var sm = new MarkovChain ();

            var s1 = sm.Add (new State ("s1", true));
            s1.ValidPropositions.Add (new Predicate () { Name = "state_one" });

            sm.Add (new Transition ("t1", 1, s1, s1));

            return sm;
        }
Beispiel #39
0
 private IEnumerable<State> ComputeS1 (LTLFormula b, LTLFormula c)
 {
     var B = States.Where (s => Satisfy (s, b) == 1);
     var C = States.Where (s => Satisfy (s, c) == 1); 
     var buscub = B.Union (States.Except (C.Union (B)));
     
     var newSM = new MarkovChain ();
     foreach (var s in States) {
         newSM.Add (s);
         foreach (var t in States) {
             if (buscub.Contains (s)) {
                 newSM.Add (new Transition (1, s, t));
             } else {
                 var transition = Transitions.Where (trans => trans.From.Equals (s)
                                                     & trans.To.Equals (t)).SingleOrDefault ();
                 if (transition != null) 
                     newSM.Add (transition);
             }
         }
     }
     
     return newSM.States.Where (s => Satisfy (s, new Finally(b)) == 1);
 }
Beispiel #40
0
 private void DFS (IEnumerable<State> B, MarkovChain sm)
 {
     var prestarb = PreStar (B).Except (B);
     
     foreach (var s in prestarb) {
         sm.Add (s);
         foreach (var t in prestarb) {
             var transition = Transitions.Where (trans => trans.From.Equals (s)
                                                 & trans.To.Equals (t)).SingleOrDefault ();
             if (transition != null) 
                 sm.Add (transition);
         }
     }
 }