/// <summary>
        /// Creates literature sequence in database.
        /// </summary>
        /// <param name="commonSequence">
        /// The common sequence.
        /// </param>
        /// <param name="sequenceStream">
        /// The sequence stream.
        /// </param>
        /// <param name="language">
        /// The language id.
        /// </param>
        /// <param name="original">
        /// The original.
        /// </param>
        /// <param name="translator">
        /// The translator id.
        /// </param>
        /// <param name="dropPunctuation">
        /// Flag indicating if punctuation should be removed from text.
        /// </param>
        public void Create(CommonSequence commonSequence, Stream sequenceStream, Language language, bool original, Translator translator, bool dropPunctuation = false)
        {
            string    stringSequence = FileHelper.ReadSequenceFromStream(sequenceStream);
            BaseChain chain;

            if (commonSequence.Notation == Notation.Letters)
            {
                stringSequence = stringSequence.ToUpper();
                if (dropPunctuation)
                {
                    stringSequence = new string(stringSequence.Where(c => !char.IsPunctuation(c)).ToArray());
                }
                chain = new BaseChain(stringSequence);
            }
            else
            {
                // file always contains empty string at the end
                // TODO: rewrite this, add empty string check at the end or write a normal trim
                string[] text = stringSequence.Split(new[] { '\n', '\r', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                chain = new BaseChain(text.Select(e => (ValueString)e).Cast <IBaseObject>().ToList());
            }

            MatterRepository.CreateOrExtractExistingMatterForSequence(commonSequence);

            long[] alphabet = ElementRepository.ToDbElements(chain.Alphabet, commonSequence.Notation, true);
            Create(commonSequence, original, language, translator, alphabet, chain.Building);
        }
        /// <summary>
        /// The insert.
        /// </summary>
        /// <param name="commonSequence">
        /// The sequence.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        public void Create(CommonSequence commonSequence, long[] alphabet, int[] building, PauseTreatment pauseTreatment = PauseTreatment.NotApplicable, bool sequentialTransfer = false)
        {
            List <NpgsqlParameter> parameters = FillParams(commonSequence, alphabet, building, pauseTreatment, sequentialTransfer);

            const string Query = @"INSERT INTO music_chain (
                                        id,
                                        notation,
                                        matter_id,
                                        alphabet,
                                        building,
                                        remote_id,
                                        remote_db,
                                        pause_treatment,
                                        sequential_transfer
                                    ) VALUES (
                                        @id,
                                        @notation,
                                        @matter_id,
                                        @alphabet,
                                        @building,
                                        @remote_id,
                                        @remote_db,
                                        @pause_treatment,
                                        @sequential_transfer
                                    );";

            Db.ExecuteCommand(Query, parameters.ToArray());
        }
Exemplo n.º 3
0
            /// <summary>
            /// Initializes a new instance of the <see cref="ImportResult"/> struct.
            /// </summary>
            /// <param name="sequence">
            /// The sequence.
            /// </param>
            /// <param name="language">
            /// The language.
            /// </param>
            /// <param name="original">
            /// The original.
            /// </param>
            /// <param name="translator">
            /// The translator.
            /// </param>
            /// <param name="partial">
            /// The partial.
            /// </param>
            /// <param name="precision">
            /// The precision.
            /// </param>
            /// <param name="multisequenceName">
            /// The multisequence name.
            /// </param>
            public ImportResult(
                CommonSequence sequence,
                Language?language,
                bool?original,
                Translator?translator,
                bool?partial,
                double?precision,
                string multisequenceName)
            {
                Matter matter = sequence.Matter;

                Name                = matter.Name;
                Description         = matter.Description;
                Nature              = matter.Nature.GetDisplayValue();
                Notation            = sequence.Notation.GetDisplayValue();
                Group               = matter.Group.GetDisplayValue();
                SequenceType        = matter.SequenceType.GetDisplayValue();
                RemoteId            = sequence.RemoteId;
                Language            = language?.GetDisplayValue();
                Original            = original;
                Translator          = translator?.GetDisplayValue();
                Partial             = partial;
                Precision           = precision;
                MultisequenceName   = multisequenceName;
                MultisequenceNumber = matter.MultisequenceNumber;
                CollectionCountry   = matter.CollectionCountry;
                CollectionDate      = matter.CollectionDate;
            }
        /// <summary>
        /// Create data sequence and matter.
        /// </summary>
        /// <param name="sequence">
        /// The common sequence.
        /// </param>
        /// <param name="sequenceStream">
        /// The sequence stream.
        /// </param>
        /// <param name="precision">
        /// Precision of data sequence.
        /// </param>
        public void Create(CommonSequence sequence, Stream sequenceStream, int precision)
        {
            var stringSequence = FileHelper.ReadSequenceFromStream(sequenceStream);

            string[] text = stringSequence.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

            var cleanedSequence = text.Where(t => !t.Equals("\"volume\"") && !string.IsNullOrEmpty(t) && !string.IsNullOrWhiteSpace(t)).ToList();

            var elements = new List<IBaseObject>();

            for (int i = 0; i < cleanedSequence.Count; i++)
            {
                var element = cleanedSequence[i];
                if (element.Substring(element.Length - 2, 2).Equals(".0"))
                {
                    cleanedSequence[i] = cleanedSequence[i].Substring(0, cleanedSequence[i].Length - 2);
                }

                int intElement = int.Parse(cleanedSequence[i]);
                int multiplier = (int)Math.Pow(10, precision);
                intElement /= multiplier;
                intElement *= multiplier;

                elements.Add(new ValueInt(intElement));
            }

            var chain = new BaseChain(elements);

            MatterRepository.CreateMatterFromSequence(sequence);

            var alphabet = ElementRepository.ToDbElements(chain.Alphabet, sequence.NotationId, true);
            Create(sequence, alphabet, chain.Building);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Create data sequence and matter.
        /// </summary>
        /// <param name="sequence">
        /// The common sequence.
        /// </param>
        /// <param name="sequenceStream">
        /// The sequence stream.
        /// </param>
        /// <param name="precision">
        /// Precision of data sequence.
        /// </param>
        public void Create(CommonSequence sequence, Stream sequenceStream, int precision)
        {
            string stringSequence = FileHelper.ReadSequenceFromStream(sequenceStream);

            string[] text = stringSequence.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

            string[] cleanedSequence = text.Where(t => !t.Equals("\"volume\"") && !string.IsNullOrEmpty(t) && !string.IsNullOrWhiteSpace(t)).ToArray();

            var elements = new List <IBaseObject>(cleanedSequence.Length);

            for (int i = 0; i < cleanedSequence.Length; i++)
            {
                string element = cleanedSequence[i];
                if (element.Substring(element.Length - 2, 2).Equals(".0"))
                {
                    cleanedSequence[i] = cleanedSequence[i].Substring(0, cleanedSequence[i].Length - 2);
                }

                int intElement = int.Parse(cleanedSequence[i]);
                int multiplier = (int)Math.Pow(10, precision);
                intElement /= multiplier;
                intElement *= multiplier;

                elements.Add(new ValueInt(intElement));
            }

            var chain = new BaseChain(elements);

            MatterRepository.CreateOrExtractExistingMatterForSequence(sequence);

            long[] alphabet = ElementRepository.ToDbElements(chain.Alphabet, sequence.Notation, true);
            Create(sequence, alphabet, chain.Building);
        }
        /// <summary>
        /// The insert.
        /// </summary>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <param name="partial">
        /// The partial.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        public void Create(CommonSequence sequence, bool partial, long[] alphabet, int[] building)
        {
            List <NpgsqlParameter> parameters = FillParams(sequence, alphabet, building);

            parameters.Add(new NpgsqlParameter <bool>("partial", NpgsqlDbType.Boolean)
            {
                TypedValue = partial
            });

            const string Query = @"INSERT INTO dna_chain (
                                        id,
                                        notation,
                                        matter_id,
                                        alphabet,
                                        building,
                                        remote_id,
                                        remote_db,
                                        partial
                                    ) VALUES (
                                        @id,
                                        @notation,
                                        @matter_id,
                                        @alphabet,
                                        @building,
                                        @remote_id,
                                        @remote_db,
                                        @partial
                                    );";

            Db.ExecuteCommand(Query, parameters.ToArray());
        }
        /// <summary>
        /// Imports sequence features.
        /// </summary>
        /// <param name="metadata">
        /// The metadata.
        /// </param>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <returns>
        /// Returns tuple where first element is import result text
        /// and second element is import status as  string.
        /// </returns>
        private (string, string) ImportFeatures(GenBankMetadata metadata, CommonSequence sequence)
        {
            try
            {
                using (var subsequenceImporter = new SubsequenceImporter(metadata.Features.All, sequence.Id))
                {
                    var(featuresCount, nonCodingCount) = subsequenceImporter.CreateSubsequences();

                    string result = $"Successfully imported sequence, {featuresCount} features "
                                    + $"and {nonCodingCount} non-coding subsequences";
                    string status = "Success";

                    return(result, status);
                }
            }
            catch (Exception exception)
            {
                string result = $"successfully imported sequence but failed to import genes: {exception.Message}";
                while (exception.InnerException != null)
                {
                    exception = exception.InnerException;
                    result   += $" {exception.Message}";
                }

                string status = "Error";
                return(result, status);
            }
        }
 /// <summary>
 /// The create matter.
 /// </summary>
 /// <param name="commonSequence">
 /// The common sequence.
 /// </param>
 public void CreateMatterFromSequence(CommonSequence commonSequence)
 {
     var matter = commonSequence.Matter;
     if (matter != null)
     {
         matter.Sequence = new Collection<CommonSequence>();
         commonSequence.MatterId = CreateMatter(matter);
     }
 }
        /// <summary>
        /// The fill parameters.
        /// </summary>
        /// <param name="commonSequence">
        /// The sequence.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        /// <returns>
        /// The <see cref="List{Object}"/>.
        /// </returns>
        protected List<object> FillParams(CommonSequence commonSequence, long[] alphabet, int[] building)
        {
            if (commonSequence.Id == default(long))
            {
                commonSequence.Id = DbHelper.GetNewElementId(Db);
            }

            var parameters = new List<object>
            {
                new NpgsqlParameter
                {
                    ParameterName = "id",
                    NpgsqlDbType = NpgsqlDbType.Bigint,
                    Value = commonSequence.Id
                },
                new NpgsqlParameter
                {
                    ParameterName = "notation_id",
                    NpgsqlDbType = NpgsqlDbType.Integer,
                    Value = commonSequence.NotationId
                },
                new NpgsqlParameter
                {
                    ParameterName = "matter_id",
                    NpgsqlDbType = NpgsqlDbType.Bigint,
                    Value = commonSequence.MatterId
                },
                new NpgsqlParameter
                {
                    ParameterName = "alphabet",
                    NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Bigint,
                    Value = alphabet
                },
                new NpgsqlParameter
                {
                    ParameterName = "building",
                    NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Integer,
                    Value = building
                },
                new NpgsqlParameter
                {
                    ParameterName = "remote_id",
                    NpgsqlDbType = NpgsqlDbType.Varchar,
                    Value = (object)commonSequence.RemoteId ?? DBNull.Value
                },
                new NpgsqlParameter
                {
                    ParameterName = "remote_db_id",
                    NpgsqlDbType = NpgsqlDbType.Integer,
                    Value = (object)commonSequence.RemoteDbId ?? DBNull.Value
                }
            };
            return parameters;
        }
        public async Task <ActionResult> DeleteConfirmed(long id)
        {
            using (var db = new LibiadaWebEntities())
            {
                CommonSequence commonSequence = await db.CommonSequence.FindAsync(id);

                db.CommonSequence.Remove(commonSequence);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
        }
        /// <summary>
        /// Creates new matter or extracts existing matter from database.
        /// </summary>
        /// <param name="commonSequence">
        /// The common sequence to be used for matter creation or extraction.
        /// </param>
        public void CreateOrExtractExistingMatterForSequence(CommonSequence commonSequence)
        {
            Matter matter = commonSequence.Matter;

            if (matter != null)
            {
                matter.Sequence         = new Collection <CommonSequence>();
                commonSequence.MatterId = SaveToDatabase(matter);
            }
            else
            {
                commonSequence.Matter = db.Matter.Single(m => m.Id == commonSequence.MatterId);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// The fill parameters.
        /// </summary>
        /// <param name="commonSequence">
        /// The sequence.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        /// <returns>
        /// The <see cref="List{Object}"/>.
        /// </returns>
        private List <NpgsqlParameter> FillParams(CommonSequence commonSequence, long[] alphabet, int[] building, PauseTreatment pauseTreatment, bool sequentialTransfer)
        {
            var parameters = FillParams(commonSequence, alphabet, building);

            parameters.Add(new NpgsqlParameter <byte>("pause_treatment", NpgsqlDbType.Smallint)
            {
                TypedValue = (byte)pauseTreatment
            });
            parameters.Add(new NpgsqlParameter <bool>("sequential_transfer", NpgsqlDbType.Boolean)
            {
                TypedValue = sequentialTransfer
            });

            return(parameters);
        }
Exemplo n.º 13
0
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <param name="sequenceStream">
        /// The sequence stream.
        /// </param>
        /// <exception cref="Exception">
        /// Thrown if congeneric tracks count not equals 1 (track is not monophonic).
        /// </exception>
        public void Create(CommonSequence sequence, Stream sequenceStream)
        {
            string stringSequence = FileHelper.ReadSequenceFromStream(sequenceStream);
            var    doc            = new XmlDocument();

            doc.LoadXml(stringSequence);

            var parser = new MusicXmlParser();

            parser.Execute(doc);
            ScoreTrack tempTrack = parser.ScoreModel;

            if (tempTrack.CongenericScoreTracks.Count != 1)
            {
                throw new Exception("Track contains more then one or zero congeneric score tracks (parts).");
            }

            MatterRepository.CreateOrExtractExistingMatterForSequence(sequence);

            BaseChain notesSequence = ConvertCongenericScoreTrackToNotesBaseChain(tempTrack.CongenericScoreTracks[0]);

            long[] notesAlphabet = ElementRepository.GetOrCreateNotesInDb(notesSequence.Alphabet);
            sequence.Notation = Notation.Notes;
            Create(sequence, notesAlphabet, notesSequence.Building);

            BaseChain measuresSequence = ConvertCongenericScoreTrackToMeasuresBaseChain(tempTrack.CongenericScoreTracks[0]);

            long[] measuresAlphabet = MeasureRepository.GetOrCreateMeasuresInDb(measuresSequence.Alphabet);
            sequence.Notation = Notation.Measures;
            sequence.Id       = default;
            Create(sequence, measuresAlphabet, measuresSequence.Building);

            sequence.Notation = Notation.FormalMotifs;
            var pauseTreatments = EnumExtensions.ToArray <PauseTreatment>().Where(pt => pt != PauseTreatment.NotApplicable);

            foreach (PauseTreatment pauseTreatment in pauseTreatments)
            {
                BaseChain fmotifsSequence = ConvertCongenericScoreTrackToFormalMotifsBaseChain(tempTrack.CongenericScoreTracks[0], pauseTreatment, false);
                long[]    fmotifsAlphabet = FmotifRepository.GetOrCreateFmotifsInDb(fmotifsSequence.Alphabet);
                sequence.Id = default;
                Create(sequence, fmotifsAlphabet, fmotifsSequence.Building, pauseTreatment, false);

                fmotifsSequence = ConvertCongenericScoreTrackToFormalMotifsBaseChain(tempTrack.CongenericScoreTracks[0], pauseTreatment, true);
                fmotifsAlphabet = FmotifRepository.GetOrCreateFmotifsInDb(fmotifsSequence.Alphabet);
                sequence.Id     = default;
                Create(sequence, fmotifsAlphabet, fmotifsSequence.Building, pauseTreatment, true);
            }
        }
        /// <summary>
        /// The details.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// The <see cref="System.Threading.Tasks.Task"/>.
        /// </returns>
        public async Task <ActionResult> Details(long?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            using (var db = new LibiadaWebEntities())
            {
                CommonSequence commonSequence = db.CommonSequence.Include(c => c.Matter).Single(c => c.Id == id);
                if (commonSequence == null)
                {
                    return(HttpNotFound());
                }

                return(View(commonSequence));
            }
        }
        public async Task <ActionResult> Edit([Bind(Include = "Id,Notation,MatterId,RemoteDb,RemoteId,Description")] CommonSequence commonSequence)
        {
            using (var db = new LibiadaWebEntities())
            {
                if (ModelState.IsValid)
                {
                    db.Entry(commonSequence).State = EntityState.Modified;
                    await db.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }

                ViewBag.MatterId = new SelectList(Cache.GetInstance().Matters.ToArray(), "Id", "Name", commonSequence.MatterId);
                ViewBag.Notation = EnumHelper.GetSelectList(typeof(Notation), commonSequence.Notation);
                ViewBag.RemoteDb = EnumHelper.GetSelectList(typeof(RemoteDb), commonSequence.RemoteDb);
                return(View(commonSequence));
            }
        }
        /// <summary>
        /// The insert.
        /// </summary>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <param name="original">
        /// The original.
        /// </param>
        /// <param name="language">
        /// The language id.
        /// </param>
        /// <param name="translator">
        /// The translator id.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        public void Create(CommonSequence sequence, bool original, Language language, Translator translator, long[] alphabet, int[] building)
        {
            List <NpgsqlParameter> parameters = FillParams(sequence, alphabet, building);

            parameters.Add(new NpgsqlParameter <bool>("original", NpgsqlDbType.Boolean)
            {
                TypedValue = original
            });
            parameters.Add(new NpgsqlParameter <byte>("language", NpgsqlDbType.Smallint)
            {
                TypedValue = (byte)language
            });
            parameters.Add(new NpgsqlParameter <byte>("translator", NpgsqlDbType.Smallint)
            {
                TypedValue = (byte)translator
            });

            const string Query = @"INSERT INTO literature_chain (
                                        id,
                                        notation,
                                        matter_id,
                                        alphabet,
                                        building,
                                        remote_id,
                                        remote_db,
                                        original,
                                        language,
                                        translator
                                    ) VALUES (
                                        @id,
                                        @notation,
                                        @matter_id,
                                        @alphabet,
                                        @building,
                                        @remote_id,
                                        @remote_db,
                                        @original,
                                        @language,
                                        @translator
                                    );";

            Db.ExecuteCommand(Query, parameters.ToArray());
        }
Exemplo n.º 17
0
        /// <summary>
        /// The fill parameters.
        /// </summary>
        /// <param name="commonSequence">
        /// The sequence.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        /// <returns>
        /// The <see cref="List{Object}"/>.
        /// </returns>
        protected List <NpgsqlParameter> FillParams(CommonSequence commonSequence, long[] alphabet, int[] building)
        {
            if (commonSequence.Id == default)
            {
                commonSequence.Id = Db.GetNewElementId();
            }

            var parameters = new List <NpgsqlParameter>
            {
                new NpgsqlParameter <long>("id", NpgsqlDbType.Bigint)
                {
                    TypedValue = commonSequence.Id
                },
                new NpgsqlParameter <byte>("notation", NpgsqlDbType.Smallint)
                {
                    TypedValue = (byte)commonSequence.Notation
                },
                new NpgsqlParameter <long>("matter_id", NpgsqlDbType.Bigint)
                {
                    TypedValue = commonSequence.MatterId
                },
                new NpgsqlParameter <long[]>("alphabet", NpgsqlDbType.Array | NpgsqlDbType.Bigint)
                {
                    TypedValue = alphabet
                },
                new NpgsqlParameter <int[]>("building", NpgsqlDbType.Array | NpgsqlDbType.Integer)
                {
                    TypedValue = building
                },
                new NpgsqlParameter <string>("remote_id", NpgsqlDbType.Varchar)
                {
                    TypedValue = commonSequence.RemoteId
                },
                new NpgsqlParameter("remote_db", NpgsqlDbType.Smallint)
                {
                    Value = (object)((byte?)commonSequence.RemoteDb) ?? DBNull.Value
                },
            };

            return(parameters);
        }
        /// <summary>
        /// The create DNA sequence.
        /// </summary>
        /// <param name="sequence">
        /// The common sequence.
        /// </param>
        /// <param name="fastaSequence">
        /// Sequence as <see cref="ISequence"/>>.
        /// </param>
        /// <param name="partial">
        /// The partial.
        /// </param>
        /// <exception cref="Exception">
        /// Thrown if at least one element of new sequence is missing in db
        /// or if sequence is empty or invalid.
        /// </exception>
        public void Create(CommonSequence sequence, ISequence fastaSequence, bool partial)
        {
            if (fastaSequence.ID.Contains("Resource temporarily unavailable"))
            {
                throw new Exception("Sequence is empty or invalid (probably ncbi is not responding).");
            }

            string stringSequence = fastaSequence.ConvertToString().ToUpper();

            var chain = new BaseChain(stringSequence);

            if (!ElementRepository.ElementsInDb(chain.Alphabet, sequence.Notation))
            {
                throw new Exception("At least one element of new sequence is invalid (not A, C, T, G or U).");
            }

            MatterRepository.CreateOrExtractExistingMatterForSequence(sequence);

            long[] alphabet = ElementRepository.ToDbElements(chain.Alphabet, sequence.Notation, false);
            Create(sequence, partial, alphabet, chain.Building);
        }
        /// <summary>
        /// The edit.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// The <see cref="System.Threading.Tasks.Task"/>.
        /// </returns>
        public async Task <ActionResult> Edit(long?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            using (var db = new LibiadaWebEntities())
            {
                CommonSequence commonSequence = await db.CommonSequence.FindAsync(id);

                if (commonSequence == null)
                {
                    return(HttpNotFound());
                }

                ViewBag.MatterId = new SelectList(Cache.GetInstance().Matters.ToArray(), "Id", "Name", commonSequence.MatterId);
                ViewBag.Notation = EnumHelper.GetSelectList(typeof(Notation), commonSequence.Notation);
                ViewBag.RemoteDb = EnumHelper.GetSelectList(typeof(RemoteDb), commonSequence.RemoteDb);
                return(View(commonSequence));
            }
        }
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <param name="sequenceStream">
        /// The sequence stream.
        /// </param>
        /// <exception cref="Exception">
        /// Thrown if congeneric tracks count not equals 1 (track is not monophonic).
        /// </exception>
        public void Create(CommonSequence sequence, Stream sequenceStream)
        {
            var stringSequence = FileHelper.ReadSequenceFromStream(sequenceStream);
            var doc = new XmlDocument();
            doc.LoadXml(stringSequence);

            MusicXmlParser parser = new MusicXmlParser();
            parser.Execute(doc, "test");
            ScoreTrack tempTrack = parser.ScoreModel;

            if (tempTrack.CongenericScoreTracks.Count != 1)
            {
                throw new Exception("Track contains more then one or zero congeneric score tracks (parts).");
            }

            var chain = ConvertCongenericScoreTrackToBaseChain(tempTrack.CongenericScoreTracks[0]);

            MatterRepository.CreateMatterFromSequence(sequence);

            var alphabet = ElementRepository.GetOrCreateNotesInDb(chain.Alphabet);
            Create(sequence, alphabet, chain.Building);
        }
        /// <summary>
        /// The insert.
        /// </summary>
        /// <param name="commonSequence">
        /// The sequence.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        public void Create(CommonSequence commonSequence, long[] alphabet, int[] building)
        {
            var parameters = FillParams(commonSequence, alphabet, building);

            const string Query = @"INSERT INTO music_chain (
                                        id,
                                        notation_id,
                                        matter_id,
                                        alphabet,
                                        building,
                                        remote_id,
                                        remote_db_id
                                    ) VALUES (
                                        @id,
                                        @notation_id,
                                        @matter_id,
                                        @alphabet,
                                        @building,
                                        @remote_id,
                                        @remote_db_id
                                    );";
            DbHelper.ExecuteCommand(Db, Query, parameters.ToArray());
        }
            /// <summary>
            /// Initializes a new instance of the <see cref="ImportResult"/> struct.
            /// </summary>
            /// <param name="sequence">
            /// The sequence.
            /// </param>
            /// <param name="language">
            /// The language.
            /// </param>
            /// <param name="original">
            /// The original.
            /// </param>
            /// <param name="translator">
            /// The translator.
            /// </param>
            /// <param name="partial">
            /// The partial.
            /// </param>
            /// <param name="precision">
            /// The precision.
            /// </param>
            public ImportResult(
                CommonSequence sequence,
                Language?language,
                bool?original,
                Translator?translator,
                bool?partial,
                double?precision)
            {
                Matter matter = sequence.Matter;

                Name         = matter.Name;
                Description  = matter.Description;
                Nature       = matter.Nature.GetDisplayValue();
                Notation     = sequence.Notation.GetDisplayValue();
                Group        = matter.Group.GetDisplayValue();
                SequenceType = matter.SequenceType.GetDisplayValue();
                RemoteId     = sequence.RemoteId;
                Language     = language?.GetDisplayValue();
                Original     = original;
                Translator   = translator?.GetDisplayValue();
                Partial      = partial;
                Precision    = precision;
            }
        /// <summary>
        /// The create DNA sequence.
        /// </summary>
        /// <param name="sequence">
        /// The common sequence.
        /// </param>
        /// <param name="fastaSequence">
        /// Sequence as <see cref="ISequence"/>>.
        /// </param>
        /// <param name="partial">
        /// The partial.
        /// </param>
        /// <exception cref="Exception">
        /// Thrown if at least one element of new sequence is missing in db
        /// or if sequence is empty or invalid.
        /// </exception>
        public void Create(CommonSequence sequence, ISequence fastaSequence, bool partial)
        {
            // TODO: fix it for batch import or remove fasta headers completely
            string fastaHeader = ">" + fastaSequence.ID;

            if (fastaHeader.Contains("Resource temporarily unavailable"))
            {
                throw new Exception("Sequence is empty or invalid (probably ncbi is not responding).");
            }

            string stringSequence = fastaSequence.ConvertToString().ToUpper();

            var chain = new BaseChain(stringSequence);

            if (!ElementRepository.ElementsInDb(chain.Alphabet, sequence.NotationId))
            {
                throw new Exception("At least one element of new sequence is invalid (not A, C, T, G or U).");
            }

            MatterRepository.CreateMatterFromSequence(sequence);

            var alphabet = ElementRepository.ToDbElements(chain.Alphabet, sequence.NotationId, false);
            Create(sequence, partial, alphabet, chain.Building);
        }
        /// <summary>
        /// Creates literature sequence in database.
        /// </summary>
        /// <param name="commonSequence">
        /// The common sequence.
        /// </param>
        /// <param name="sequenceStream">
        /// The sequence stream.
        /// </param>
        /// <param name="languageId">
        /// The language id.
        /// </param>
        /// <param name="original">
        /// The original.
        /// </param>
        /// <param name="translatorId">
        /// The translator id.
        /// </param>
        public void Create(CommonSequence commonSequence, Stream sequenceStream, int languageId, bool original, int? translatorId)
        {
            var stringSequence = FileHelper.ReadSequenceFromStream(sequenceStream);
            string[] text = stringSequence.Split('\n');
            for (int l = 0; l < text.Length - 1; l++)
            {
                // removing "\r"
                text[l] = text[l].Substring(0, text[l].Length - 1);
            }

            var chain = new BaseChain(text.Length - 1);

            // file always contains empty string at the end
            // TODO: rewrite this, add empty string check at the end or write a normal trim
            for (int i = 0; i < text.Length - 1; i++)
            {
                chain.Set(new ValueString(text[i]), i);
            }

            MatterRepository.CreateMatterFromSequence(commonSequence);

            var alphabet = ElementRepository.ToDbElements(chain.Alphabet, commonSequence.NotationId, true);
            Create(commonSequence, original, languageId, translatorId, alphabet, chain.Building);
        }
Exemplo n.º 25
0
        /// <summary>
        /// The insert.
        /// </summary>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        public void Create(CommonSequence sequence, long[] alphabet, int[] building)
        {
            var parameters = FillParams(sequence, alphabet, building);

            const string Query = @"INSERT INTO chain (
                                        id,
                                        notation,
                                        matter_id,
                                        alphabet,
                                        building,
                                        remote_id,
                                        remote_db
                                    ) VALUES (
                                        @id,
                                        @notation,
                                        @matter_id,
                                        @alphabet,
                                        @building,
                                        @remote_id,
                                        @remote_db
                                    );";

            Db.ExecuteCommand(Query, parameters.ToArray());
        }
Exemplo n.º 26
0
        public ActionResult Index(long matterId,
                                  Notation notation,
                                  Language?language,
                                  Translator?translator,
                                  PauseTreatment?pauseTreatment,
                                  bool?sequentialTransfer,
                                  int scrambling)
        {
            Matter matter = Cache.GetInstance().Matters.Single(m => m.Id == matterId);
            long   sequenceId;

            switch (matter.Nature)
            {
            case Nature.Literature:
                sequenceId = db.LiteratureSequence.Single(l => l.MatterId == matterId &&
                                                          l.Notation == notation &&
                                                          l.Language == language &&
                                                          l.Translator == translator).Id;
                break;

            case Nature.Music:
                sequenceId = db.MusicSequence.Single(m => m.MatterId == matterId &&
                                                     m.Notation == notation &&
                                                     m.PauseTreatment == pauseTreatment &&
                                                     m.SequentialTransfer == sequentialTransfer).Id;
                break;

            default:
                sequenceId = db.CommonSequence.Single(c => c.MatterId == matterId && c.Notation == notation).Id;
                break;
            }

            BaseChain chain = sequenceRepository.GetLibiadaBaseChain(sequenceId);

            for (int i = 0; i < scrambling; i++)
            {
                int firstIndex  = randomGenerator.Next(chain.Length);
                int secondIndex = randomGenerator.Next(chain.Length);

                IBaseObject firstElement  = chain[firstIndex];
                IBaseObject secondElement = chain[secondIndex];
                chain[firstIndex]  = secondElement;
                chain[secondIndex] = firstElement;
            }

            var resultMatter = new Matter
            {
                Nature = matter.Nature,
                Name   = $"{matter.Name} {scrambling} mixes"
            };
            MatterRepository matterRepository = new MatterRepository(db);

            matterRepository.SaveToDatabase(resultMatter);

            var result = new CommonSequence
            {
                Notation = notation,
                MatterId = resultMatter.Id
            };

            long[] alphabet = elementRepository.ToDbElements(chain.Alphabet, notation, false);

            switch (matter.Nature)
            {
            case Nature.Genetic:
                DnaSequence dnaSequence = db.DnaSequence.Single(c => c.Id == sequenceId);

                dnaSequenceRepository.Create(result, dnaSequence.Partial, alphabet, chain.Building);
                break;

            case Nature.Music:
                musicSequenceRepository.Create(result, alphabet, chain.Building);
                break;

            case Nature.Literature:
                LiteratureSequence sequence = db.LiteratureSequence.Single(c => c.Id == sequenceId);

                literatureSequenceRepository.Create(result, sequence.Original, sequence.Language, sequence.Translator, alphabet, chain.Building);
                break;

            case Nature.MeasurementData:
                dataSequenceRepository.Create(result, alphabet, chain.Building);
                break;

            default:
                throw new InvalidEnumArgumentException(nameof(matter.Nature), (int)matter.Nature, typeof(Nature));
            }

            return(RedirectToAction("Index", "Matters"));
        }
Exemplo n.º 27
0
        public ActionResult Create(
            [Bind(Include = "Id,Notation,RemoteDb,RemoteId,Description,Matter,MatterId")] CommonSequence commonSequence,
            bool localFile,
            Language?language,
            bool?original,
            Translator?translator,
            bool?partial,
            int?precision)
        {
            return(CreateTask(() =>
            {
                var db = new LibiadaWebEntities();
                try
                {
                    if (!ModelState.IsValid)
                    {
                        throw new Exception("Model state is invalid");
                    }

                    Stream sequenceStream;
                    Nature nature = commonSequence.Notation.GetNature();
                    if (nature == Nature.Genetic && !localFile)
                    {
                        sequenceStream = NcbiHelper.GetFastaFileStream(commonSequence.RemoteId);
                    }
                    else
                    {
                        sequenceStream = FileHelper.GetFileStream(Request.Files[0]);
                    }

                    switch (nature)
                    {
                    case Nature.Genetic:
                        ISequence bioSequence = NcbiHelper.GetFastaSequence(sequenceStream);
                        var dnaSequenceRepository = new GeneticSequenceRepository(db);
                        dnaSequenceRepository.Create(commonSequence, bioSequence, partial ?? false);
                        break;

                    case Nature.Music:
                        var musicSequenceRepository = new MusicSequenceRepository(db);
                        musicSequenceRepository.Create(commonSequence, sequenceStream);
                        break;

                    case Nature.Literature:
                        var literatureSequenceRepository = new LiteratureSequenceRepository(db);
                        literatureSequenceRepository.Create(commonSequence, sequenceStream, language ?? Language.Russian, original ?? true, translator ?? Translator.NoneOrManual);
                        break;

                    case Nature.MeasurementData:
                        var dataSequenceRepository = new DataSequenceRepository(db);
                        dataSequenceRepository.Create(commonSequence, sequenceStream, precision ?? 0);
                        break;

                    case Nature.Image:
                        var matterRepository = new MatterRepository(db);
                        int fileSize = Request.Files[0].ContentLength;
                        var file = new byte[fileSize];
                        Request.Files[0].InputStream.Read(file, 0, fileSize);
                        var matter = new Matter
                        {
                            Nature = Nature.Image,
                            SequenceType = commonSequence.Matter.SequenceType,
                            Name = commonSequence.Matter.Name,
                            Source = file,
                            Group = commonSequence.Matter.Group
                        };
                        matterRepository.SaveToDatabase(matter);
                        break;

                    default:
                        throw new InvalidEnumArgumentException(nameof(nature), (int)nature, typeof(Nature));
                    }
                    string multisequenceName = db.Multisequence.SingleOrDefault(ms => ms.Id == commonSequence.Matter.MultisequenceId).Name;
                    var result = new ImportResult(commonSequence, language, original, translator, partial, precision, multisequenceName);

                    return new Dictionary <string, string> {
                        { "data", JsonConvert.SerializeObject(result) }
                    };
                }
                catch (Exception)
                {
                    long matterId = commonSequence.MatterId;
                    if (matterId != 0)
                    {
                        List <Matter> orphanMatter = db.Matter
                                                     .Include(m => m.Sequence)
                                                     .Where(m => m.Id == matterId && m.Sequence.Count == 0)
                                                     .ToList();

                        if (orphanMatter.Count > 0)
                        {
                            db.Matter.Remove(orphanMatter[0]);
                            db.SaveChanges();
                        }
                    }

                    throw;
                }
                finally
                {
                    Dispose(true);
                }
            }));
        }
        /// <summary>
        /// The insert.
        /// </summary>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <param name="fastaHeader">
        /// The fasta header.
        /// </param>
        /// <param name="partial">
        /// The partial.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        public void Create(CommonSequence sequence, bool partial, long[] alphabet, int[] building)
        {
            var parameters = FillParams(sequence, alphabet, building);

            parameters.Add(new NpgsqlParameter
            {
                ParameterName = "partial",
                NpgsqlDbType = NpgsqlDbType.Boolean,
                Value = partial
            });

            const string Query = @"INSERT INTO dna_chain (
                                        id,
                                        notation_id,
                                        matter_id,
                                        alphabet,
                                        building,
                                        remote_id,
                                        remote_db_id,
                                        partial
                                    ) VALUES (
                                        @id,
                                        @notation_id,
                                        @matter_id,
                                        @alphabet,
                                        @building,
                                        @remote_id,
                                        @remote_db_id,
                                        @partial
                                    );";

            DbHelper.ExecuteCommand(Db, Query, parameters.ToArray());
        }
        /// <summary>
        /// The index.
        /// </summary>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        public ActionResult Index()
        {
            using (var db = new LibiadaWebEntities())
            {
                var           matterRepository         = new MatterRepository(db);
                var           dnaSequenceRepository    = new GeneticSequenceRepository(db);
                var           commonSequenceRepository = new CommonSequenceRepository(db);
                var           elementRepository        = new ElementRepository(db);
                var           matterIds = new long[] { 1332, 1333, 1339, 1330, 1337, 1342, 1331, 1338, 1340, 1943, 1945, 1334 };
                DnaSequence[] sequences = db.DnaSequence.Include(d => d.Matter).Where(d => matterIds.Contains(d.MatterId)).ToArray();

                for (int i = 0; i < sequences.Length; i++)
                {
                    var newMatter = new Matter
                    {
                        Name         = $"{sequences[i].Matter.Name} Cleaned of IS110",
                        Description  = sequences[i].Matter.Description,
                        Nature       = sequences[i].Matter.Nature,
                        Group        = sequences[i].Matter.Group,
                        SequenceType = sequences[i].Matter.SequenceType
                    };

                    var newSequence = new CommonSequence
                    {
                        Notation    = sequences[i].Notation,
                        Matter      = newMatter,
                        Description = sequences[i].Description,
                        RemoteDb    = sequences[i].RemoteDb,
                        RemoteId    = sequences[i].RemoteId
                    };
                    var chain = commonSequenceRepository.GetLibiadaChain(sequences[i].Id);

                    matterRepository.CreateOrExtractExistingMatterForSequence(newSequence);
                    dnaSequenceRepository.Create(newSequence, false, elementRepository.ToDbElements(chain.Alphabet, Notation.Nucleotides, false), chain.Building);
                    var sequenceId              = sequences[i].Id;
                    var subsequences            = db.Subsequence.Include(s => s.Position).Include(s => s.SequenceAttribute).Where(s => s.SequenceId == sequenceId).ToList();
                    var subsequenceIds          = subsequences.Select(s => s.Id);
                    var subsequencesIdsToRemove = db.SequenceAttribute
                                                  .Where(sa => subsequenceIds.Contains(sa.SequenceId) && sa.Value.Contains("IS110"))
                                                  .Select(sa => sa.SequenceId)
                                                  .Distinct()
                                                  .ToArray();

                    subsequences.RemoveAll(s => subsequencesIdsToRemove.Contains(s.Id));

                    var newSubsequences       = new Subsequence[subsequences.Count];
                    var newSequenceAttributes = new List <SequenceAttribute>();
                    var newPositions          = new List <Position>();
                    for (int j = 0; j < subsequences.Count; j++)
                    {
                        newSubsequences[j] = new Subsequence
                        {
                            Id         = db.GetNewElementId(),
                            Feature    = subsequences[j].Feature,
                            SequenceId = newSequence.Id,
                            Start      = subsequences[j].Start,
                            Length     = subsequences[j].Length,
                            RemoteId   = subsequences[j].RemoteId,
                            Partial    = subsequences[j].Partial
                        };

                        foreach (SequenceAttribute subsequenceAttribute in subsequences[j].SequenceAttribute.ToArray())
                        {
                            newSequenceAttributes.Add(new SequenceAttribute
                            {
                                SequenceId = newSubsequences[j].Id,
                                Attribute  = subsequenceAttribute.Attribute,
                                Value      = subsequenceAttribute.Value
                            });
                        }

                        foreach (Position position in subsequences[j].Position.ToArray())
                        {
                            newPositions.Add(new Position
                            {
                                SubsequenceId = newSubsequences[j].Id,
                                Length        = position.Length,
                                Start         = position.Start
                            });
                        }
                    }

                    db.Subsequence.AddRange(newSubsequences);
                    db.SequenceAttribute.AddRange(newSequenceAttributes);
                    db.Position.AddRange(newPositions);
                    db.SaveChanges();
                }
            }

            return(View());
        }
        public ActionResult Index(
            string searchQuery,
            bool importGenes,
            bool importPartial,
            bool filterMinLength,
            int minLength,
            bool filterMaxLength,
            int maxLength)
        {
            return(CreateTask(() =>
            {
                string searchResults;
                string[] accessions;
                List <NuccoreObject> nuccoreObjects;

                if (filterMinLength)
                {
                    searchResults = filterMaxLength ?
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery, minLength, maxLength: maxLength) :
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery, minLength);
                }
                else
                {
                    searchResults = filterMaxLength ?
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery, minLength: 1, maxLength: maxLength) :
                                    NcbiHelper.FormatNcbiSearchTerm(searchQuery);
                }
                nuccoreObjects = NcbiHelper.ExecuteESummaryRequest(searchResults, importPartial);
                accessions = nuccoreObjects.Select(no => no.AccessionVersion.Split('.')[0]).Distinct().ToArray();
                var importResults = new List <MatterImportResult>(accessions.Length);

                using (var db = new LibiadaWebEntities())
                {
                    var matterRepository = new MatterRepository(db);
                    var dnaSequenceRepository = new GeneticSequenceRepository(db);

                    var(existingAccessions, accessionsToImport) = dnaSequenceRepository.SplitAccessionsIntoExistingAndNotImported(accessions);

                    importResults.AddRange(existingAccessions.ConvertAll(existingAccession => new MatterImportResult
                    {
                        MatterName = existingAccession,
                        Result = "Sequence already exists",
                        Status = "Exists"
                    }));

                    foreach (string accession in accessionsToImport)
                    {
                        var importResult = new MatterImportResult()
                        {
                            MatterName = accession
                        };

                        try
                        {
                            ISequence bioSequence = NcbiHelper.DownloadGenBankSequence(accession);
                            GenBankMetadata metadata = NcbiHelper.GetMetadata(bioSequence);
                            importResult.MatterName = metadata.Version.CompoundAccession;

                            Matter matter = matterRepository.CreateMatterFromGenBankMetadata(metadata);

                            importResult.SequenceType = matter.SequenceType.GetDisplayValue();
                            importResult.Group = matter.Group.GetDisplayValue();
                            importResult.MatterName = matter.Name;
                            importResult.AllNames = $"Common name = {metadata.Source.CommonName}, "
                                                    + $"Species = {metadata.Source.Organism.Species}, "
                                                    + $"Definition = {metadata.Definition}, "
                                                    + $"Saved matter name = {importResult.MatterName}";

                            var sequence = new CommonSequence
                            {
                                Matter = matter,
                                Notation = Notation.Nucleotides,
                                RemoteDb = RemoteDb.GenBank,
                                RemoteId = metadata.Version.CompoundAccession
                            };
                            bool partial = metadata.Definition.ToLower().Contains("partial");
                            dnaSequenceRepository.Create(sequence, bioSequence, partial);

                            (importResult.Result, importResult.Status) = importGenes ?
                                                                         ImportFeatures(metadata, sequence) :
                                                                         ("Successfully imported sequence", "Success");
                        }
                        catch (Exception exception)
                        {
                            importResult.Status = "Error";
                            importResult.Result = $"Error: {exception.Message}";
                            while (exception.InnerException != null)
                            {
                                exception = exception.InnerException;
                                importResult.Result += $" {exception.Message}";
                            }

                            foreach (var dbEntityEntry in db.ChangeTracker.Entries())
                            {
                                if (dbEntityEntry.Entity != null)
                                {
                                    dbEntityEntry.State = EntityState.Detached;
                                }
                            }
                        }
                        finally
                        {
                            importResults.Add(importResult);
                        }
                    }

                    string[] names = importResults.Select(r => r.MatterName).ToArray();

                    // removing matters for which adding of sequence failed
                    Matter[] orphanMatters = db.Matter
                                             .Include(m => m.Sequence)
                                             .Where(m => names.Contains(m.Name) && m.Sequence.Count == 0)
                                             .ToArray();

                    if (orphanMatters.Length > 0)
                    {
                        db.Matter.RemoveRange(orphanMatters);
                        db.SaveChanges();
                    }
                }

                var result = new Dictionary <string, object> {
                    { "result", importResults }
                };

                return new Dictionary <string, string> {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
        /// <summary>
        /// The insert.
        /// </summary>
        /// <param name="sequence">
        /// The sequence.
        /// </param>
        /// <param name="original">
        /// The original.
        /// </param>
        /// <param name="languageId">
        /// The language id.
        /// </param>
        /// <param name="translatorId">
        /// The translator id.
        /// </param>
        /// <param name="alphabet">
        /// The alphabet.
        /// </param>
        /// <param name="building">
        /// The building.
        /// </param>
        public void Create(CommonSequence sequence, bool original, int languageId, int? translatorId, long[] alphabet, int[] building)
        {
            var parameters = FillParams(sequence, alphabet, building);

            parameters.Add(new NpgsqlParameter
            {
                ParameterName = "original",
                NpgsqlDbType = NpgsqlDbType.Boolean,
                Value = original
            });
            parameters.Add(new NpgsqlParameter
            {
                ParameterName = "language_id",
                NpgsqlDbType = NpgsqlDbType.Integer,
                Value = languageId
            });

            parameters.Add(new NpgsqlParameter
            {
                ParameterName = "translator_id",
                NpgsqlDbType = NpgsqlDbType.Integer,
                Value = (object)translatorId ?? DBNull.Value
            });

            const string Query = @"INSERT INTO literature_chain (
                                        id,
                                        notation_id,
                                        matter_id,
                                        alphabet,
                                        building,
                                        remote_id,
                                        remote_db_id,
                                        original,
                                        language_id,
                                        translator_id
                                    ) VALUES (
                                        @id,
                                        @notation_id,
                                        @matter_id,
                                        @alphabet,
                                        @building,
                                        @remote_id,
                                        @remote_db_id,
                                        @original,
                                        @language_id,
                                        @translator_id
                                    );";

            DbHelper.ExecuteCommand(Db, Query, parameters.ToArray());
        }
        public ActionResult Index(string[] accessions, bool importGenes)
        {
            return Action(() =>
            {
                var matterNames = new string[accessions.Length];
                var savedMatterNames = new string[accessions.Length];
                var results = new string[accessions.Length];
                var statuses = new string[accessions.Length];

                using (var db = new LibiadaWebEntities())
                {
                    var existingAccessions = db.DnaSequence.Select(d => d.RemoteId).Distinct().ToArray();
                    var dnaSequenceRepository = new DnaSequenceRepository(db);
                    var bioSequences = NcbiHelper.GetGenBankSequences(accessions);

                    for (int i = 0; i < accessions.Length; i++)
                    {
                        string accession = accessions[i];
                        matterNames[i] = accession;
                        if (existingAccessions.Contains(accession) || existingAccessions.Contains(accession + ".1"))
                        {
                            results[i] = "Sequence already exists";
                            statuses[i] = "Exist";
                            continue;
                        }

                        try
                        {
                            var metadata = NcbiHelper.GetMetadata(bioSequences[i]);
                            if (existingAccessions.Contains(metadata.Version.CompoundAccession))
                            {
                                results[i] = "Sequence already exists";
                                statuses[i] = "Exist";
                                continue;
                            }

                            savedMatterNames[i] = NcbiHelper.ExtractSequenceName(metadata) + " | " + metadata.Version.CompoundAccession;
                            matterNames[i] = "Common name=" + metadata.Source.CommonName +
                                             ", Species=" + metadata.Source.Organism.Species +
                                             ", Definition=" + metadata.Definition +
                                             ", Saved matter name=" + savedMatterNames[i];

                            var matter = new Matter
                                             {
                                                 Name = savedMatterNames[i],
                                                 Nature = Nature.Genetic,
                                                 Group = GroupRepository.ExtractSequenceGroup(savedMatterNames[i]),
                                                 SequenceType = SequenceTypeRepsitory.ExtractSequenceGroup(savedMatterNames[i])
                                             };

                            var sequence = new CommonSequence
                                               {
                                                   Matter = matter,
                                                   NotationId = Aliases.Notation.Nucleotide,
                                                   RemoteDbId = Aliases.RemoteDb.RemoteDbNcbi,
                                                   RemoteId = metadata.Version.CompoundAccession
                                               };

                            dnaSequenceRepository.Create(sequence, bioSequences[i], metadata.Definition.ToLower().Contains("partial"));
                            if (importGenes)
                            {
                                try
                                {
                                    using (var subsequenceImporter = new SubsequenceImporter(metadata.Features.All, sequence.Id))
                                    {
                                        subsequenceImporter.CreateSubsequences();
                                    }

                                    var nonCodingCount = db.Subsequence.Count(s => s.SequenceId == sequence.Id && s.FeatureId == Aliases.Feature.NonCodingSequence);
                                    var featuresCount = db.Subsequence.Count(s => s.SequenceId == sequence.Id && s.FeatureId != Aliases.Feature.NonCodingSequence);

                                    statuses[i] = "Success";
                                    results[i] = "Successfully imported  sequence and " + featuresCount + " features and " + nonCodingCount + " non coding subsequences";
                                }
                                catch (Exception exception)
                                {
                                    results[i] = "successfully imported sequence but failed to import genes: " + exception.Message;
                                    statuses[i] = "Error";

                                    if (exception.InnerException != null)
                                    {
                                        results[i] += " " + exception.InnerException.Message;
                                    }
                                }
                            }
                            else
                            {
                                results[i] = "successfully imported sequence";
                                statuses[i] = "Success";
                            }
                        }
                        catch (Exception exception)
                        {
                            results[i] = "Error:" + exception.Message + (exception.InnerException == null ? string.Empty : exception.InnerException.Message);
                            statuses[i] = "Error";
                        }
                    }

                    // removing matters for whitch adding of sequence failed
                    var orphanMatters = db.Matter.Include(m => m.Sequence).Where(m => savedMatterNames.Contains(m.Name) && m.Sequence.Count == 0).ToArray();

                    if (orphanMatters.Length > 0)
                    {
                        db.Matter.RemoveRange(orphanMatters);
                        db.SaveChanges();
                    }
                }

                return new Dictionary<string, object>
                           {
                               { "matterNames", matterNames },
                               { "results", results },
                               { "status", statuses }
                           };
            });
        }
Exemplo n.º 33
0
        public ActionResult Index(HttpPostedFileBase[] files)
        {
            return(CreateTask(() =>
            {
                var importResults = new List <MatterImportResult>();

                using (var db = new LibiadaWebEntities())
                {
                    Matter[] matters = Cache.GetInstance().Matters.Where(m => m.Nature == Nature.Music).ToArray();

                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        string sequenceName = Request.Files[i].FileName.Substring(0, Request.Files[i].FileName.LastIndexOf('.'));

                        var importResult = new MatterImportResult()
                        {
                            MatterName = sequenceName
                        };

                        try
                        {
                            var sequence = new CommonSequence();

                            if (matters.Any(m => m.Name == sequenceName))
                            {
                                sequence.MatterId = matters.Single(m => m.Name == sequenceName).Id;
                                importResult.Result = "Successfully imported music for existing matter";
                            }
                            else
                            {
                                sequence.Matter = new Matter
                                {
                                    Name = sequenceName,
                                    Group = Group.ClassicalMusic,
                                    Nature = Nature.Music,
                                    SequenceType = SequenceType.CompleteMusicalComposition
                                };

                                importResult.Result = "Successfully imported music and created matter";
                            }

                            var repository = new MusicSequenceRepository(db);

                            repository.Create(sequence, Request.Files[i].InputStream);
                            importResult.Status = "Success";
                            importResults.Add(importResult);
                        }
                        catch (Exception exception)
                        {
                            importResult.Result = $"Failed to import music: {exception.Message}";
                            while (exception.InnerException != null)
                            {
                                importResult.Result += $" {exception.InnerException.Message}";

                                exception = exception.InnerException;
                            }

                            importResult.Status = "Error";
                            importResults.Add(importResult);
                        }
                    }

                    var result = new Dictionary <string, object> {
                        { "result", importResults }
                    };

                    return new Dictionary <string, string> {
                        { "data", JsonConvert.SerializeObject(result) }
                    };
                }
            }));
        }
