Esempio n. 1
1
        public void Load(string indexFileName)
        {
            using (var file = File.OpenRead(indexFileName))
            using (var decompressor = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(file))
            {
                var serializer = new NetSerializer.Serializer(new Type[] { typeof(Indexes) });
                Indexes indexes = (Indexes)serializer.Deserialize(decompressor);
                _chunkIdToFirstNonFreeObjectInChunk = indexes.ChunkIdToFirstNonFreeObjectInChunk;
                _startOfChunkToChunkId = indexes.StartOfChunkToChunkId;
                _chunkToReferencingChunks = indexes.ChunkToReferencingChunks;
                _directlyRooted = new HashSet<ulong>(indexes.DirectlyRooted);
                _staticRootsEnumerated = indexes.StaticRootsEnumerated;
                _allRoots = indexes.AllRoots;
                _chunkSize = indexes.ChunkSize;
            }

            if (!_staticRootsEnumerated)
            {
                _context.WriteWarningLine("This heap index does not have detailed static root information. " +
                    "As a result, you will not see the names of static variables referencing your objects, " +
                    "only their addresses. Recreate the index without the --fast switch to get full " +
                    "information. This may be slower.");
            }
        }
Esempio n. 2
0
 public static void Serialize <T>(string filePath, T objectToWrite, bool gzip = false)
 {
     NetSerializer.Serializer Serializer = new NetSerializer.Serializer(new Type[] { typeof(T) });
     fileLock.TryAdd(filePath, new ReaderWriterLockSlim());
     if (fileLock.TryGetValue(filePath, out ReaderWriterLockSlim rwlock))
     {
         rwlock.EnterWriteLock();
         try {
             using (Stream stream = File.Open(filePath, FileMode.Create)) {
                 if (gzip)
                 {
                     using (GZipStream gzipSteam = new GZipStream(stream, CompressionMode.Compress)) {
                         Serializer.Serialize(gzipSteam, objectToWrite);
                     }
                 }
                 else
                 {
                     Serializer.Serialize(stream, objectToWrite);
                 }
             }
         } finally {
             rwlock.ExitWriteLock();
         }
     }
 }
Esempio n. 3
0
        private void GenerateIndexes(IndexingEngine indexEngine, List <DbForTask> dbFilenameList, ref List <CompactPeptide> peptideIndex, ref List <int>[] fragmentIndex, string taskId)
        {
            string pathToFolderWithIndices = GetExistingFolderWithIndices(indexEngine, dbFilenameList);

            if (pathToFolderWithIndices == null)
            {
                var output_folderForIndices = GenerateOutputFolderForIndices(dbFilenameList);
                Status("Writing params...", new List <string> {
                    taskId
                });
                var paramsFile = Path.Combine(output_folderForIndices, "indexEngine.params");
                WriteIndexEngineParams(indexEngine, paramsFile);
                FinishedWritingFile(paramsFile, new List <string> {
                    taskId
                });

                Status("Running Index Engine...", new List <string> {
                    taskId
                });
                var indexResults = (IndexingResults)indexEngine.Run();
                peptideIndex  = indexResults.PeptideIndex;
                fragmentIndex = indexResults.FragmentIndex;

                Status("Writing peptide index...", new List <string> {
                    taskId
                });
                var peptideIndexFile = Path.Combine(output_folderForIndices, "peptideIndex.ind");
                WritePeptideIndex(peptideIndex, peptideIndexFile);
                FinishedWritingFile(peptideIndexFile, new List <string> {
                    taskId
                });

                Status("Writing fragment index...", new List <string> {
                    taskId
                });
                var fragmentIndexFile = Path.Combine(output_folderForIndices, "fragmentIndex.ind");
                WriteFragmentIndexNetSerializer(fragmentIndex, fragmentIndexFile);
                FinishedWritingFile(fragmentIndexFile, new List <string> {
                    taskId
                });
            }
            else
            {
                Status("Reading peptide index...", new List <string> {
                    taskId
                });
                var messageTypes = GetSubclassesAndItself(typeof(List <CompactPeptide>));
                var ser          = new NetSerializer.Serializer(messageTypes);
                using (var file = File.OpenRead(Path.Combine(pathToFolderWithIndices, "peptideIndex.ind")))
                    peptideIndex = (List <CompactPeptide>)ser.Deserialize(file);

                Status("Reading fragment index...", new List <string> {
                    taskId
                });
                messageTypes = GetSubclassesAndItself(typeof(List <int>[]));
                ser          = new NetSerializer.Serializer(messageTypes);
                using (var file = File.OpenRead(Path.Combine(pathToFolderWithIndices, "fragmentIndex.ind")))
                    fragmentIndex = (List <int>[])ser.Deserialize(file);
            }
        }
