/// <summary>
        /// Reorganizes <see cref="AbstractChain"/> into <see cref="AbstractChain"/>.
        /// </summary>
        /// <param name="source">
        /// Source chain.
        /// </param>
        /// <returns>
        /// The <see cref="AbstractChain"/>.
        /// </returns>
        public override AbstractChain Reorganize(AbstractChain source)
        {
            var result = new BaseChain();
            result.ClearAndSetNewLength(source.GetLength() / blockSize);
            IteratorBase iteratorFrom;
            IWritableIterator iteratorTo;

            if (link != Link.End)
            {
                iteratorFrom = new IteratorStart(source, blockSize, blockSize);
                iteratorTo = new IteratorWritableStart(result);
            }
            else
            {
                iteratorFrom = new IteratorEnd(source, blockSize, blockSize);
                iteratorTo = new IteratorWritableEnd(result);
            }

            while (iteratorTo.Next() && iteratorFrom.Next())
            {
                iteratorTo.WriteValue(iteratorFrom.Current());
            }

            return result;
        }
예제 #2
0
        /// <summary>
        /// Saves measures to db.
        /// </summary>
        /// <param name="measure">
        /// The measure.
        /// </param>
        /// <returns>
        /// The <see cref="long"/>.
        /// </returns>
        public long CreateMeasure(Measure measure)
        {
            var measureChain = new BaseChain(measure.NoteList.Cast <IBaseObject>().ToList());

            long[] notes = new ElementRepository(db).GetOrCreateNotesInDb(measureChain.Alphabet);

            string localMeasureHash = measure.GetHashCode().ToString();
            var    dbMeasures       = db.Measure.Where(m => m.Value == localMeasureHash).ToList();

            if (dbMeasures.Count > 0)
            {
                foreach (var dbMeasure in dbMeasures)
                {
                    long[] dbAlphabet = db.GetMeasureAlphabet(dbMeasure.Id);
                    if (notes.SequenceEqual(dbAlphabet))
                    {
                        int[] dbBuilding = db.GetMeasureBuilding(dbMeasure.Id);
                        if (measureChain.Building.SequenceEqual(dbBuilding))
                        {
                            if (measure.Attributes.Key.Fifths != dbMeasure.Fifths ||
                                measure.Attributes.Size.BeatBase != dbMeasure.Beatbase ||
                                measure.Attributes.Size.Beats != dbMeasure.Beats)
                            {
                                throw new Exception("Found in db measure is not equal to local measure.");
                            }

                            return(dbMeasure.Id);
                        }
                    }
                }
            }

            return(Create(measure, notes, measureChain.Building));
        }
예제 #3
0
        /// <summary>
        /// Saves Fmotifs to db.
        /// </summary>
        /// <param name="fmotif">
        /// The Fmotif.
        /// </param>
        /// <returns>
        /// The <see cref="long"/>.
        /// </returns>
        public long CreateFmotif(Fmotif fmotif)
        {
            var fmotifChain = new BaseChain(fmotif.NoteList.Cast <IBaseObject>().ToList());

            long[] notes = new ElementRepository(db).GetOrCreateNotesInDb(fmotifChain.Alphabet);

            var localFmotifHash = fmotif.GetHashCode().ToString();
            var dbFmotifs       = db.Fmotif.Where(f => f.Value == localFmotifHash).ToList();

            if (dbFmotifs.Count > 0)
            {
                foreach (var dbFmotif in dbFmotifs)
                {
                    long[] dbAlphabet = db.GetFmotifAlphabet(dbFmotif.Id);
                    if (notes.SequenceEqual(dbAlphabet))
                    {
                        int[] dbBuilding = db.GetFmotifBuilding(dbFmotif.Id);
                        if (fmotifChain.Building.SequenceEqual(dbBuilding))
                        {
                            if (fmotif.Type != dbFmotif.FmotifType)
                            {
                                throw new Exception("Found in db fmotif is not equal to local fmotif.");
                            }

                            return(dbFmotif.Id);
                        }
                    }
                }
            }

            return(Create(fmotif, notes, fmotifChain.Building));
        }
예제 #4
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);
        }
