public void PlayExecutesSamePlayerOrderInEachRound()
        {
            var players = new[]
            {
                "Horse",
                "Car",
                "Hat"
            };

            var mockTurn = new Mock<ITurn>();
            var game = new Game(players, mockTurn.Object, new GuidShuffler<String>());
            var controller = new GameController(game);
            var turnsTaken = new List<String>();

            mockTurn.Setup(m => m.Take(It.IsAny<String>())).Callback((String p) => turnsTaken.Add(p));
            controller.Play();

            var lastRoundTurns = Enumerable.Empty<String>();

            while (turnsTaken.Any())
            {
                var roundTurns = turnsTaken.Take(players.Count());

                if (lastRoundTurns.Any())
                {
                    for (var i = 0; i < lastRoundTurns.Count(); i++)
                        Assert.AreEqual(roundTurns.ElementAt(i), lastRoundTurns.ElementAt(i));
                }

                lastRoundTurns = roundTurns;
                turnsTaken.RemoveRange(0, players.Count());
            }
        }
Example #2
0
        public void TestEncodeDecodeWithCompression()
        {
            var input =
            "He paused for a moment, many recollections overpowering him. Then he went on telling her the history of his life, unfolding to her the story of his hopes and ambitions, describing to her the very home where he was born, and the dark-eyed sister whom he had loved, and with whom he had played over the daisied fields, and through the carpeted woods, and all among the richly tinted bracken. One day he was told she was dead, and that he must never speak her name; but he spoke it all the day and all the night, Beryl, nothing but Beryl, and he looked for her in the fields and in the woods and among the bracken. It seemed as if he had unlocked the casket of his heart, closed for so many years, and as if all the memories of the past and all the secrets of his life were rushing out, glad to be free once more, and grateful for the open air of sympathy.";

             var dict = CharacterFrequencyDictionary.CreateDictionary(input);

             var encodeTree = new HuffmanTree<char>(dict);

             var encode = encodeTree.Encode(input);

             var encodeAsByte = CompressUtil.ConvertToByteArray(encode);

             var secondDict = CharacterFrequencyDictionary.CreateDictionary(
            dict.GetKeysAsByteArray(), dict.GetValuesAsByteArray());

             var encodeAsByteArray = new List<byte>();
             foreach (var b in encodeAsByte)
            encodeAsByteArray.AddRange(CompressUtil.ConvertToBitArray(b));

             if (encode.Length < encodeAsByteArray.ToArray().Length)
            encodeAsByteArray.RemoveRange(encode.Length, encodeAsByteArray.ToArray().Length - encode.Length);

             CollectionAssert.AreEqual(dict, secondDict);
             CollectionAssert.AreEqual(encode, encodeAsByteArray.ToArray());

             var decodeTree = new HuffmanTree<char>(secondDict);
             var decode = decodeTree.Decode(encodeAsByteArray);

             Assert.AreEqual(input, decode);
        }
        public void RemoveRange()
        {
            // Type
            var @this = new List<string> {"zA", "zB", "C"};

            // Exemples
            @this.RemoveRange("zA", "zB"); // Remove "zA" and "zB" items

            // Unit Test
            Assert.AreEqual(1, @this.Count);
        }
Example #4
0
        public void TestDistinctCopy_CreateSet()
        {
            Random random = new Random();

            // build a list of random numbers
            var list = new List<int>(100);
            Sublist.Generate(100, i => random.Next(100)).AddTo(list.ToSublist());

            // unique requires that elements be sorted
            list.ToSublist().Sort().InPlace();

            // now we create a set from the list
            var destination = new List<int>(100);
            Sublist.Generate(100, 0).AddTo(destination.ToSublist());
            int result = list.ToSublist().Distinct().CopyTo(destination.ToSublist());
            destination.RemoveRange(result, destination.Count - result); // remove dangling elements

            // check that we have a valid set
            bool isSet = destination.ToSublist().IsSet();
            Assert.IsTrue(isSet, "The destinatin was not a valid set.");
        }