Esempio n. 4
0
        public static void TestCompactPeptideSerialization()
        {
            // purpose of this test is to serialize/deserialize a CompactPeptide and make sure the deserialized peptide
            // has the same properties as before it was serialized. This peptide is unmodified
            string sequence = "PEPTIDE";
            PeptideWithSetModifications p = new PeptideWithSetModifications(sequence, new Dictionary <string, Modification>(), 0, null, null, 0, 7, 0, null);
            CompactPeptide cp             = p.CompactPeptide(FragmentationTerminus.Both);
            CompactPeptide deserializedCp = null;

            string dir = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestCompactPeptideSerialization");

            System.IO.Directory.CreateDirectory(dir);
            string path = System.IO.Path.Combine(dir, "myCompactPeptideIndex.ind");

            var messageTypes = typeof(CompactPeptide);
            var ser          = new NetSerializer.Serializer(new List <Type> {
                messageTypes
            });

            using (var file = System.IO.File.Create(path))
            {
                ser.Serialize(file, cp);
            }

            using (var file = System.IO.File.OpenRead(path))
            {
                deserializedCp = (CompactPeptide)ser.Deserialize(file);
            }

            Assert.That(cp.Equals(deserializedCp));
        }
Esempio n. 5
0
        private static void WriteFragmentIndexNetSerializer(List <int>[] fragmentIndex, string fragmentIndexFile)
        {
            var messageTypes = GetSubclassesAndItself(typeof(List <int>[]));
            var ser          = new NetSerializer.Serializer(messageTypes);

            using (var file = File.Create(fragmentIndexFile))
                ser.Serialize(file, fragmentIndex);
        }
Esempio n. 6
0
        private static void WritePeptideIndex(List <CompactPeptide> peptideIndex, string peptideIndexFile)
        {
            var messageTypes = GetSubclassesAndItself(typeof(List <CompactPeptide>));
            var ser          = new NetSerializer.Serializer(messageTypes);

            using (var file = File.Create(peptideIndexFile))
            {
                ser.Serialize(file, peptideIndex);
            }
        }
Esempio n. 7
0
        public NETSerializerTest() {
            var type = typeof(INetMessage);
            var types = type.Assembly.GetTypes()
                .Where(t => !t.IsInterface && t.IsClass && !t.IsAbstract && type.IsAssignableFrom(t))
                .ToArray();

            NetSerializer.Serializer instance = new NetSerializer.Serializer(types);
            NETSerializer ns = new NETSerializer(instance);
            SerializerFactory.AddSerializer(new NETSerializer(instance), "NET");
        }
Esempio n. 8
0
        private void WriteFragmentIndexNetSerializer(List <int>[] fragmentIndex, string fragmentIndexFile, string taskId)
        {
            var messageTypes = GetSubclassesAndItself(typeof(Dictionary <float, List <int> >));
            var ser          = new NetSerializer.Serializer(messageTypes);

            using (var file = File.Create(fragmentIndexFile))
                ser.Serialize(file, fragmentIndex);
            FinishedWritingFile(fragmentIndexFile, new List <string> {
                taskId
            });
        }
        public NETSerializerTest()
        {
            var type  = typeof(INetMessage);
            var types = type.Assembly.GetTypes()
                        .Where(t => !t.IsInterface && t.IsClass && !t.IsAbstract && type.IsAssignableFrom(t))
                        .ToArray();

            NetSerializer.Serializer instance = new NetSerializer.Serializer(types);
            NETSerializer            ns       = new NETSerializer(instance);

            SerializerFactory.AddSerializer(new NETSerializer(instance), "NET");
        }