예제 #5
0
        public ActionResult Index(IEnumerable <long> matterIds, string transformType)
        {
            Notation notation = transformType.Equals("toAmino") ? Notation.AminoAcids : Notation.Triplets;

            foreach (var matterId in matterIds)
            {
                var   sequenceId  = db.CommonSequence.Single(c => c.MatterId == matterId && c.Notation == Notation.Nucleotides).Id;
                Chain sourceChain = commonSequenceRepository.GetLibiadaChain(sequenceId);

                BaseChain transformedChain = transformType.Equals("toAmino")
                                                 ? DnaTransformer.EncodeAmino(sourceChain)
                                                 : DnaTransformer.EncodeTriplets(sourceChain);

                var result = new DnaSequence
                {
                    MatterId = matterId,
                    Notation = notation
                };

                long[] alphabet = elementRepository.ToDbElements(transformedChain.Alphabet, notation, false);
                dnaSequenceRepository.Insert(result, alphabet, transformedChain.Building);
            }

            return(RedirectToAction("Index", "CommonSequences"));
        }
        /// <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>
        /// Reorganizes <see cref="AbstractChain"/> into <see cref="AbstractChain"/>.
        /// </summary>
        /// <param name="source">
        /// Source chain.
        /// </param>
        /// <returns>
        /// The <see cref="AbstractChain"/>.
        /// </returns>
        public override AbstractChain Reorganize(AbstractChain source)
        {
            var resent = new BaseChain(source.GetLength());
            for (int i = 0; i < source.GetLength(); i++)
            {
                var message = source[i] as ValuePhantom ?? new ValuePhantom { source[i] };

                resent.Set(message, i);
            }

            return resent;
        }
        public static void Process(BaseChain chain, Node node, IncomingMessage message)
        {
            if (message.Message.Command != "headers")
            {
                return;
            }

            NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

            HeadersPayload payload = (HeadersPayload)message.Message.Payload;

            _logger.Debug("Processing Headers Message: {0}", payload.Headers.ToString());
        }
        /// <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);
            }
        }