Example #5
0
        public void TestPop()
        {
            var dynamicStack = new DynamicStack<int>();
            var list = new List<object>();
            for (int i = 0; i < 1000; i++)
            {
                dynamicStack.Push(i);
                list.Add(i);
            }

            for (int i = 0; i < 50; i++)
            {
                dynamicStack.Pop();

            }
            list.RemoveRange(950, 50);
            list.Reverse();
            var expected = list.ToArray();
            var actual = dynamicStack.ToArray();

            CollectionAssert.AreEqual(expected, actual);
        }
        private static void LDiffExperimentZ3(BitWidth encoding)
        {
            List<string> regexes = new List<string>(SampleRegexes.regexes);
            regexes.RemoveRange(2, regexes.Count - 2); //just consider the first 5 cases

            long timeout = 5 * Microsoft.Automata.Internal.Utilities.HighTimer.Frequency; //5 sec

            for (int i = 0; i < regexes.Count; i++)
                for (int j = 0; j < regexes.Count; j++)
                {
                    string regexA = regexes[i];
                    string regexB = regexes[j];

                    var z3p = new Z3Provider(encoding);

                    z3p.MainSolver.Push();

                    var A = z3p.RegexConverter.Convert(regexA, System.Text.RegularExpressions.RegexOptions.None);
                    var B = z3p.RegexConverter.Convert(regexB, System.Text.RegularExpressions.RegexOptions.None);
                    //A.ShowGraph();
                    try
                    {
                        List<Expr> witness;
                        var AmB = Automaton<Expr>.MkDifference(A, B, (int)timeout).Determinize().Minimize();
                        //AmB.ShowGraph();
                        bool isNonempty = Automaton<Expr>.CheckDifference(A, B, (int)timeout, out witness);
                        if (isNonempty)
                        {
                            string s = new String(Array.ConvertAll(witness.ToArray(), c => z3p.GetCharValue(z3p.MainSolver.FindOneMember(c).Value)));
                            Assert.IsTrue(Regex.IsMatch(s, regexA), s + " must match " + regexA);
                            Assert.IsFalse(Regex.IsMatch(s, regexB), s + " must not match " + regexB);
                        }
                    }
                    catch (TimeoutException)
                    {
                        Console.WriteLine("Timeout {0},{1}", i, j);
                    }

                    z3p.MainSolver.Pop();
                }
        }
        private static void DiffExperimentZ3(BitWidth encoding)
        {
            List<string> regexes = new List<string>(SampleRegexes.regexes);
            regexes.RemoveRange(3, regexes.Count - 3); //just consider the first few cases

            long timeout = 5 * Microsoft.Automata.Internal.Utilities.HighTimer.Frequency; //5 sec

            for (int i = 0; i < regexes.Count; i++)
                if (i != 6)
                    for (int j = 0; j < regexes.Count; j++)
                    {
                        string regexA = regexes[i];
                        string regexB = regexes[j];

                        var z3p = new Z3Provider(encoding);

                        z3p.MainSolver.Push();

                        var A = z3p.RegexConverter.Convert(regexA, System.Text.RegularExpressions.RegexOptions.None);
                        var B = z3p.RegexConverter.Convert(regexB, System.Text.RegularExpressions.RegexOptions.None);
                        try
                        {
                            var C = Automaton<Expr>.MkDifference(A, B, (int)timeout);
                            if (!C.IsEmpty)
                            {
                                string s = GetMember(z3p, C);
                                Assert.IsTrue(Regex.IsMatch(s, regexA), s + " must match " + regexA);
                                Assert.IsFalse(Regex.IsMatch(s, regexB), s + " must not match " + regexB);
                            }
                        }
                        catch (TimeoutException)
                        {
                            Console.WriteLine("Timeout {0},{1}", i, j);
                        }

                        z3p.MainSolver.Pop();
                    }
        }
        public void ProdTest()
        {
            BitWidth encoding = BitWidth.BV7;

            List<string> regexes = new List<string>(SampleRegexes.regexes);
            regexes.RemoveRange(6, regexes.Count - 6); //just consider the first 6 cases

            int nonemptyCount = 0;

            for (int i = 0; i < regexes.Count; i++)
                for (int j = 0; j < regexes.Count; j++)
                {

                    string regexA = regexes[i];
                    string regexB = regexes[j];

                    var z3p = new Z3Provider(encoding);

                    z3p.MainSolver.Push();

                    var A = z3p.RegexConverter.Convert(regexA, System.Text.RegularExpressions.RegexOptions.None);
                    var B = z3p.RegexConverter.Convert(regexB, System.Text.RegularExpressions.RegexOptions.None);

                    var A1 = z3p.CharSetProvider.Convert(regexA);
                    var B1 = z3p.CharSetProvider.Convert(regexB);

                    var C1 = Automaton<BDD>.MkProduct(A1, B1).Determinize().Minimize();

                    var C = Automaton<Expr>.MkProduct(A, B);
                    var C2 = new SFAz3(z3p, z3p.CharSort, C.Determinize().Minimize()).Concretize(200);

                    var equiv = C1.IsEquivalentWith(C1);
                    Assert.IsTrue(equiv);

                    if (i == j)
                        Assert.IsFalse(C.IsEmpty);
                    if (!C.IsEmpty)
                    {
                        if (i != j)
                        {
                            //z3p.CharSetProvider.ShowGraph(C1, "C1");
                            //z3p.CharSetProvider.ShowGraph(C2, "C2");
                        }

                        nonemptyCount += 1;
                        string s = GetMember(z3p, C);
                        Assert.IsTrue(Regex.IsMatch(s, regexA, RegexOptions.None), "regex mismatch");
                        Assert.IsTrue(Regex.IsMatch(s, regexB, RegexOptions.None), "regex mismatch");
                    }

                    z3p.MainSolver.Pop();
                }
            Assert.AreEqual<int>(10, nonemptyCount, "wrong number of empty intersections");
        }