Esempio n. 10
0
        public static void Main(string[] args)
        {
#if NETFULL
            NetSerializer.Serializer instance = new NetSerializer.Serializer(new[] { typeof(Foo), typeof(SerializerWrapper) });
            NETSerializer            ns       = new NETSerializer(instance);
            SerializerFactory.AddSerializer(new NETSerializer(instance), "NET");
#endif
            SerializerFactory.AddSerializer <JilSerializer>("jil");
            SerializerFactory.AddSerializer <JsonNetSerializer>("jsonNet");
            SerializerFactory.AddSerializer <ProtoBufSerializer>("ProtoBuf");


            TestExcute.Excute(typeof(Program));
        }
Esempio n. 11
0
        private void WritePeptideIndex(List <CompactPeptide> peptideIndex, string peptideIndexFile, string taskId)
        {
            var messageTypes = GetSubclassesAndItself(typeof(List <CompactPeptide>));
            var ser          = new NetSerializer.Serializer(messageTypes);

            using (var file = File.Create(peptideIndexFile))
            {
                ser.Serialize(file, peptideIndex);
            }

            FinishedWritingFile(peptideIndexFile, new List <string> {
                taskId
            });
        }
Esempio n. 12
0
        public static void TestSerializationPeptideFromProtein()
        {
            // purpose of this test is to serialize/deserialize a PeptideWithSetModifications and make sure the deserialized peptide
            // has the same properties as before it was serialized. This peptide is unmodified and generated from digesting a protein
            Protein protein = new Protein("PEPTIDE", "Accession1", name: "MyProtein");

            PeptideWithSetModifications peptide             = protein.Digest(new DigestionParams(), new List <Modification>(), new List <Modification>()).First();
            PeptideWithSetModifications deserializedPeptide = null;

            string dir = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestSerializationPeptideFromProtein");

            System.IO.Directory.CreateDirectory(dir);
            string path = System.IO.Path.Combine(dir, "myPeptideIndex.ind");

            var messageTypes = typeof(PeptideWithSetModifications);
            var ser          = new NetSerializer.Serializer(new List <Type> {
                messageTypes
            });

            using (var file = System.IO.File.Create(path))
            {
                ser.Serialize(file, peptide);
            }

            using (var file = System.IO.File.OpenRead(path))
            {
                deserializedPeptide = (PeptideWithSetModifications)ser.Deserialize(file);
            }

            deserializedPeptide.SetNonSerializedPeptideInfo(new Dictionary <string, Modification>(), new Dictionary <string, Protein> {
                { protein.Accession, protein }
            }, peptide.DigestionParams);

            Assert.That(peptide.DigestionParams.Equals(deserializedPeptide.DigestionParams));
            Assert.That(peptide.Equals(deserializedPeptide));
            Assert.That(deserializedPeptide.Protein.Name == peptide.Protein.Name);
            Assert.That(deserializedPeptide.MonoisotopicMass == peptide.MonoisotopicMass);
            Assert.That(deserializedPeptide.SequenceWithChemicalFormulas == peptide.SequenceWithChemicalFormulas);

            var products = new List <Product>();

            deserializedPeptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> deserializedPeptideFragments = products.Select(v => v.NeutralMass).ToList();

            peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> peptideFragments = products.Select(v => v.NeutralMass).ToList();

            Assert.That(deserializedPeptideFragments.SequenceEqual(peptideFragments));
        }
Esempio n. 13
0
        public static void Main(string[] args) {
#if NETFULL
            SerializerFactory.AddSerializer<JilSerializer>("jil");
            NetSerializer.Serializer instance = new NetSerializer.Serializer(new[] { typeof(Foo), typeof(SerializerWrapper) });
            NETSerializer ns = new NETSerializer(instance);
            SerializerFactory.AddSerializer(new NETSerializer(instance), "NET");
#endif

            SerializerFactory.AddSerializer<JsonNetSerializer>("jsonNet");
            SerializerFactory.AddSerializer<ProtoBufSerializer>("ProtoBuf");



            TestExcute.Excute(typeof(Program));
        }