Exemplo n.º 34
0
        public ActionResult Index(Notation notation, bool dropPunctuation)
        {
            return(CreateTask(() =>
            {
                var importResults = new List <MatterImportResult>();

                using (var db = new LibiadaWebEntities())
                {
                    Matter[] matters = db.Matter.Where(m => m.Nature == Nature.Literature).ToArray();

                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        string sequenceName = Request.Files[i].FileName.Substring(0, Request.Files[i].FileName.LastIndexOf('.'));

                        var importResult = new MatterImportResult()
                        {
                            MatterName = sequenceName
                        };


                        try
                        {
                            var sequence = new CommonSequence
                            {
                                Notation = notation
                            };


                            if (matters.Any(m => m.Name == sequenceName))
                            {
                                sequence.MatterId = matters.Single(m => m.Name == sequenceName).Id;
                                importResult.Result = "Successfully imported poem for existing matter";
                            }
                            else
                            {
                                sequence.Matter = new Matter
                                {
                                    Name = sequenceName,
                                    Group = Group.ClassicalLiterature,
                                    Nature = Nature.Literature,
                                    SequenceType = SequenceType.CompleteText
                                };

                                importResult.Result = "Successfully imported poem and created matter";
                            }

                            var repository = new LiteratureSequenceRepository(db);

                            repository.Create(sequence, Request.Files[i].InputStream, Language.Russian, true, Translator.NoneOrManual, dropPunctuation);
                            importResult.Status = "Success";
                            importResults.Add(importResult);
                        }
                        catch (Exception exception)
                        {
                            importResult.Result = $"Failed to import poem: {exception.Message}";
                            while (exception.InnerException != null)
                            {
                                importResult.Result += $" {exception.InnerException.Message}";

                                exception = exception.InnerException;
                            }

                            importResult.Status = "Error";
                            importResults.Add(importResult);
                        }
                    }

                    var data = new Dictionary <string, object> {
                        { "result", importResults }
                    };

                    return new Dictionary <string, object>
                    {
                        { "data", JsonConvert.SerializeObject(data) }
                    };
                }
            }));
        }