Example #9
0
 public byte[] ApplyChange(byte[] inputFile)
 {
     List<byte> result = new List<byte>(inputFile);
     int type = r.Next(3);
     switch (type)
     {
         case 0:
             // just change a byte
             result[r.Next(result.Count)] = (byte)r.Next(256);
             break;
         case 1:
             // insert some bytes
             var randBytes = new byte[r.Next(1000)];
             r.NextBytes(randBytes);
             result.InsertRange(r.Next(result.Count), randBytes);
             break;
         case 2:
             // delete some bytes
             result.RemoveRange(r.Next(result.Count), r.Next(100));
             break;
     }
     return result.ToArray();
 }
        public void checkingOrderOfCollection(string CassandraCollectionType, Type TypeOfDataToBeInputed, Type TypeOfKeyForMap = null, string pendingMode = "")
        {
            string cassandraDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfDataToBeInputed);
            string cassandraKeyDataTypeName = "";

            string openBracket = CassandraCollectionType == "list" ? "[" : "{";
            string closeBracket = CassandraCollectionType == "list" ? "]" : "}";
            string mapSyntax = "";

            string randomKeyValue = string.Empty;

            if (TypeOfKeyForMap != null)
            {
                cassandraKeyDataTypeName = QueryTools.convertTypeNameToCassandraEquivalent(TypeOfKeyForMap);
                mapSyntax = cassandraKeyDataTypeName + ",";

                if (TypeOfKeyForMap == typeof(DateTimeOffset))
                    randomKeyValue = (string)(Randomm.RandomVal(typeof(DateTimeOffset)).GetType().GetMethod("ToString", new Type[] { typeof(string) }).Invoke(Randomm.RandomVal(typeof(DateTimeOffset)), new object[1] { "yyyy-MM-dd H:mm:sszz00" }) + "' : '");
                else
                    randomKeyValue = Randomm.RandomVal(TypeOfDataToBeInputed) + "' : '";
            }

            string tableName = "table" + Guid.NewGuid().ToString("N");
            try
            {
                Session.Cluster.WaitForSchemaAgreement(
                    QueryTools.ExecuteSyncNonQuery(Session, string.Format(@"CREATE TABLE {0}(
             tweet_id uuid PRIMARY KEY,
             some_collection {1}<{2}{3}>
             );", tableName, CassandraCollectionType, mapSyntax, cassandraDataTypeName)));
            }
            catch (AlreadyExistsException)
            {
            }
            Guid tweet_id = Guid.NewGuid();

            StringBuilder longQ = new StringBuilder();
            longQ.AppendLine("BEGIN BATCH ");

            int CollectionElementsNo = 100;
            List<Int32> orderedAsInputed = new List<Int32>(CollectionElementsNo);

            string inputSide = "some_collection + {1}";
            if (CassandraCollectionType == "list" && pendingMode == "prepending")
                inputSide = "{1} + some_collection";

            for (int i = 0; i < CollectionElementsNo; i++)
            {
                var data = i * (i % 2);
                longQ.AppendFormat(@"UPDATE {0} SET some_collection = " + inputSide + " WHERE tweet_id = {2};"
                    , tableName, openBracket + randomKeyValue + data + closeBracket, tweet_id.ToString());
                orderedAsInputed.Add(data);
            }

            longQ.AppendLine("APPLY BATCH;");
            QueryTools.ExecuteSyncNonQuery(Session, longQ.ToString(), "Inserting...");

            if (CassandraCollectionType == "set")
            {
                orderedAsInputed.Sort();
                orderedAsInputed.RemoveRange(0, orderedAsInputed.LastIndexOf(0));
            }
            else if (CassandraCollectionType == "list" && pendingMode == "prepending")
                orderedAsInputed.Reverse();

            CqlRowSet rs = Session.Execute(string.Format("SELECT * FROM {0};", tableName), ConsistencyLevel.Default);

            using (rs)
            {
                int ind = 0;
                foreach (var row in rs.GetRows())
                    foreach (var value in row[1] as System.Collections.IEnumerable)
                    {
                        Assert.True(orderedAsInputed[ind] == (int)value);
                        ind++;
                    }
            }

            QueryTools.ExecuteSyncQuery(Session, string.Format("SELECT * FROM {0};", tableName));
            QueryTools.ExecuteSyncNonQuery(Session, string.Format("DROP TABLE {0};", tableName));
        }
Example #11
0
        public void TestWhereCopy_RemoveOddItems()
        {
            var list = new List<int>() { 1, 2, 3, 4, 5, 6 };
            // only keep the even items
            int result = list.ToSublist().Where(item => item % 2 == 0).CopyTo(list.ToSublist());
            list.RemoveRange(result, list.Count - result);

            int[] expected = { 2, 4, 6 };
            Assert.IsTrue(expected.ToSublist().IsEqualTo(list.ToSublist()), "The items were not where they were expected.");
        }
        public void _02_02_CollectionsGenerischTest()
        {
            var meinArray = new ArrayInt(5);

            // Compiler wandelt folgende Zeile um in
            // meinArray.this[0].set(2)
            meinArray[0] = 2;
            meinArray[1] = 3;
            meinArray[2] = 5;
            meinArray[3] = 7;
            meinArray[4] = 11;

            int a = meinArray[3];

            for (int i = 0; i < meinArray.Length; i++)
            {
                meinArray[i] = i * 10;
            }

            // Dank IEnumarable können wir auf dem selbsdefinierten Array mittels 
            // einer foreach- Schleife iterieren

            foreach (int elem in meinArray)
            {
                Debug.WriteLine(elem);
            }

            int sum = 0;
            for (int i = 0; i < meinArray.Length; i++)
                // Compiler wandelt folgende Zeile um in
                // meinArray.this[i].get()
                sum += meinArray[i];

            // jetzt den generischen Typ nutzen
            var PreislisteGen = new ArrayGenerisch<Preis>(3);

            PreislisteGen[0] = new Preis(4, 99);
            PreislisteGen[1] = new Preis(1, 99);
            PreislisteGen[2] = new Preis(2, 29);

            var p1 = PreislisteGen[1];           


            var A8 = new ArrayGenerisch<Basics._04_Objektorientiert.Autobahn.Auto>(3);

            //A8[0].tanken(100);

            var deinArray = new ArrayGenerisch<double>(3);

            deinArray[0] = 3.14;
            deinArray[1] = 2.72;
            deinArray[2] = 9.81;

            // deinArray ist streng typisiert
            //deinArray[2] = "Hallo";

            double dblSum = 0;
            for (int i = 0; i < deinArray.Length; i++)
                dblSum += deinArray[i];


            // Vorgefertigte generische Collections einsetzen

            // 1) List- ein dynamischer Ersatz für Arrays
            var Preisliste = new List<Preis>(10);

            FüllePreisliste(Preisliste);

            // Compiler wandelt folgenden Aufruf um in
            // Preisliste.this[3].get()
            var preis3 = Preisliste[3];
            Assert.AreEqual(8, preis3.GetEuro());
            Assert.AreEqual(8, Preisliste[3].GetEuro());

            // Einen Preis aus der Liste entfernen
            Preisliste.RemoveAt(0); // 1. Element entfernen
            Preisliste.RemoveAt(Preisliste.Count - 1); // letztes Element entfernen
            Preisliste.RemoveRange(1, 2);

            FüllePreisliste(Preisliste);

            // Linked List
            var AktuellePreise = new LinkedList<string>();
            foreach (var p in Preisliste)
            {
                AktuellePreise.AddLast(p.ToString());
            }

            foreach (var el in AktuellePreise)
            {
                Debug.WriteLine(el);
            }

            // Iterieren über die LinkedList vorwärts
            LinkedListNode<string> actNode = null;
            for (actNode = AktuellePreise.First; actNode != null; actNode = actNode.Next)
            {
                Debug.WriteLine("preis: " + actNode.Value);

            }

            // Iterieren über die LinkedList rückwärts
            for (actNode = AktuellePreise.Last; actNode != null; actNode = actNode.Previous)
            {
                Debug.WriteLine("preis: " + actNode.Value);

            }

            foreach (var p in AktuellePreise)
            {
                // Current greift auf Value vom Node zu
                Debug.WriteLine("preis: " + p);
            }


            // 2 PReise entfernen
            Preisliste.Remove(new Preis(12, 45));

            // den 3. Preis entfernen
            Preisliste.RemoveAt(3);

            
            AktuellePreise.Clear();
            foreach (var p in Preisliste)
            {
                AktuellePreise.AddLast(p.ToString());
            }

            // Telefonbuch
            var telBuch = new Dictionary<string, int>();

            telBuch.Add("Anton", 4711);

            // neuer Eintrag hinzugefügt, da noch nicht unter dem Schlüssel vorhanden
            // Folgeder Indexeraufruf entspricht telbuch.Add("Berta", 6969);
            telBuch["Berta"] = 6969;

            // Eintrag geändert
            telBuch["Berta"] = 7766;

            telBuch["Cäsar"] = 3344;

            // Iterieren durch Dictionary 1
            var telBuchListe = new LinkedList<string>();
            foreach (var k in telBuch.Keys)
            {
                telBuchListe.AddLast(k + ": " + telBuch[k]);
            }

            // Iterieren durch Dictionary 2
            telBuchListe.Clear();
            foreach (KeyValuePair<string, int> pair in telBuch)
            {
                telBuchListe.AddLast(pair.Key + ": " + pair.Value);
            }

            // Queue

            var Warteschlange = new Queue<Tuple<int, string>>();


            // Aufträge in Warteschlange einstellen
            Warteschlange.Enqueue(new Tuple<int, string>(99, "Abwaschen"));
            Warteschlange.Enqueue(new Tuple<int, string>(77, "Abtrocknen"));
            Warteschlange.Enqueue(new Tuple<int, string>(66, "Wegräumen"));

            // Jobverarbeitung schaltet sich ein
            var Auftragsprotokoll = new LinkedList<string>();
            var Auftrag = Warteschlange.Dequeue();
            Auftragsprotokoll.AddLast("Führe aus: " + Auftrag.Item2);

            Warteschlange.Enqueue(new Tuple<int, string>(55, "Zumachen"));

            // Nachschauen, ohne zu entnehmen
            var erstes = Warteschlange.Peek();

            // Da die Queue IEnumerable implementiert, können alle aktuellen
            // Einträge mittels foreach- Schleife besucht werden
            foreach (var job in Warteschlange)
            {
                Debug.WriteLine(job.Item2);
            }

            var alleJobsDieMitABeginnen = Warteschlange.Where(r => r.Item2.StartsWith("A")).ToArray();

            Auftrag = Warteschlange.Dequeue();
            Auftragsprotokoll.AddLast("Führe aus: " + Auftrag.Item2);

            // Alle restlichen verarbeiten
            while (Warteschlange.Count > 0)
            {
                Auftrag = Warteschlange.Dequeue();
                Auftragsprotokoll.AddLast("Führe aus: " + Auftrag.Item2);
            }

        }
        private static List<StackFrame> FilterStackTrace(Exception e)
        {
            StackTrace st = new StackTrace(e, true);
              List<StackFrame> stackFrames = new List<StackFrame>(st.GetFrames());

              // Last stack frame is always "MonoMethod.Invoke()". Remove it.
              stackFrames.RemoveAt(stackFrames.Count - 1);

              // Search for first unit testing api frame
              int index = -1;
              foreach (StackFrame sf in stackFrames) {
            MethodBase method = sf.GetMethod();
            if (method.DeclaringType.Namespace != typeof(Assert).Namespace) {
              break;
            }

            index++;
              }

              if (index != -1) {
            stackFrames.RemoveRange(0, index);
              }

              return stackFrames;
        }
Example #14
0
        // this function removes rinshan tsumo
        List<MJsonMessageAll> RecursiveFilterTsumo(List<MJsonMessageAll> msgobjList)
        {
            var lastKanIndex = msgobjList.FindIndex(e => e.IsKAKAN() || e.IsDAIMINKAN() || e.IsANKAN());

            if (lastKanIndex == -1)
            {
                return msgobjList;
            }

            var rinshanIndex = lastKanIndex + 1;
            if (rinshanIndex >= msgobjList.Count)
            {
                return msgobjList.GetRange(0, lastKanIndex);
            }
            else
            {
                msgobjList.RemoveRange(lastKanIndex, 2);
                return RecursiveFilterTsumo(msgobjList);
            }
        }
        private void LProdExperimentZ3(BitWidth encoding)
        {
            List<string> regexes = new List<string>(SampleRegexes.regexes);
            regexes.RemoveRange(6, regexes.Count - 6); //just consider the first 100 cases

            int nonemptyCount = 0;

            for (int i = 0; i < regexes.Count; i++)
                for (int j = 0; j < regexes.Count; j++)
                {
                    string regexA = regexes[i];
                    string regexB = regexes[j];

                    var z3p = new Z3Provider(encoding);

                    z3p.MainSolver.Push();

                    var A = z3p.RegexConverter.Convert(regexA, System.Text.RegularExpressions.RegexOptions.None);
                    var B = z3p.RegexConverter.Convert(regexB, System.Text.RegularExpressions.RegexOptions.None);

                    List<Expr> witness;
                    bool C = Automaton<Expr>.CheckProduct(A, B, 0, out witness);

                    if (i == j)
                        Assert.IsTrue(C, "product must me nonempty");
                    if (C)
                    {
                        nonemptyCount += 1;
                        string s = new String(Array.ConvertAll(witness.ToArray(), cs => { return z3p.GetCharValue(z3p.MainSolver.FindOneMember(cs).Value); }));
                        Assert.IsTrue(Regex.IsMatch(s, regexA, RegexOptions.None), "regex mismatch");
                        Assert.IsTrue(Regex.IsMatch(s, regexB, RegexOptions.None), "regex mismatch");
                    }

                    z3p.MainSolver.Pop();
                }
            Assert.AreEqual<int>(10, nonemptyCount, "wrong number of empty intersections");
        }
Example #16
0
        public void ModifyExplicitModTest()
        {
            SrmDocument docStudy7 = CreateStudy7Doc();
            var settings = docStudy7.Settings.ChangeTransitionFilter(filter => filter.ChangeAutoSelect(false));
            var listStaticMods = settings.PeptideSettings.Modifications.StaticModifications;
            var listHeavyMods = new List<StaticMod>(settings.PeptideSettings.Modifications.HeavyModifications);

            // Change an explicit heavy modification to something new
            var modV = new StaticMod("Heavy V", "V", null, LabelAtoms.C13|LabelAtoms.N15);
            listHeavyMods.Add(modV);

            IdentityPath path = docStudy7.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var peptideMod = (PeptideDocNode) docStudy7.FindNode(path);
            var explicitMods = peptideMod.ExplicitMods;
            explicitMods = explicitMods.ChangeHeavyModifications(new[] {explicitMods.HeavyModifications[0].ChangeModification(modV)});
            var docHeavyV = docStudy7.ChangePeptideMods(path, explicitMods, listStaticMods, listHeavyMods);

            var modSettings = docHeavyV.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(5, modSettings.HeavyModifications.Count);
            Assert.AreEqual(4, modSettings.HeavyModifications.Count(mod => mod.Formula != null));
            Assert.AreEqual(1, modSettings.HeavyModifications.Count(mod => mod.Label13C && mod.Label15N));
            Assert.AreEqual(3, docHeavyV.Peptides.Count(peptide => peptide.HasExplicitMods));
            Assert.AreEqual(1, docHeavyV.Peptides.Count(peptide => peptide.HasExplicitMods &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));
            Assert.AreEqual(1, docHeavyV.Peptides.Count(peptide => peptide.HasExplicitMods &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.Label15N));

            // Change an explicit heavy modification to something new
            listHeavyMods = new List<StaticMod>(settings.PeptideSettings.Modifications.HeavyModifications);
            modV = listHeavyMods[2] = ATOMIC_HEAVY_MODS[2];

            explicitMods = peptideMod.ExplicitMods;
            explicitMods = explicitMods.ChangeHeavyModifications(new[] { explicitMods.HeavyModifications[0].ChangeModification(modV) });
            var doc13V = docStudy7.ChangePeptideMods(path, explicitMods, listStaticMods, listHeavyMods);

            modSettings = doc13V.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(4, modSettings.HeavyModifications.Count);
            Assert.AreEqual(3, modSettings.HeavyModifications.Count(mod => mod.Formula != null));
            Assert.AreEqual(1, modSettings.HeavyModifications.Count(mod => mod.Label13C));
            Assert.AreEqual(3, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods));
            Assert.AreEqual(2, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));

            // No change to the peptide, but change an orthoganal modification
            path = docStudy7.GetPathTo((int)SrmDocument.Level.Molecules, docStudy7.Peptides.Count() - 1);
            peptideMod = (PeptideDocNode)docStudy7.FindNode(path);
            doc13V = docStudy7.ChangePeptideMods(path, peptideMod.ExplicitMods, listStaticMods, listHeavyMods);

            modSettings = doc13V.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(4, modSettings.HeavyModifications.Count);
            Assert.AreEqual(3, modSettings.HeavyModifications.Count(mod => mod.Formula != null));
            Assert.AreEqual(1, modSettings.HeavyModifications.Count(mod => mod.Label13C));
            Assert.AreEqual(3, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods));
            Assert.AreEqual(2, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));

            // No change to the peptide, but remove all other modifications from global lists
            var docClear = docStudy7.ChangePeptideMods(path, peptideMod.ExplicitMods,
                new StaticMod[0], new[] {listHeavyMods[3]});
            Assert.AreSame(docClear, docStudy7);

            // Remove explicit modifications from the global lists
            listHeavyMods.RemoveRange(2, 2);
            // Mimic the way PeptideSettingsUI would change the settings
            var docRemoveExplicit = docStudy7.ChangeSettings(docStudy7.Settings.ChangePeptideModifications(
                mods => mods.ChangeHeavyModifications(listHeavyMods)
                    .DeclareExplicitMods(docStudy7, listStaticMods, listHeavyMods)));
            // Test expected changes
            modSettings = docRemoveExplicit.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(2, modSettings.HeavyModifications.Count);
            Assert.AreEqual(3, docRemoveExplicit.Peptides.Count(peptide => peptide.HasExplicitMods));
            // Should leave no heavy modifications on the explicitly modified peptides
            Assert.AreEqual(0, docRemoveExplicit.Peptides.Count(peptide => peptide.HasExplicitMods &&
                peptide.ExplicitMods.HeavyModifications.Count > 0));
        }
        private void ProdExperimentZ3(BitWidth encoding)
        {
            List<string> regexes = new List<string>(SampleRegexes.regexes);
            regexes.RemoveRange(6, regexes.Count - 6); //just consider the first 6 cases

            int nonemptyCount = 0;

            var z3p = new Z3Provider(encoding);

            for (int i = 0; i < regexes.Count; i++)
                for (int j = 0; j < regexes.Count; j++)
                {

                    string regexA = regexes[i];
                    string regexB = regexes[j];

                    z3p.MainSolver.Push();

                    var A = z3p.RegexConverter.Convert(regexA, System.Text.RegularExpressions.RegexOptions.None);
                    var B = z3p.RegexConverter.Convert(regexB, System.Text.RegularExpressions.RegexOptions.None);

                    var C = Automaton<Expr>.MkProduct(A, B);

                    if (i == j)
                        Assert.IsFalse(C.IsEmpty);
                    if (!C.IsEmpty)
                    {
                        nonemptyCount += 1;
                        string s = GetMember(z3p, C);
                        Assert.IsTrue(Regex.IsMatch(s, regexA, RegexOptions.None), "regex mismatch");
                        Assert.IsTrue(Regex.IsMatch(s, regexB, RegexOptions.None), "regex mismatch");
                    }

                    z3p.MainSolver.Pop();
                }
            Assert.AreEqual<int>(10, nonemptyCount, "wrong number of empty intersections");
        }