Esempio n. 14
0
        static Serializer()
        {
            var dataTypes = new Type[] { typeof(IntGrid2), typeof(IntGrid2Z) };
            var messageTypes = Helpers.GetSubclasses(typeof(Message));
            var objectDataTypes = Helpers.GetSubclasses(typeof(BaseGameObjectData));
            var changeTypes = Helpers.GetSubclasses(typeof(ChangeData));
            var actionTypes = Helpers.GetSubclasses(typeof(GameAction));
            var events = Helpers.GetSubclasses(typeof(GameEvent));
            var extra = new Type[] { typeof(GameColor), typeof(LivingGender), typeof(GameSeason) };
            var reports = Helpers.GetSubclasses(typeof(GameReport));
            var tileDataEnums = typeof(TileData).GetFields().Select(fi => fi.FieldType);
            var types = dataTypes.Concat(messageTypes).Concat(objectDataTypes).Concat(changeTypes).Concat(actionTypes).Concat(events)
                .Concat(extra).Concat(reports).Concat(tileDataEnums);

            s_serializer = new NetSerializer.Serializer(types.ToArray());
        }
Esempio n. 15
0
        static Serializer()
        {
            var dataTypes       = new Type[] { typeof(IntGrid2), typeof(IntGrid2Z) };
            var messageTypes    = Helpers.GetSubclasses(typeof(Message));
            var objectDataTypes = Helpers.GetSubclasses(typeof(BaseGameObjectData));
            var changeTypes     = Helpers.GetSubclasses(typeof(ChangeData));
            var actionTypes     = Helpers.GetSubclasses(typeof(GameAction));
            var events          = Helpers.GetSubclasses(typeof(GameEvent));
            var extra           = new Type[] { typeof(GameColor), typeof(LivingGender), typeof(GameSeason) };
            var reports         = Helpers.GetSubclasses(typeof(GameReport));
            var tileDataEnums   = typeof(TileData).GetFields().Select(fi => fi.FieldType);
            var types           = dataTypes.Concat(messageTypes).Concat(objectDataTypes).Concat(changeTypes).Concat(actionTypes).Concat(events)
                                  .Concat(extra).Concat(reports).Concat(tileDataEnums);

            s_serializer = new NetSerializer.Serializer(types.ToArray());
        }
Esempio n. 16
0
        public static void TestSerializationPeptideFromString()
        {
            // purpose of this test is to serialize/deserialize a PeptideWithSetModifications and make sure the deserialized peptide
            // has the same properties as before it was serialized. This peptide is unmodified and generated from reading in a string
            string sequence = "PEPTIDE";
            PeptideWithSetModifications peptide             = new PeptideWithSetModifications(sequence, new Dictionary <string, Modification>(), 0, null, null, 1, 7, 0);
            PeptideWithSetModifications deserializedPeptide = null;

            string dir = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestSerializationPeptideFromString");

            System.IO.Directory.CreateDirectory(dir);
            string path = System.IO.Path.Combine(dir, "myPeptideIndex.ind");

            var messageTypes = typeof(PeptideWithSetModifications);
            var ser          = new NetSerializer.Serializer(new List <Type> {
                messageTypes
            });

            using (var file = System.IO.File.Create(path))
            {
                ser.Serialize(file, peptide);
            }

            using (var file = System.IO.File.OpenRead(path))
            {
                deserializedPeptide = (PeptideWithSetModifications)ser.Deserialize(file);
            }

            deserializedPeptide.SetNonSerializedPeptideInfo(new Dictionary <string, Modification>(), new Dictionary <string, Protein>(), null);

            // not asserting any protein properties - since the peptide was created from a sequence string it didn't have a protein to begin with

            Assert.That(peptide.Equals(deserializedPeptide));
            Assert.That(deserializedPeptide.MonoisotopicMass == peptide.MonoisotopicMass);
            Assert.That(deserializedPeptide.SequenceWithChemicalFormulas == peptide.SequenceWithChemicalFormulas);

            var products = new List <Product>();

            deserializedPeptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> deserializedPeptideFragments = products.Select(v => v.NeutralMass).ToList();

            peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> peptideFragments = products.Select(v => v.NeutralMass).ToList();

            Assert.That(deserializedPeptideFragments.SequenceEqual(peptideFragments));
        }