예제 #10
0
        public virtual void OnTalk(PlayerMobile player)
        {
            if (QuestHelper.DeliveryArrived(player, this))
            {
                return;
            }

            if (QuestHelper.InProgress(player, this))
            {
                return;
            }

            if (QuestHelper.QuestLimitReached(player))
            {
                return;
            }

            // check if this quester can offer any quest chain (already started)
            foreach (KeyValuePair <QuestChain, BaseChain> pair in player.Chains)
            {
                BaseChain chain = pair.Value;

                if (chain != null && chain.Quester != null && chain.Quester == GetType())
                {
                    BaseQuest quest = QuestHelper.RandomQuest(player, new Type[] { chain.CurrentQuest }, this);

                    if (quest != null)
                    {
                        player.CloseGump(typeof(MondainQuestGump));
                        player.SendGump(new MondainQuestGump(quest));
                        return;
                    }
                }
            }

            BaseQuest questt = QuestHelper.RandomQuest(player, Quests, this);

            if (questt != null)
            {
                player.CloseGump(typeof(MondainQuestGump));
                player.SendGump(new MondainQuestGump(questt));
            }
        }
        /// <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);
        }
        public static void Process(BaseChain chain, Node node, IncomingMessage message)
        {
            if (message.Message.Command != "addr")
            {
                return;
            }

            NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
            AddrPayload payload = (AddrPayload)message.Message.Payload;

            foreach (NetworkAddress address in payload.Addresses)
            {
                AddNodeCommand command = new AddNodeCommand
                {
                    Chain   = chain.ChainName,
                    Address = address.Endpoint.Address.ToString(),
                    Port    = address.Endpoint.Port,
                };
                chain.SendCommand(command).GetAwaiter().GetResult();
            }
        }
        /// <summary>
        /// Translates dna sequence into triplet sequence.
        /// </summary>
        /// <param name="inputChain">
        /// Nucleotide sequence.
        /// </param>
        /// <returns>
        /// Triplet sequence of <see cref="BaseChain"/> type.
        /// Elements are of <see cref="ValueString"/> type.
        /// </returns>
        public static BaseChain EncodeTriplets(BaseChain inputChain)
        {
            DnaProcessor.CheckDnaAlphabet(inputChain.Alphabet);

            var resultLength = (int)Math.Floor((double)inputChain.GetLength() / 3);
            var resultChain = new BaseChain(resultLength);

            for (int i = 0; i < resultLength * 3; i += 3)
            {
                resultChain[i / 3] = new ValueString(inputChain[i].ToString() + inputChain[i + 1] + inputChain[i + 2]);
            }

            return resultChain;
        }
        /// <summary>
        /// Translates amino acid sequences into phantom sequences.
        /// </summary>
        /// <param name="inputChain">
        /// Amino acid sequence.
        /// </param>
        /// <returns>
        /// Phantom sequence of <see cref="BaseChain"/> type.
        /// Elements are <see cref="ValuePhantom"/>.
        /// </returns>
        public static BaseChain Decode(BaseChain inputChain)
        {
            var resultChain = new BaseChain(inputChain.GetLength());
            for (int i = 0; i < inputChain.GetLength(); i++)
            {
                string aminoAcid = inputChain[i].ToString();
                var element = new ValuePhantom();
                switch (aminoAcid)
                {
                    case "F":
                        element.Add(new ValueString("TTT"));
                        element.Add(new ValueString("TTC"));
                        break;
                    case "L":
                        element.Add(new ValueString("TTA"));
                        element.Add(new ValueString("TTG"));
                        element.Add(new ValueString("CTT"));
                        element.Add(new ValueString("CTC"));
                        element.Add(new ValueString("CTA"));
                        element.Add(new ValueString("CTG"));
                        break;
                    case "S":
                        element.Add(new ValueString("TCT"));
                        element.Add(new ValueString("TCC"));
                        element.Add(new ValueString("TCA"));
                        element.Add(new ValueString("TCG"));
                        element.Add(new ValueString("AGT"));
                        element.Add(new ValueString("AGC"));
                        break;
                    case "Y":
                        element.Add(new ValueString("TAT"));
                        element.Add(new ValueString("TAC"));
                        break;
                    case "X":
                        element.Add(new ValueString("TAA"));
                        element.Add(new ValueString("TAG"));
                        element.Add(new ValueString("TGA"));
                        break;
                    case "C":
                        element.Add(new ValueString("TGT"));
                        element.Add(new ValueString("TGC"));
                        break;
                    case "W":
                        element.Add(new ValueString("TGG"));
                        break;
                    case "P":
                        element.Add(new ValueString("CCT"));
                        element.Add(new ValueString("CCC"));
                        element.Add(new ValueString("CCA"));
                        element.Add(new ValueString("CCG"));
                        break;
                    case "H":
                        element.Add(new ValueString("CAT"));
                        element.Add(new ValueString("CAC"));
                        break;
                    case "Q":
                        element.Add(new ValueString("CAA"));
                        element.Add(new ValueString("CAG"));
                        break;
                    case "R":
                        element.Add(new ValueString("CGT"));
                        element.Add(new ValueString("CGC"));
                        element.Add(new ValueString("CGA"));
                        element.Add(new ValueString("CGG"));
                        element.Add(new ValueString("AGA"));
                        element.Add(new ValueString("AGG"));
                        break;
                    case "I":
                        element.Add(new ValueString("ATT"));
                        element.Add(new ValueString("ATC"));
                        element.Add(new ValueString("ATA"));
                        break;
                    case "M":
                        element.Add(new ValueString("ATG"));
                        break;
                    case "T":
                        element.Add(new ValueString("ACT"));
                        element.Add(new ValueString("ACC"));
                        element.Add(new ValueString("ACA"));
                        element.Add(new ValueString("ACG"));
                        break;
                    case "N":
                        element.Add(new ValueString("AAT"));
                        element.Add(new ValueString("AAC"));
                        break;
                    case "K":
                        element.Add(new ValueString("AAA"));
                        element.Add(new ValueString("AAG"));
                        break;
                    case "V":
                        element.Add(new ValueString("GTT"));
                        element.Add(new ValueString("GTC"));
                        element.Add(new ValueString("GTA"));
                        element.Add(new ValueString("GTG"));
                        break;
                    case "A":
                        element.Add(new ValueString("GCT"));
                        element.Add(new ValueString("GCC"));
                        element.Add(new ValueString("GCA"));
                        element.Add(new ValueString("GCG"));
                        break;
                    case "D":
                        element.Add(new ValueString("GAT"));
                        element.Add(new ValueString("GAC"));
                        break;
                    case "E":
                        element.Add(new ValueString("GAA"));
                        element.Add(new ValueString("GAG"));
                        break;
                    case "G":
                        element.Add(new ValueString("GGT"));
                        element.Add(new ValueString("GGC"));
                        element.Add(new ValueString("GGA"));
                        element.Add(new ValueString("GGG"));
                        break;
                    default:
                        throw new ArgumentException("Unknown amino acid");
                }

                resultChain[i] = element;
            }

            return resultChain;
        }
        /// <summary>
        /// Translates DNA sequence into amino acids.
        /// </summary>
        /// <param name="inputChain">
        /// DNA sequence.
        /// </param>
        /// <returns>
        /// Amino acid sequence of type <see cref="BaseChain"/>.
        /// Elements are of <see cref="ValueString"/> type.
        /// </returns>
        public static BaseChain EncodeAmino(BaseChain inputChain)
        {
            DnaProcessor.CheckDnaAlphabet(inputChain.Alphabet);

            var count = (int)Math.Floor((double)inputChain.GetLength() / 3);
            var outChain = new BaseChain(count);
            for (int i = 0; i < count * 3; i += 3)
            {
                string first = inputChain[i].ToString();
                string second = inputChain[i + 1].ToString();
                string third = inputChain[i + 2].ToString();
                switch (first)
                {
                    case "T":
                        switch (second)
                        {
                            case "T":
                                if ((third == "T") || (third == "C"))
                                {
                                    outChain[i / 3] = new ValueString('F');
                                }
                                else
                                {
                                    if ((third == "A") || (third == "G"))
                                    {
                                        outChain[i / 3] = new ValueString('L');
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                break;
                            case "C":
                                outChain[i / 3] = new ValueString('S');
                                break;
                            case "A":
                                if ((third == "T") || (third == "C"))
                                {
                                    outChain[i / 3] = new ValueString('Y');
                                }
                                else
                                {
                                    if ((third == "A") || (third == "G"))
                                    {
                                        outChain[i / 3] = new ValueString('X');
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                break;
                            case "G":
                                if ((third == "T") || (third == "C"))
                                {
                                    outChain[i / 3] = new ValueString('C');
                                }
                                else
                                {
                                    if (third == "A")
                                    {
                                        outChain[i / 3] = new ValueString('X');
                                    }
                                    else
                                    {
                                        if (third == "G")
                                        {
                                            outChain[i / 3] = new ValueString('W');
                                        }
                                        else
                                        {
                                            throw new Exception();
                                        }
                                    }
                                }

                                break;
                            default:
                                throw new Exception();
                        }

                        break;
                    case "C":
                        switch (second)
                        {
                            case "T":
                                outChain[i / 3] = new ValueString('L');
                                break;
                            case "C":
                                outChain[i / 3] = new ValueString('P');
                                break;
                            case "A":
                                if ((third == "T") || (third == "C"))
                                {
                                    outChain[i / 3] = new ValueString('H');
                                }
                                else
                                {
                                    if ((third == "A") || (third == "G"))
                                    {
                                        outChain[i / 3] = new ValueString('Q');
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                break;
                            case "G":
                                outChain[i / 3] = new ValueString('R');
                                break;
                            default:
                                throw new Exception();
                        }

                        break;
                    case "A":
                        switch (second)
                        {
                            case "T":
                                if ((third == "T") || (third == "C") || (third == "A"))
                                {
                                    outChain[i / 3] = new ValueString('I');
                                }
                                else
                                {
                                    if (third == "G")
                                    {
                                        outChain[i / 3] = new ValueString('M');
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                break;
                            case "C":
                                outChain[i / 3] = new ValueString('T');
                                break;
                            case "A":
                                if ((third == "T") || (third == "C"))
                                {
                                    outChain[i / 3] = new ValueString('N');
                                }
                                else
                                {
                                    if ((third == "A") || (third == "G"))
                                    {
                                        outChain[i / 3] = new ValueString('K');
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                break;
                            case "G":
                                if ((third == "T") || (third == "C"))
                                {
                                    outChain[i / 3] = new ValueString('S');
                                }
                                else
                                {
                                    if ((third == "A") || (third == "G"))
                                    {
                                        outChain[i / 3] = new ValueString('R');
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                break;
                            default:
                                throw new Exception();
                        }

                        break;
                    case "G":
                        switch (second)
                        {
                            case "T":
                                outChain[i / 3] = new ValueString('V');
                                break;
                            case "C":
                                outChain[i / 3] = new ValueString('A');
                                break;
                            case "A":
                                if ((third == "T") || (third == "C"))
                                {
                                    outChain[i / 3] = new ValueString('D');
                                }
                                else
                                {
                                    if ((third == "A") || (third == "G"))
                                    {
                                        outChain[i / 3] = new ValueString('E');
                                    }
                                    else
                                    {
                                        throw new Exception();
                                    }
                                }

                                break;
                            case "G":
                                outChain[i / 3] = new ValueString('G');
                                break;
                            default:
                                throw new Exception();
                        }

                        break;
                    default:
                        throw new Exception();
                }
            }

            return outChain;
        }
예제 #16
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"));
        }
        public ActionResult Index(long matterId, string[] file)
        {
            return(CreateTask(() =>
            {
                var myFile = Request.Files[0];

                if (myFile == null || myFile.ContentLength == 0)
                {
                    throw new ArgumentNullException(nameof(file), "Sequence file not found or empty.");
                }

                int fileLen = myFile.ContentLength;
                var input = new byte[fileLen];

                // Initialize the stream.
                var fileStream = myFile.InputStream;

                // Read the file into the byte array.
                fileStream.Read(input, 0, fileLen);

                // Copy the byte array into a string.
                string stringSequence = Encoding.ASCII.GetString(input);
                string[] tempString = stringSequence.Split('\n', '\r');

                var sequenceStringBuilder = new StringBuilder();

                for (int j = 1; j < tempString.Length; j++)
                {
                    sequenceStringBuilder.Append(tempString[j]);
                }

                string resultStringSequence = DataTransformers.CleanFastaFile(sequenceStringBuilder.ToString());

                var chain = new BaseChain(resultStringSequence);
                string message;
                string status;
                BaseChain dbChain;
                using (var db = new LibiadaWebEntities())
                {
                    long sequenceId = db.CommonSequence.Single(c => c.MatterId == matterId).Id;
                    var commonSequenceRepository = new CommonSequenceRepository(db);
                    dbChain = commonSequenceRepository.GetLibiadaBaseChain(sequenceId);
                }

                if (dbChain.Equals(chain))
                {
                    message = "Sequence in db and in file are equal";
                    status = "Success";
                }
                else
                {
                    status = "Error";
                    if (chain.Alphabet.Cardinality != dbChain.Alphabet.Cardinality)
                    {
                        message = $"Alphabet sizes are not equal. In db - {dbChain.Alphabet.Cardinality}. In file - {chain.Alphabet.Cardinality}";
                        return new Dictionary <string, string> {
                            { "data", JsonConvert.SerializeObject(new { message }) }
                        };
                    }

                    for (int i = 0; i < chain.Alphabet.Cardinality; i++)
                    {
                        if (!chain.Alphabet[i].ToString().Equals(dbChain.Alphabet[i].ToString()))
                        {
                            message = $"{i} elements in alphabet are not equal. In db - {dbChain.Alphabet[i]}. In file - {chain.Alphabet[i]}";
                            return new Dictionary <string, string> {
                                { "data", JsonConvert.SerializeObject(new { message }) }
                            };
                        }
                    }

                    if (chain.Length != dbChain.Length)
                    {
                        message = $"Sequence length in db {dbChain.Length}, and sequence length from file{chain.Length}";
                        return new Dictionary <string, string> {
                            { "data", JsonConvert.SerializeObject(new { message, status }) }
                        };
                    }

                    int[] libiadaBuilding = chain.Building;
                    int[] dataBaseBuilding = dbChain.Building;

                    for (int j = 0; j < chain.Length; j++)
                    {
                        if (libiadaBuilding[j] != dataBaseBuilding[j])
                        {
                            message = $"{j} sequences elements are not equal. In db {dataBaseBuilding[j]}. In file {libiadaBuilding[j]}";
                            return new Dictionary <string, string> {
                                { "data", JsonConvert.SerializeObject(new { message, status }) }
                            };
                        }
                    }

                    message = "Sequences are equal and not equal at the same time.";
                }

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