Example #18
0
        public void WatersCacheTest()
        {
            // First test transition from per-replicate caching strategy to
            // single cache per document strategy.
            var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);

            // Open the replicate document, and let it reload the data from mzML
            // showing the document can find data files by name in its own directory,
            // since the document paths will not match those on disk.
            string docPath;
            var doc = InitWatersDocument(testFilesDir, out docPath);
            var docReload = InitWatersDocument(testFilesDir, "160109_Mix1_calcurve_rep.sky", out docPath);
            var docContainer = new ResultsTestDocumentContainer(doc, docPath);
            var streamManager = docContainer.ChromatogramManager.StreamManager;
            Assert.IsTrue(docContainer.SetDocument(docReload, doc, true));
            docContainer.AssertComplete();
            docReload = docContainer.Document;
            // Release file handles to cache files created during load
            Assert.IsTrue(docContainer.SetDocument(doc, docReload));
            // Delete the cache
            string cachePath = Path.ChangeExtension(docPath, ".skyd");
            FileEx.SafeDelete(cachePath);

            // Then try using cached replicate files
            // Move per-replicate cache files into place
            var replicateCacheNames = new[]
                {
                    "160109_Mix1_calcurve_rep_calcurve_070.skyd",
                    "160109_Mix1_calcurve_rep_calcurve_073.skyd"
                };
            GetCacheFiles(testFilesDir, replicateCacheNames);
            // Delete the files these cache
            DeleteFiles(testFilesDir,
                new[]
                {
                    "160109_Mix1_calcurve_070.mzML",
                    "160109_Mix1_calcurve_073.mzML",
                });
            var docCached = InitWatersDocument(testFilesDir, "160109_Mix1_calcurve_rep.sky", out docPath);
            Assert.IsTrue(docContainer.SetDocument(docCached, doc, true));
            docContainer.AssertComplete();
            docCached = docContainer.Document;

            // The document with data from the .mzML files should be the same as
            // the one loaded from the .skyd files.
            // Unfortunately, this is to hard to maintain when cache changes are made.
            // AssertEx.Cloned(docCached, docReload);

            // The one cache should be present
            Assert.IsTrue(File.Exists(cachePath));
            // And the replicate cache files should have been removed
            foreach (var cacheName in replicateCacheNames)
                Assert.IsFalse(File.Exists(testFilesDir.GetTestPath(cacheName)));

            // Save the cache file time stamp
            var cacheInfo = new FileInfo(cachePath);
            long cacheSize = cacheInfo.Length;

            // Adding files already in the document should have no impact on the cache.
            string extRaw = ExtensionTestContext.ExtWatersRaw;
            var listChromatograms = new List<ChromatogramSet>(docCached.Settings.MeasuredResults.Chromatograms)
                {
                    new ChromatogramSet("extra1",
                                        new[] { MsDataFileUri.Parse(testFilesDir.GetTestPath("160109_Mix1_calcurve_075" + extRaw)) }),
                    new ChromatogramSet("extra2",
                                        new[] { MsDataFileUri.Parse(testFilesDir.GetTestPath("160109_Mix1_calcurve_078.mzML")) })
                };

            // Adding a new file should cause the cache to grow.
            var settings = docCached.Settings.MeasuredResults.ChangeChromatograms(listChromatograms);
            var docGrow = docCached.ChangeMeasuredResults(settings);
            Assert.IsTrue(docContainer.SetDocument(docGrow, docCached, true));
            docContainer.AssertComplete();
            docGrow = docContainer.Document;

            cacheInfo = new FileInfo(cachePath);
            Assert.IsTrue(cacheSize < cacheInfo.Length);

            cacheSize = cacheInfo.Length;
            var writeTime = cacheInfo.LastWriteTime;

            listChromatograms.Add(
                    new ChromatogramSet("double",
                        new[]
                            {
                                testFilesDir.GetTestPath("160109_Mix1_calcurve_075" + extRaw),
                                testFilesDir.GetTestPath("160109_Mix1_calcurve_078.mzML")
                            }));

            settings = docGrow.Settings.MeasuredResults.ChangeChromatograms(listChromatograms);
            var docNoCacheChange1 = docGrow.ChangeMeasuredResults(settings);
            Assert.IsTrue(docContainer.SetDocument(docNoCacheChange1, docGrow, true));
            docContainer.AssertComplete();
            docNoCacheChange1 = docContainer.Document;

            Assert.AreEqual(writeTime, File.GetLastWriteTime(cachePath));

            // Removing files should have no impact, until optimized
            listChromatograms.RemoveRange(listChromatograms.Count - 2, 2);
            listChromatograms.RemoveAt(1);

            settings = docNoCacheChange1.Settings.MeasuredResults.ChangeChromatograms(listChromatograms);
            var docNoCacheChange2 = docNoCacheChange1.ChangeMeasuredResults(settings);
            Assert.IsTrue(docContainer.SetDocument(docNoCacheChange2, docNoCacheChange1, true));
            docContainer.AssertComplete();
            docNoCacheChange2 = docContainer.Document;

            Assert.AreEqual(writeTime, File.GetLastWriteTime(cachePath));

            // Optimizing should shrink the cache
            var results = docNoCacheChange2.Settings.MeasuredResults.OptimizeCache(docPath, streamManager);
            var docOptimized = new SrmDocument(docNoCacheChange2,
                                               docNoCacheChange2.Settings.ChangeMeasuredResults(results),
                                               docNoCacheChange2.Children);
            // This should not cause a reload
            Assert.IsTrue(docContainer.SetDocument(docOptimized, docNoCacheChange2, false));

            cacheInfo = new FileInfo(cachePath);
            Assert.IsTrue(cacheSize > cacheInfo.Length);

            // Test file caches
            // First reload the files from .mzML
            docReload = InitWatersDocument(testFilesDir, "160109_Mix1_calcurve_file.sky", out docPath);
            // Change the path to use the right .skyd file
            docContainer.DocumentFilePath = docPath;
            Assert.IsTrue(docContainer.SetDocument(docReload, docOptimized, true));
            docContainer.AssertComplete();
            docReload = docContainer.Document;
            // Release file handles to cache files created during load
            Assert.IsTrue(docContainer.SetDocument(doc, docReload));
            // Delete the cache
            cachePath = Path.ChangeExtension(docPath, ".skyd");
            FileEx.SafeDelete(cachePath);

            // Then try using cached files
            // Move per-file cache files into place
            var fileCacheNames = new[]
                {
                    "160109_Mix1_calcurve_075.mzML.skyd",
                    "160109_Mix1_calcurve_078.mzML.skyd"
                };
            GetCacheFiles(testFilesDir, fileCacheNames);
            // Swap the mzML files, so the test will fail, if not reading from the cache
            // CONSIDER: Should this really work, since they have different time stamps?
            string file075 = testFilesDir.GetTestPath("160109_Mix1_calcurve_075.mzML");
            string file078 = testFilesDir.GetTestPath("160109_Mix1_calcurve_078.mzML");
            string fileTemp = file075 + ".tmp";
            File.Move(file075, fileTemp);
            File.Move(file078, file075);
            File.Move(fileTemp, file078);

            docCached = InitWatersDocument(testFilesDir, "160109_Mix1_calcurve_file.sky", out docPath);
            // Make sure cache files exactly match the names the loader will look for
            var listResultsFiles = new List<MsDataFileUri>();
            foreach (var chromatogram in docCached.Settings.MeasuredResults.Chromatograms)
                listResultsFiles.AddRange(chromatogram.MSDataFilePaths);
            for (int i = 0; i < fileCacheNames.Length; i++)
            {
                string partPath = ChromatogramCache.PartPathForName(docPath, listResultsFiles[i]);
                File.Move(testFilesDir.GetTestPath(fileCacheNames[i]), partPath);
            }

            Assert.IsTrue(docContainer.SetDocument(docCached, doc, true));
            docContainer.AssertComplete();
            // docCached = docContainer.Document;

            // The document with data from the .mzML files should be the same as
            // the one loaded from the .skyd files.
            // Unfortunately, this is to hard to maintain when cache changes are made.
            // AssertEx.Cloned(docCached, docReload);

            // The one cache should be present
            Assert.IsTrue(File.Exists(Path.ChangeExtension(docPath, ".skyd")));
            // And the replicate cache files should have been removed
            foreach (var cacheName in fileCacheNames)
                Assert.IsFalse(File.Exists(testFilesDir.GetTestPath(cacheName)));

            // Release file handles
            docContainer.Release();
            testFilesDir.Dispose();
        }