Esempio n. 17
0
 public static T Deserialize <T>(byte[] arr, bool gzip = false)
 {
     NetSerializer.Serializer Serializer = new NetSerializer.Serializer(new Type[] { typeof(T) });
     try {
         using (MemoryStream memoryStream = new MemoryStream(arr)) {
             if (gzip)
             {
                 using (GZipStream gzipSteam = new GZipStream(memoryStream, CompressionMode.Decompress)) {
                     return((T)Serializer.Deserialize(gzipSteam));
                 }
             }
             return((T)Serializer.Deserialize(memoryStream));
         }
     } catch {
         return(default(T));
     }
 }
Esempio n. 18
0
        private void SerializeNetSerializer()
        {
            var s          = new MemoryStream();
            var serializer = new NetSerializer.Serializer(new[] { typeof(T) });

            serializer.Serialize(s, Value);
            var bytes = s.ToArray();

            RunTest("Net Serializer", () =>
            {
                var stream = new MemoryStream();
                serializer.Serialize(stream, Value);
            }, () =>
            {
                s.Position = 0;
                serializer.Deserialize(s);
            }, bytes.Length);
        }
Esempio n. 19
0
 private void Save(string indexFileName)
 {
     using (var file = File.Create(indexFileName))
         using (var compressor = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(file))
         {
             var serializer = new NetSerializer.Serializer(new Type[] { typeof(Indexes) });
             var indexes    = new Indexes();
             indexes.ChunkIdToFirstNonFreeObjectInChunk = _chunkIdToFirstNonFreeObjectInChunk;
             indexes.StartOfChunkToChunkId    = _startOfChunkToChunkId;
             indexes.ChunkToReferencingChunks = _chunkToReferencingChunks;
             indexes.DirectlyRooted           = _directlyRooted.ToArray();
             indexes.AllRoots = _allRoots;
             indexes.StaticRootsEnumerated = _staticRootsEnumerated;
             indexes.ChunkSize             = _chunkSize;
             serializer.Serialize(compressor, indexes);
         }
     _context.WriteLine("Wrote index file of size {0}",
                        ((ulong)new FileInfo(indexFileName).Length).ToMemoryUnits());
 }
Esempio n. 20
0
 public static byte[] Serialize <T>(T objectToWrite, bool gzip = false)
 {
     NetSerializer.Serializer Serializer = new NetSerializer.Serializer(new Type[] { typeof(T) });
     try {
         using (var stream = new MemoryStream()) {
             if (gzip)
             {
                 using (GZipStream gzipSteam = new GZipStream(stream, CompressionMode.Compress)) {
                     Serializer.Serialize(gzipSteam, objectToWrite);
                 }
             }
             else
             {
                 Serializer.Serialize(stream, objectToWrite);
             }
             return(stream.ToArray());
         }
     } catch (Exception e) {
         return(null);
     }
 }
Esempio n. 21
0
        private void RunBenchmarkNetSerializer <T>(T obj, int count)
        {
            try
            {
                Stopwatch sw;
                //-----------------------------------

                var netSerializer = new NetSerializer.Serializer(new[] { typeof(T) });

                var pbuffMem = new MemoryStream();
                netSerializer.Serialize(pbuffMem, obj);

                using (var mem = new MemoryStream())
                {
                    sw = Stopwatch.StartNew();
                    for (int i = 0; i < count; i++)
                    {
                        netSerializer.Serialize(mem, obj);
                        mem.SetLength(0);
                    }
                }
                sw.Stop();
                Log("NetSerializer.Serialize		took: "+ ToString(sw.Elapsed) + "  data-size: " + pbuffMem.Length);


                sw = Stopwatch.StartNew();
                for (int i = 0; i < count; i++)
                {
                    pbuffMem.Seek(0, SeekOrigin.Begin);
                    netSerializer.Deserialize(pbuffMem);
                }
                sw.Stop();
                Log("NetSerializer.Deserialize		took: "+ ToString(sw.Elapsed));
            }
            catch (Exception ex)
            {
                Log("NetSerializer failed, " + ex.Message);
            }
        }
Esempio n. 22
0
 public static T Deserialize <T>(string filePath, bool gzip = false)
 {
     NetSerializer.Serializer Serializer = new NetSerializer.Serializer(new Type[] { typeof(T) });
     fileLock.TryAdd(filePath, new ReaderWriterLockSlim());
     if (fileLock.TryGetValue(filePath, out ReaderWriterLockSlim rwlock))
     {
         rwlock.EnterReadLock();
         try {
             using (Stream stream = File.Open(filePath, FileMode.Open)) {
                 if (gzip)
                 {
                     using (GZipStream gzipSteam = new GZipStream(stream, CompressionMode.Decompress)) {
                         return((T)Serializer.Deserialize(gzipSteam));
                     }
                 }
                 return((T)Serializer.Deserialize(stream));
             }
         } finally {
             rwlock.ExitReadLock();
         }
     }
     return(default(T));
 }
Esempio n. 23
0
        public void Load(string indexFileName)
        {
            using (var file = File.OpenRead(indexFileName))
                using (var decompressor = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(file))
                {
                    var     serializer = new NetSerializer.Serializer(new Type[] { typeof(Indexes) });
                    Indexes indexes    = (Indexes)serializer.Deserialize(decompressor);
                    _chunkIdToFirstNonFreeObjectInChunk = indexes.ChunkIdToFirstNonFreeObjectInChunk;
                    _startOfChunkToChunkId    = indexes.StartOfChunkToChunkId;
                    _chunkToReferencingChunks = indexes.ChunkToReferencingChunks;
                    _directlyRooted           = new HashSet <ulong>(indexes.DirectlyRooted);
                    _staticRootsEnumerated    = indexes.StaticRootsEnumerated;
                    _allRoots  = indexes.AllRoots;
                    _chunkSize = indexes.ChunkSize;
                }

            if (!_staticRootsEnumerated)
            {
                _context.WriteWarningLine("This heap index does not have detailed static root information. " +
                                          "As a result, you will not see the names of static variables referencing your objects, " +
                                          "only their addresses. Recreate the index without the --fast switch to get full " +
                                          "information. This may be slower.");
            }
        }
Esempio n. 24
0
 public void Initialize(IEnumerable <Type> types)
 {
     _netSerializer = new NetSerializer.Serializer(types);
 }
Esempio n. 25
0
 private void Save(string indexFileName)
 {
     using (var file = File.Create(indexFileName))
     using (var compressor = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(file))
     {
         var serializer = new NetSerializer.Serializer(new Type[] { typeof(Indexes) });
         var indexes = new Indexes();
         indexes.ChunkIdToFirstNonFreeObjectInChunk = _chunkIdToFirstNonFreeObjectInChunk;
         indexes.StartOfChunkToChunkId = _startOfChunkToChunkId;
         indexes.ChunkToReferencingChunks = _chunkToReferencingChunks;
         indexes.DirectlyRooted = _directlyRooted.ToArray();
         indexes.AllRoots = _allRoots;
         indexes.StaticRootsEnumerated = _staticRootsEnumerated;
         indexes.ChunkSize = _chunkSize;
         serializer.Serialize(compressor, indexes);
     }
     _context.WriteLine("Wrote index file of size {0}",
         ((ulong)new FileInfo(indexFileName).Length).ToMemoryUnits());
 }
Esempio n. 26
0
        public static void TestSerializationPeptideFromProteinWithMod()
        {
            // purpose of this test is to serialize/deserialize a PeptideWithSetModifications and make sure the deserialized peptide
            // has the same properties as before it was serialized. This peptide is modified with a phosphorylation

            ModificationMotif.TryGetMotif("T", out ModificationMotif motif);

            Dictionary <DissociationType, List <double> > myNeutralLosses = new Dictionary <DissociationType, List <double> >()
            {
                { DissociationType.HCD, new List <double> {
                      ChemicalFormula.ParseFormula("H3 O4 P1").MonoisotopicMass
                  } },
                { DissociationType.ETD, new List <double>()
                  {
                      ChemicalFormula.ParseFormula("H3 N1").MonoisotopicMass
                  } }                                                                                                   // this makes no sense in real life, it's just for a unit test
            };

            Modification mod = new Modification(_originalId: "phospho", _modificationType: "testModType", _target: motif, _chemicalFormula: ChemicalFormula.ParseFormula("H1 O3 P1"), _neutralLosses: myNeutralLosses, _locationRestriction: "Anywhere.");

            Dictionary <int, List <Modification> > mods = new Dictionary <int, List <Modification> > {
                { 4, new List <Modification> {
                      mod
                  } }
            };

            Protein protein = new Protein("PEPTIDE", "Accession1", name: "MyProtein", oneBasedModifications: mods);

            PeptideWithSetModifications peptide             = protein.Digest(new DigestionParams(), new List <Modification>(), new List <Modification>()).Where(v => v.AllModsOneIsNterminus.Count == 1).First();
            PeptideWithSetModifications deserializedPeptide = null;

            string dir = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestSerializationPeptideFromProteinWithMod");

            System.IO.Directory.CreateDirectory(dir);
            string path = System.IO.Path.Combine(dir, "myPeptideIndex.ind");

            var messageTypes = typeof(PeptideWithSetModifications);
            var ser          = new NetSerializer.Serializer(new List <Type> {
                messageTypes
            });

            using (var file = System.IO.File.Create(path))
            {
                ser.Serialize(file, peptide);
            }

            using (var file = System.IO.File.OpenRead(path))
            {
                deserializedPeptide = (PeptideWithSetModifications)ser.Deserialize(file);
            }

            Dictionary <string, Modification> stringToMod = new Dictionary <string, Modification> {
                { mods.Values.First().First().IdWithMotif, mods.Values.First().First() }
            };

            deserializedPeptide.SetNonSerializedPeptideInfo(stringToMod, new Dictionary <string, Protein> {
                { protein.Accession, protein }
            }, peptide.DigestionParams);

            Assert.That(peptide.Equals(deserializedPeptide));
            Assert.That(deserializedPeptide.Protein.Name == peptide.Protein.Name);
            Assert.That(deserializedPeptide.MonoisotopicMass == peptide.MonoisotopicMass);
            Assert.That(deserializedPeptide.SequenceWithChemicalFormulas == peptide.SequenceWithChemicalFormulas);

            var products = new List <Product>();

            deserializedPeptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> deserializedPeptideFragments = products.Select(v => v.NeutralMass).ToList();

            peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> peptideFragments = products.Select(v => v.NeutralMass).ToList();

            Assert.That(deserializedPeptideFragments.SequenceEqual(peptideFragments));
        }
Esempio n. 27
0
        public void Setup()
        {
            var jsonNetOptions = new JsonSerializerSettings
            {
                Formatting = Formatting.None,
                Converters = new JsonConverter[] {
                    new IsoDateTimeConverter {
                        DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
                    },
                    new LongToStringConverter(),
                },

                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                NullValueHandling     = NullValueHandling.Ignore
            };

            var serializeOptions = new JsonSerializerOptions
            {
                WriteIndented               = false,
                IgnoreNullValues            = false,
                PropertyNameCaseInsensitive = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            serializeOptions.Converters.Add(new ImplicitInt64Converter());
            serializeOptions.Converters.Add(new ImplicitUInt64Converter());
            serializeOptions.Converters.Add(new ImplicitDateTimeConverter());
            serializeOptions.Converters.Add(new ImplicitDateTimeOffsetConverter());

            var deserializeOptions = new JsonSerializerOptions
            {
                WriteIndented               = false,
                IgnoreNullValues            = true,
                PropertyNameCaseInsensitive = true,
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            deserializeOptions.Converters.Add(new ImplicitInt16Converter());
            deserializeOptions.Converters.Add(new ImplicitUInt16Converter());
            deserializeOptions.Converters.Add(new ImplicitInt32Converter());
            deserializeOptions.Converters.Add(new ImplicitUInt32Converter());
            deserializeOptions.Converters.Add(new ImplicitInt64Converter());
            deserializeOptions.Converters.Add(new ImplicitUInt64Converter());
            deserializeOptions.Converters.Add(new ImplicitDecimalConverter());
            deserializeOptions.Converters.Add(new ImplicitDoubleConverter());
            deserializeOptions.Converters.Add(new ImplicitSingleConverter());
            deserializeOptions.Converters.Add(new ImplicitByteConverter());
            deserializeOptions.Converters.Add(new ImplicitSByteConverter());
            deserializeOptions.Converters.Add(new ImplicitDateTimeConverter());
            deserializeOptions.Converters.Add(new ImplicitDateTimeOffsetConverter());

            serializeToStringObject = new
            {
                int16    = 111.ToString(),
                uint16   = ushort.MaxValue.ToString(),
                int32    = int.MaxValue.ToString(),
                uint32   = uint.MaxValue.ToString(),
                int32N   = "".ToString(),
                int64    = 12321.ToString(),
                uint64   = ulong.MaxValue.ToString(),
                boolean  = true,
                decimalV = decimal.MaxValue.ToString(),
                doubleV  = "1.123445767",
                floatV   = "1.1111",
                byteV    = byte.MaxValue.ToString(),
                sbyteV   = sbyte.MaxValue.ToString(),
                charV    = 'c',
                date     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                date1    = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                arr      = new string[] { "a", "b" },
                TestEnum = TestEnum.Approved
            };

            jsonFromString = JsonConvert.SerializeObject(serializeToStringObject, jsonNetOptions);

            serializeToStringClass = (TestClass)JsonConvert.DeserializeObject(jsonFromString, typeof(TestClass), jsonNetOptions);

            jsonNetSerializer  = new JsonNetSerializer(jsonNetOptions);
            textJsonSerializer = new TextJsonSerializer(serializeOptions, deserializeOptions);
            jilSerializer      = new JilSerializer();

            dataContractSerializer = new DataContractSerializer();
#if !NET5_0
            binarySerializer = new BinarySerializer();
#endif
            protoBufSerializer = new ProtoBufSerializer();

            NetSerializer.Serializer instance = new NetSerializer.Serializer(new[] { typeof(TestClass) });
            netSerializer = new NETSerializer(instance);

            dataContractFromString = dataContractSerializer.SerializeToString(serializeToStringClass);
#if !NET5_0
            binaryFromString = binarySerializer.SerializeToString(serializeToStringClass);
#endif
            protoBufFromString      = protoBufSerializer.SerializeToString(serializeToStringClass);
            netSerializerFromString = netSerializer.SerializeToString(serializeToStringClass);

            jilFromString = jilSerializer.SerializeToString(serializeToStringClass);
        }
Esempio n. 28
0
        public void Setup()
        {
            //
            // Create example data
            var parent1 = new Person
            {
                Age       = -901,
                FirstName = "Parent 1",
                LastName  = "abc",
                Sex       = Sex.Male,
            };
            var parent2 = new Person
            {
                Age       = 7881964,
                FirstName = "Parent 2",
                LastName  = "xyz",
                Sex       = Sex.Female,
            };

            _person = new Person
            {
                Age       = 5,
                FirstName = "Riki",
                LastName  = "Example Person Object",
                Sex       = Sex.Unknown,
                Parent1   = parent1,
                Parent2   = parent2,
            };

            _list = Enumerable.Range(25000, 100).Select(x => new Person {
                Age = x, FirstName = "a", LastName = "b", Sex = Sex.Female
            }).ToArray();

            //
            // Config Serializers
            _wire = new Wire.Serializer(new Wire.SerializerOptions(knownTypes: new Type[] { typeof(Person), typeof(Person[]) }));

            _netSerializer = new NetSerializer.Serializer(rootTypes: new Type[] { typeof(Person), typeof(Person[]) });

            var config = new SerializerConfig();

            config.DefaultTargets = TargetMember.AllPublic;
            var knownTypes = new[] { typeof(Person), typeof(List <>), typeof(Person[]) };

            config.KnownTypes.AddRange(knownTypes);
            config.PreserveReferences = false;
            _ceras = new CerasSerializer(config);

            //
            // Run each serializer once to verify they work correctly!
            if (!Equals(RunCeras(_person), _person))
            {
                ThrowError();
            }
            if (!Equals(RunJson(_person), _person))
            {
                ThrowError();
            }
            if (!Equals(RunMessagePackCSharp(_person), _person))
            {
                ThrowError();
            }
            if (!Equals(RunProtobuf(_person), _person))
            {
                ThrowError();
            }
            if (!Equals(RunWire(_person), _person))
            {
                ThrowError();
            }
            if (!Equals(RunNetSerializer(_person), _person))
            {
                ThrowError();
            }

            void ThrowError() => throw new InvalidOperationException("Cannot continue with the benchmark because a serializer does not round-trip an object correctly. (Benchmark results will be wrong)");
        }