Exemplo n.º 1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SequenceTransformerController"/> class.
 /// </summary>
 public SequenceTransformerController()
 {
     db = new LibiadaWebEntities();
     dnaSequenceRepository    = new GeneticSequenceRepository(db);
     commonSequenceRepository = new CommonSequenceRepository(db);
     elementRepository        = new ElementRepository(db);
 }
Exemplo n.º 2
0
        public ActionResult Index(
            long matterId,
            short characteristicLinkId,
            Notation notation,
            int step,
            int initialLength,
            string accuracy)
        {
            return(CreateTask(() =>
            {
                string characteristicName;
                string matterName;
                double[] characteristics;
                Chain sequence;
                IFullCalculator calculator;
                Link link;

                using (var db = new LibiadaWebEntities())
                {
                    var commonSequenceRepository = new CommonSequenceRepository(db);
                    matterName = Cache.GetInstance().Matters.Single(m => matterId == m.Id).Name;
                    var sequenceId = db.CommonSequence.Single(c => matterId == c.MatterId && c.Notation == notation).Id;
                    sequence = commonSequenceRepository.GetLibiadaChain(sequenceId);

                    var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                    characteristicName = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkId, notation);

                    FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkId);
                    calculator = FullCalculatorsFactory.CreateCalculator(characteristic);
                    link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkId);
                }

                // characteristics = SequencesCharacteristicsCalculator.Calculate( new[] { sequenceId }, characteristicLinkId);

                AverageRemoteness averageRemotenessCalc = new AverageRemoteness();
                double averageRemoteness = averageRemotenessCalc.Calculate(sequence, Link.Start);
                Alphabet alphabet = sequence.Alphabet;
                var doubleAccuracy = double.Parse(accuracy);

                List <SequencePredictionData> sequencePredictionResult;
                Chain chain;
                (sequencePredictionResult, chain) = Predict(averageRemotenessCalc, sequence, initialLength, alphabet, averageRemoteness, doubleAccuracy);

                var matching = FindPercentageOfMatching(sequence, chain, initialLength) * 100;


                var result = new Dictionary <string, object>
                {
                    { "result", sequencePredictionResult },
                    { "matterName", matterName },
                    { "matching", matching }
                };

                return new Dictionary <string, string>
                {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
        /// <summary>
        /// Calculation method.
        /// </summary>
        /// <param name="chainCharacteristicsIds">
        /// Dictionary with chain ids as a key
        /// and characteristicLink ids array as value.
        /// </param>
        /// <returns>
        /// The <see cref="T:double[][]"/>.
        /// </returns>
        public static Dictionary <long, Dictionary <short, double> > Calculate(Dictionary <long, short[]> chainCharacteristicsIds)
        {
            var newCharacteristics = new List <CharacteristicValue>();
            var allCharacteristics = new Dictionary <long, Dictionary <short, double> >();

            using (var db = new LibiadaWebEntities())
            {
                short[] characteristicLinkIds            = chainCharacteristicsIds.SelectMany(c => c.Value).Distinct().ToArray();
                var     characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                var     calculators = new Dictionary <short, LinkedFullCalculator>();
                foreach (short characteristicLinkId in characteristicLinkIds)
                {
                    Link link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkId);
                    FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkId);
                    calculators.Add(characteristicLinkId, new LinkedFullCalculator(characteristic, link));
                }

                var    commonSequenceRepository = new CommonSequenceRepository(db);
                long[] sequenceIds = chainCharacteristicsIds.Keys.ToArray();
                foreach (long sequenceId in sequenceIds)
                {
                    short[] sequenceCharacteristicLinkIds      = chainCharacteristicsIds[sequenceId];
                    Dictionary <short, double> characteristics = db.CharacteristicValue
                                                                 .Where(c => sequenceId == c.SequenceId && sequenceCharacteristicLinkIds.Contains(c.CharacteristicLinkId))
                                                                 .ToDictionary(ct => ct.CharacteristicLinkId, ct => ct.Value);

                    allCharacteristics.Add(sequenceId, characteristics);

                    if (characteristics.Count < sequenceCharacteristicLinkIds.Length)
                    {
                        Chain sequence = commonSequenceRepository.GetLibiadaChain(sequenceId);

                        foreach (short sequenceCharacteristicLinkId in sequenceCharacteristicLinkIds)
                        {
                            if (!characteristics.ContainsKey(sequenceCharacteristicLinkId))
                            {
                                LinkedFullCalculator calculator = calculators[sequenceCharacteristicLinkId];
                                double characteristicValue      = calculator.Calculate(sequence);
                                var    characteristic           = new CharacteristicValue
                                {
                                    SequenceId           = sequenceId,
                                    CharacteristicLinkId = sequenceCharacteristicLinkId,
                                    Value = characteristicValue
                                };

                                characteristics.Add(sequenceCharacteristicLinkId, characteristicValue);
                                newCharacteristics.Add(characteristic);
                            }
                        }
                    }
                }

                var characteristicRepository = new CharacteristicRepository(db);
                characteristicRepository.TrySaveCharacteristicsToDatabase(newCharacteristics);

                return(allCharacteristics);
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SequenceMixerController"/> class.
 /// </summary>
 public SequenceMixerController()
 {
     db = new LibiadaWebEntities();
     sequenceRepository           = new CommonSequenceRepository(db);
     dnaSequenceRepository        = new GeneticSequenceRepository(db);
     musicSequenceRepository      = new MusicSequenceRepository(db);
     literatureSequenceRepository = new LiteratureSequenceRepository(db);
     dataSequenceRepository       = new DataSequenceRepository(db);
     elementRepository            = new ElementRepository(db);
 }
        /// <summary>
        /// Calculation method.
        /// </summary>
        /// <param name="chainIds">
        /// The chains ids.
        /// </param>
        /// <param name="characteristicLinkIds">
        /// The characteristic type link ids.
        /// </param>
        /// <param name="rotate">
        /// The rotate flag.
        /// </param>
        /// <param name="complementary">
        /// The complementary flag.
        /// </param>
        /// <param name="rotationLength">
        /// The rotation length.
        /// </param>
        /// <returns>
        /// The <see cref="T:double[][]"/>.
        /// </returns>
        public static double[][] Calculate(long[][] chainIds, short[] characteristicLinkIds, bool rotate, bool complementary, uint?rotationLength)
        {
            var links           = new Link[characteristicLinkIds.Length];
            var calculators     = new IFullCalculator[characteristicLinkIds.Length];
            var characteristics = new double[chainIds.Length][];

            long[] sequenceIds = chainIds.SelectMany(c => c).Distinct().ToArray();
            var    sequences   = new Dictionary <long, Chain>();

            using (var db = new LibiadaWebEntities())
            {
                var commonSequenceRepository = new CommonSequenceRepository(db);
                for (int i = 0; i < sequenceIds.Length; i++)
                {
                    sequences.Add(sequenceIds[i], commonSequenceRepository.GetLibiadaChain(sequenceIds[i]));
                }

                var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                for (int k = 0; k < characteristicLinkIds.Length; k++)
                {
                    links[k] = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkIds[k]);
                    FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkIds[k]);
                    calculators[k] = FullCalculatorsFactory.CreateCalculator(characteristic);
                }
            }

            for (int i = 0; i < chainIds.Length; i++)
            {
                characteristics[i] = new double[calculators.Length];

                for (int j = 0; j < calculators.Length; j++)
                {
                    long sequenceId = chainIds[i][j];
                    var  sequence   = (Chain)sequences[sequenceId].Clone();
                    if (complementary)
                    {
                        var       sourceSequence        = new Sequence(Alphabets.DNA, sequence.ToString());
                        ISequence complementarySequence = sourceSequence.GetReverseComplementedSequence();
                        sequence = new Chain(complementarySequence.ConvertToString());
                    }

                    if (rotate)
                    {
                        int[] building = sequence.Building.Rotate(rotationLength ?? 0);
                        List <IBaseObject> newSequence = building.Select(t => new ValueInt(t)).ToList <IBaseObject>();
                        sequence = new Chain(newSequence);
                    }

                    characteristics[i][j] = calculators[j].Calculate(sequence, links[j]);
                }
            }

            return(characteristics);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SequenceElementsController"/> class.
 /// </summary>
 public SequenceElementsController()
 {
     db = new LibiadaWebEntities();
     elementRepository  = new ElementRepository(db);
     sequenceRepository = new CommonSequenceRepository(db);
 }
        /// <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());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="OrderTransformerController"/> class.
 /// </summary>
 public OrderTransformerController() : base(TaskType.OrderTransformer)
 {
     db = new LibiadaWebEntities();
     commonSequenceRepository = new CommonSequenceRepository(db);
 }
Exemplo n.º 9
0
        public ActionResult Index(
            long[] matterIds,
            short[] characteristicLinkIds,
            Notation[] notations,
            Language?[] languages,
            Translator?[] translators,
            PauseTreatment?[] pauseTreatments,
            bool?[] sequentialTransfers,
            ImageOrderExtractor?[] trajectories,
            bool rotate,
            bool complementary,
            uint?rotationLength)
        {
            return(CreateTask(() =>
            {
                Dictionary <long, string> mattersNames;

                long[][] sequenceIds;
                using (var db = new LibiadaWebEntities())
                {
                    var commonSequenceRepository = new CommonSequenceRepository(db);
                    sequenceIds = commonSequenceRepository.GetSequenceIds(matterIds,
                                                                          notations,
                                                                          languages,
                                                                          translators,
                                                                          pauseTreatments,
                                                                          sequentialTransfers,
                                                                          trajectories);
                    mattersNames = Cache.GetInstance().Matters.Where(m => matterIds.Contains(m.Id)).ToDictionary(m => m.Id, m => m.Name);
                }

                double[][] characteristics;
                if (!rotate && !complementary)
                {
                    characteristics = SequencesCharacteristicsCalculator.Calculate(sequenceIds, characteristicLinkIds);
                }
                else
                {
                    characteristics = SequencesCharacteristicsCalculator.Calculate(sequenceIds, characteristicLinkIds, rotate, complementary, rotationLength);
                }

                var sequencesCharacteristics = new SequenceCharacteristics[matterIds.Length];
                for (int i = 0; i < matterIds.Length; i++)
                {
                    sequencesCharacteristics[i] = new SequenceCharacteristics
                    {
                        MatterName = mattersNames[matterIds[i]],
                        Characteristics = characteristics[i]
                    };
                }

                var characteristicNames = new string[characteristicLinkIds.Length];
                var characteristicsList = new SelectListItem[characteristicLinkIds.Length];
                var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                for (int k = 0; k < characteristicLinkIds.Length; k++)
                {
                    characteristicNames[k] = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkIds[k], notations[k]);
                    characteristicsList[k] = new SelectListItem
                    {
                        Value = k.ToString(),
                        Text = characteristicNames[k],
                        Selected = false
                    };
                }

                var result = new Dictionary <string, object>
                {
                    { "characteristics", sequencesCharacteristics },
                    { "characteristicNames", characteristicNames },
                    { "characteristicsList", characteristicsList }
                };

                return new Dictionary <string, string> {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
Exemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClusterizationController"/> class.
 /// </summary>
 public ClusterizationController() : base(TaskType.Clusterization)
 {
     db = new LibiadaWebEntities();
     commonSequenceRepository         = new CommonSequenceRepository(db);
     characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
 }
Exemplo n.º 11
0
        public ActionResult Index(
            long[] matterIds,
            short[] characteristicLinkIds,
            Notation[] notations,
            Language?[] languages,
            Translator?[] translators,
            PauseTreatment?[] pauseTreatments,
            bool?[] sequentialTransfers,
            ImageOrderExtractor?[] trajectories,
            bool sort,
            bool theoretical)
        {
            return(CreateTask(() =>
            {
                var sequencesCharacteristics = new CongenericSequencesCharacteristics[matterIds.Length];
                var characteristicNames = new string[characteristicLinkIds.Length];
                var characteristicsList = new SelectListItem[characteristicLinkIds.Length];
                Dictionary <long, string> mattersNames;
                long[][] sequenceIds;

                using (var db = new LibiadaWebEntities())
                {
                    mattersNames = Cache.GetInstance().Matters.Where(m => matterIds.Contains(m.Id)).ToDictionary(m => m.Id, m => m.Name);

                    var commonSequenceRepository = new CommonSequenceRepository(db);
                    sequenceIds = commonSequenceRepository.GetSequenceIds(matterIds, notations, languages, translators, pauseTreatments, sequentialTransfers, trajectories);

                    var congenericCharacteristicRepository = CongenericCharacteristicRepository.Instance;
                    for (int k = 0; k < characteristicLinkIds.Length; k++)
                    {
                        characteristicNames[k] = congenericCharacteristicRepository.GetCharacteristicName(characteristicLinkIds[k], notations[k]);
                        characteristicsList[k] = new SelectListItem
                        {
                            Value = k.ToString(),
                            Text = characteristicNames[k],
                            Selected = false
                        };
                    }
                }

                double[][][] characteristics = CongenericSequencesCharacteristicsCalculator.Calculate(sequenceIds, characteristicLinkIds);

                for (int i = 0; i < matterIds.Length; i++)
                {
                    sequencesCharacteristics[i] = new CongenericSequencesCharacteristics
                    {
                        MatterName = mattersNames[matterIds[i]],
                        Elements = null,
                        Characteristics = characteristics[i]
                    };
                }

                var result = new Dictionary <string, object>
                {
                    { "characteristics", sequencesCharacteristics },
                    { "characteristicNames", characteristicNames },
                    { "characteristicsList", characteristicsList }
                };

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



                //var theoreticalRanks = new List<List<List<double>>>();
                //var elementNames = new List<List<string>>();
                //var newCharacteristics = new List<CongenericCharacteristicValue>();

                //var isLiteratureSequence = false;

                //// cycle through matters; first level of characteristics array
                //for (int w = 0; w < matterIds.Length; w++)
                //{
                //    long matterId = matterIds[w];
                //    elementNames.Add(new List<string>());
                //    characteristics.Add(new List<List<KeyValuePair<int, double>>>());
                //    theoreticalRanks.Add(new List<List<double>>());

                //    // cycle through characteristics and notations; second level of characteristics array
                //    for (int i = 0; i < characteristicLinkIds.Length; i++)
                //    {
                //        Notation notation = notations[i];

                //        long sequenceId;

                //        if (db.Matter.Single(m => m.Id == matterId).Nature == Nature.Literature)
                //        {
                //            Language language = languages[i];
                //            Translator? translator = translators[i];

                //            isLiteratureSequence = true;
                //            sequenceId = db.LiteratureSequence.Single(l => l.MatterId == matterId
                //                                                      && l.Notation == notation
                //                                                      && l.Language == language
                //                                                      && translator == l.Translator).Id;
                //        }
                //        else
                //        {
                //            sequenceId = db.CommonSequence.Single(c => c.MatterId == matterId && c.Notation == notation).Id;
                //        }

                //        Chain chain = commonSequenceRepository.GetLibiadaChain(sequenceId);
                //        chain.FillIntervalManagers();
                //        characteristics.Last().Add(new List<KeyValuePair<int, double>>());
                //        short characteristicLinkId = characteristicLinkIds[i];

                //        CongenericCharacteristic congenericCharacteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkId);
                //        ICongenericCalculator calculator = CongenericCalculatorsFactory.CreateCalculator(congenericCharacteristic);
                //        Link link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkId);
                //        List<long> sequenceElements = db.GetElementIds(sequenceId);
                //        int calculated = db.CongenericCharacteristicValue.Count(c => c.SequenceId == sequenceId && c.CharacteristicLinkId == characteristicLinkId);
                //        if (calculated < chain.Alphabet.Cardinality)
                //        {
                //            for (int j = 0; j < chain.Alphabet.Cardinality; j++)
                //            {
                //                long elementId = sequenceElements[j];

                //                CongenericChain tempChain = chain.CongenericChain(j);

                //                if (!db.CongenericCharacteristicValue.Any(b => b.SequenceId == sequenceId
                //                                                       && b.CharacteristicLinkId == characteristicLinkId
                //                                                       && b.ElementId == elementId))
                //                {
                //                    double value = calculator.Calculate(tempChain, link);
                //                    var currentCharacteristic = new CongenericCharacteristicValue
                //                    {
                //                        SequenceId = sequenceId,
                //                        CharacteristicLinkId = characteristicLinkId,
                //                        ElementId = elementId,
                //                        Value = value
                //                    };

                //                    newCharacteristics.Add(currentCharacteristic);
                //                }
                //            }
                //        }

                //        // cycle through all alphabet elements; third level of characteristics array
                //        for (int d = 0; d < chain.Alphabet.Cardinality; d++)
                //        {
                //            long elementId = sequenceElements[d];

                //            double characteristic = db.CongenericCharacteristicValue.Single(c => c.SequenceId == sequenceId
                //                                                                         && c.CharacteristicLinkId == characteristicLinkId
                //                                                                         && c.ElementId == elementId).Value;

                //            characteristics.Last().Last().Add(new KeyValuePair<int, double>(d, characteristic));

                //            if (i == 0)
                //            {
                //                elementNames.Last().Add(chain.Alphabet[d].ToString());
                //            }
                //        }

                //        // theoretical frequencies of orlov criterion
                //        if (theoretical)
                //        {
                //            theoreticalRanks[w].Add(new List<double>());
                //            ICongenericCalculator countCalculator = CongenericCalculatorsFactory.CreateCalculator(CongenericCharacteristic.ElementsCount);
                //            var counts = new List<int>();
                //            for (int f = 0; f < chain.Alphabet.Cardinality; f++)
                //            {
                //                counts.Add((int)countCalculator.Calculate(chain.CongenericChain(f), Link.NotApplied));
                //            }

                //            ICongenericCalculator frequencyCalculator = CongenericCalculatorsFactory.CreateCalculator(CongenericCharacteristic.Probability);
                //            var frequency = new List<double>();
                //            for (int f = 0; f < chain.Alphabet.Cardinality; f++)
                //            {
                //                frequency.Add(frequencyCalculator.Calculate(chain.CongenericChain(f), Link.NotApplied));
                //            }

                //            double maxFrequency = frequency.Max();
                //            double k = 1 / Math.Log(counts.Max());
                //            double b = (k / maxFrequency) - 1;
                //            int n = 1;
                //            double plow = chain.Length;
                //            double p = k / (b + n);
                //            while (p >= (1 / plow))
                //            {
                //                theoreticalRanks.Last().Last().Add(p);
                //                n++;
                //                p = k / (b + n);
                //            }
                //        }
                //    }
                //}

                //db.CongenericCharacteristicValue.AddRange(newCharacteristics);
                //db.SaveChanges();

                //// characteristics names
                //for (int k = 0; k < characteristicLinkIds.Length; k++)
                //{
                //    string characteristicType = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkIds[k], notations[k]);
                //    if (isLiteratureSequence)
                //    {
                //        Language language = languages[k];
                //        characteristicNames.Add(characteristicType + " " + language.GetDisplayValue());
                //    }
                //    else
                //    {
                //        characteristicNames.Add(characteristicType);
                //    }
                //}

                //// rank sorting
                //if (sort)
                //{
                //    for (int f = 0; f < matterIds.Length; f++)
                //    {
                //        for (int p = 0; p < characteristics[f].Count; p++)
                //        {
                //            SortKeyValuePairList(characteristics[f][p]);
                //        }
                //    }
                //}


                //return new Dictionary<string, object>
                //{
                //    { "characteristics", characteristics },
                //    { "elementNames", elementNames },
                //    { "characteristicNames", characteristicNames },
                //    { "matterIds", matterIds },
                //    { "theoreticalRanks", theoreticalRanks },
                //    { "characteristicsList", characteristicsList }
                //};
            }));
        }
Exemplo n.º 12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AccordanceCalculationController"/> class.
 /// </summary>
 public AccordanceCalculationController() : base(TaskType.AccordanceCalculation)
 {
     db = new LibiadaWebEntities();
     commonSequenceRepository         = new CommonSequenceRepository(db);
     characteristicTypeLinkRepository = AccordanceCharacteristicRepository.Instance;
 }
Exemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SubsequenceExtractor"/> class.
 /// </summary>
 /// <param name="db">
 /// The db.
 /// </param>
 public SubsequenceExtractor(LibiadaWebEntities db)
 {
     this.db = db;
     commonSequenceRepository = new CommonSequenceRepository(db);
 }
        public ActionResult Index(
            long matterId,
            short characteristicLinkId,
            Notation notation,
            int step,
            int initialLength,
            double accuracy)
        {
            return(CreateTask(() =>
            {
                string characteristicName;
                string mattersName;
                double[] characteristics;
                Chain sequence;
                IFullCalculator calculator;
                Link link;

                using (var db = new LibiadaWebEntities())
                {
                    var commonSequenceRepository = new CommonSequenceRepository(db);
                    mattersName = db.Matter.Single(m => matterId == m.Id).Name;
                    var sequenceId = db.CommonSequence.Single(c => matterId == c.MatterId && c.Notation == notation).Id;
                    sequence = commonSequenceRepository.GetLibiadaChain(sequenceId);

                    var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                    characteristicName = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkId, notation);

                    FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkId);
                    calculator = FullCalculatorsFactory.CreateCalculator(characteristic);
                    link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkId);
                }

                // characteristics = SequencesCharacteristicsCalculator.Calculate( new[] { sequenceId }, characteristicLinkId);

                CutRule cutRule = new CutRuleWithFixedStart(sequence.Length, step);

                Depth depthCaulc = new Depth();

                CutRuleIterator iter = cutRule.GetIterator();

                var fragments = new List <Chain>();
                var partNames = new List <string>();
                var lengthes = new List <int>();
                var teoreticalDepht = new List <double>();

                while (iter.Next())
                {
                    var fragment = new Chain(iter.GetEndPosition() - iter.GetStartPosition());

                    for (int k = 0; iter.GetStartPosition() + k < iter.GetEndPosition(); k++)
                    {
                        fragment.Set(sequence[iter.GetStartPosition() + k], k);
                    }

                    fragments.Add(fragment);
                    partNames.Add(fragment.ToString());
                    lengthes.Add(fragment.Length);

                    teoreticalDepht.Add(depthCaulc.Calculate(fragment, Link.Start));
                }

                characteristics = new double[fragments.Count];
                for (int k = 0; k < fragments.Count; k++)
                {
                    characteristics[k] = calculator.Calculate(fragments[k], link);
                    // fragmentsData[k] = new FragmentData(characteristics, fragments[k].ToString(), starts[i][k], fragments[k].Length);
                }



                // var predicted = new List<Chain>();

                //int[] startingPart = new int[initialLength];


                Chain predicted = new Chain(initialLength);

                for (int i = 0; i < initialLength; i++)
                {
                    predicted.Set(sequence[i], i);
                }

                Alphabet alphabet = sequence.Alphabet;
                IEnumerator enumerator = alphabet.GetEnumerator();
                var sequencePredictionResult = new List <SequencePredictionData>();

                for (int i = initialLength; i < sequence.Length; i++)
                {
                    Chain temp = new Chain(i + 1);
                    for (int j = 0; j < i; j++)
                    {
                        temp.Set(predicted[j], j);
                    }
                    predicted = temp;
                    double depth = 0;

                    /* do
                     * {
                     *   predicted.Set((IBaseObject)enumerator.Current, i);
                     *   depth = depthCaulc.Calculate(predicted, Link.Start);
                     *   if (System.Math.Abs(depth - teoreticalDepht.ElementAt(i)) <= accuracy)
                     *   {
                     *       break;
                     *   }
                     * } while (enumerator.MoveNext());*/
                    IBaseObject predictedLetter = null;
                    foreach (IBaseObject letter in alphabet)
                    {
                        predicted.Set(letter, i);
                        depth = depthCaulc.Calculate(predicted, Link.Start);
                        if (System.Math.Abs(depth - teoreticalDepht.ElementAt(i)) <= accuracy)
                        {
                            predictedLetter = letter;
                            break;
                        }
                    }



                    sequencePredictionResult.Add(new SequencePredictionData
                    {
                        Fragment = fragments.ElementAt(i).ToString(),
                        Predicted = /*enumerator.Current.ToString()*/ predicted.ToString(),
                        ActualCharacteristic = depth,
                        TheoreticalCharacteristic = teoreticalDepht.ElementAt(i)
                    });
                }

                /*int equal = 0;
                 * for (int i = initialLength; i < sequence.Length; i++)
                 * {
                 *  if (sequence[i] == predicted[i])
                 *  {
                 *      equal++;
                 *  }
                 * }
                 *
                 *
                 * double accuracyPercentage = equal / (sequence.Length - initialLength);*/


                // TODO: sequence prediction


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

                return new Dictionary <string, object>
                {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
        public ActionResult Index(
            long[] matterIds,
            OrderTransformation[] transformationsSequence,
            int iterationsCount,
            short[] characteristicLinkIds,
            Notation[] notations,
            Language?[] languages,
            Translator?[] translators,
            PauseTreatment?[] pauseTreatments,
            bool?[] sequentialTransfers,
            ImageOrderExtractor?[] trajectories)
        {
            return(CreateTask(() =>
            {
                Dictionary <long, string> mattersNames = Cache.GetInstance().Matters.Where(m => matterIds.Contains(m.Id)).ToDictionary(m => m.Id, m => m.Name);
                Chain[][] sequences = new Chain[matterIds.Length][];

                using (var db = new LibiadaWebEntities())
                {
                    var commonSequenceRepository = new CommonSequenceRepository(db);
                    long[][] sequenceIds = commonSequenceRepository.GetSequenceIds(matterIds,
                                                                                   notations,
                                                                                   languages,
                                                                                   translators,
                                                                                   pauseTreatments,
                                                                                   sequentialTransfers,
                                                                                   trajectories);
                    for (int i = 0; i < matterIds.Length; i++)
                    {
                        sequences[i] = new Chain[characteristicLinkIds.Length];
                        for (int j = 0; j < characteristicLinkIds.Length; j++)
                        {
                            sequences[i][j] = commonSequenceRepository.GetLibiadaChain(sequenceIds[i][j]);
                        }
                    }
                }

                var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                var sequencesCharacteristics = new SequenceCharacteristics[matterIds.Length];
                matterIds = matterIds.OrderBy(m => m).ToArray();

                for (int i = 0; i < matterIds.Length; i++)
                {
                    long matterId = matterIds[i];
                    var characteristics = new double[characteristicLinkIds.Length];
                    for (int j = 0; j < characteristicLinkIds.Length; j++)
                    {
                        Notation notation = notations[j];


                        Chain sequence = sequences[i][j];
                        for (int l = 0; l < iterationsCount; l++)
                        {
                            for (int k = 0; k < transformationsSequence.Length; k++)
                            {
                                sequence = transformationsSequence[k] == OrderTransformation.Dissimilar ? DissimilarChainFactory.Create(sequence)
                                                                     : HighOrderFactory.Create(sequence, EnumExtensions.GetLink(transformationsSequence[k]));
                            }
                        }

                        int characteristicLinkId = characteristicLinkIds[j];
                        Link link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkId);
                        FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkId);

                        IFullCalculator calculator = FullCalculatorsFactory.CreateCalculator(characteristic);
                        characteristics[j] = calculator.Calculate(sequence, link);
                    }

                    sequencesCharacteristics[i] = new SequenceCharacteristics
                    {
                        MatterName = mattersNames[matterId],
                        Characteristics = characteristics
                    };
                }

                var characteristicNames = new string[characteristicLinkIds.Length];
                var characteristicsList = new SelectListItem[characteristicLinkIds.Length];
                for (int k = 0; k < characteristicLinkIds.Length; k++)
                {
                    characteristicNames[k] = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkIds[k], notations[k]);
                    characteristicsList[k] = new SelectListItem
                    {
                        Value = k.ToString(),
                        Text = characteristicNames[k],
                        Selected = false
                    };
                }

                var transformations = transformationsSequence.Select(ts => ts.GetDisplayValue());

                var result = new Dictionary <string, object>
                {
                    { "characteristics", sequencesCharacteristics },
                    { "characteristicNames", characteristicNames },
                    { "characteristicsList", characteristicsList },
                    { "transformationsList", transformations },
                    { "iterationsCount", iterationsCount }
                };

                return new Dictionary <string, string> {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
        public ActionResult Index(
            long[] matterIds,
            short[] characteristicLinkIds,
            Notation[] notations,
            Language?[] languages,
            Translator?[] translators,
            PauseTreatment?[] pauseTreatments,
            bool?[] sequentialTransfers,
            ImageOrderExtractor?[] trajectories,
            int clustersCount,
            ClusterizationType clusterizationType,
            double equipotencyWeight        = 1,
            double normalizedDistanceWeight = 1,
            double distanceWeight           = 1,
            double bandwidth    = 0,
            int maximumClusters = 2)
        {
            return(CreateTask(() =>
            {
                Dictionary <long, string> mattersNames;
                Dictionary <long, string> matters = Cache.GetInstance()
                                                    .Matters
                                                    .Where(m => matterIds.Contains(m.Id))
                                                    .ToDictionary(m => m.Id, m => m.Name);

                long[][] sequenceIds;
                using (var db = new LibiadaWebEntities())
                {
                    var commonSequenceRepository = new CommonSequenceRepository(db);
                    sequenceIds = commonSequenceRepository.GetSequenceIds(matterIds,
                                                                          notations,
                                                                          languages,
                                                                          translators,
                                                                          pauseTreatments,
                                                                          sequentialTransfers,
                                                                          trajectories);
                    mattersNames = db.Matter.Where(m => matterIds.Contains(m.Id)).ToDictionary(m => m.Id, m => m.Name);
                }

                double[][] characteristics;

                characteristics = SequencesCharacteristicsCalculator.Calculate(sequenceIds, characteristicLinkIds);

                var clusterizationParams = new Dictionary <string, double>
                {
                    { "clustersCount", clustersCount },
                    { "equipotencyWeight", equipotencyWeight },
                    { "normalizedDistanceWeight", normalizedDistanceWeight },
                    { "distanceWeight", distanceWeight },
                    { "bandwidth", bandwidth },
                    { "maximumClusters", maximumClusters }
                };

                IClusterizator clusterizator = ClusterizatorsFactory.CreateClusterizator(clusterizationType, clusterizationParams);
                int[] clusterizationResult = clusterizator.Cluster(clustersCount, characteristics);
                var mattersCharacteristics = new object[matterIds.Length];
                for (int i = 0; i < clusterizationResult.Length; i++)
                {
                    mattersCharacteristics[i] = new
                    {
                        MatterName = mattersNames[matterIds[i]],
                        cluster = clusterizationResult[i] + 1,
                        Characteristics = characteristics[i]
                    };
                }

                var characteristicNames = new string[characteristicLinkIds.Length];
                var characteristicsList = new SelectListItem[characteristicLinkIds.Length];
                var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                for (int k = 0; k < characteristicLinkIds.Length; k++)
                {
                    characteristicNames[k] = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkIds[k], notations[k]);
                    characteristicsList[k] = new SelectListItem
                    {
                        Value = k.ToString(),
                        Text = characteristicNames[k],
                        Selected = false
                    };
                }

                var result = new Dictionary <string, object>
                {
                    { "characteristicNames", characteristicNames },
                    { "characteristics", mattersCharacteristics },
                    { "characteristicsList", characteristicsList },
                    { "clustersCount", clusterizationResult.Distinct().Count() }
                };

                return new Dictionary <string, string> {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
        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 }) }
                };
            }));
        }
Exemplo n.º 18
0
        public ActionResult Index(
            long[] matterIds,
            OrderTransformation[] transformationsSequence,
            int iterationsCount,
            short[] characteristicLinkIds,
            Notation[] notations,
            Language[] languages,
            Translator?[] translators,
            PauseTreatment[] pauseTreatments,
            bool[] sequentialTransfers)
        {
            return(CreateTask(() =>
            {
                var db = new LibiadaWebEntities();
                var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                var commonSequenceRepository = new CommonSequenceRepository(db);
                var mattersCharacteristics = new object[matterIds.Length];
                matterIds = matterIds.OrderBy(m => m).ToArray();
                Dictionary <long, Matter> matters = db.Matter.Where(m => matterIds.Contains(m.Id)).ToDictionary(m => m.Id);

                for (int i = 0; i < matterIds.Length; i++)
                {
                    long matterId = matterIds[i];
                    var characteristics = new double[characteristicLinkIds.Length];
                    for (int k = 0; k < characteristicLinkIds.Length; k++)
                    {
                        Notation notation = notations[k];
                        long sequenceId;
                        switch (matters[matterId].Nature)
                        {
                        case Nature.Literature:
                            Language language = languages[k];
                            Translator translator = translators[k] ?? Translator.NoneOrManual;
                            sequenceId = db.LiteratureSequence.Single(l => l.MatterId == matterId &&
                                                                      l.Notation == notation &&
                                                                      l.Language == language &&
                                                                      l.Translator == translator).Id;
                            break;

                        case Nature.Music:
                            PauseTreatment pauseTreatment = pauseTreatments[k];
                            bool sequentialTransfer = sequentialTransfers[k];
                            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;
                        }

                        Chain sequence = commonSequenceRepository.GetLibiadaChain(sequenceId);
                        for (int l = 0; l < iterationsCount; l++)
                        {
                            for (int j = 0; j < transformationsSequence.Length; j++)
                            {
                                sequence = transformationsSequence[j] == OrderTransformation.Dissimilar ? DissimilarChainFactory.Create(sequence)
                                                                     : HighOrderFactory.Create(sequence, EnumExtensions.GetLink(transformationsSequence[j]));
                            }
                        }

                        int characteristicLinkId = characteristicLinkIds[k];
                        Link link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkId);
                        FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkId);

                        IFullCalculator calculator = FullCalculatorsFactory.CreateCalculator(characteristic);
                        characteristics[k] = calculator.Calculate(sequence, link);
                    }

                    mattersCharacteristics[i] = new { matterName = matters[matterId].Name, characteristics };
                }

                var characteristicNames = new string[characteristicLinkIds.Length];
                for (int k = 0; k < characteristicLinkIds.Length; k++)
                {
                    characteristicNames[k] = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkIds[k], notations[k]);
                }

                var characteristicsList = new SelectListItem[characteristicLinkIds.Length];
                for (int i = 0; i < characteristicNames.Length; i++)
                {
                    characteristicsList[i] = new SelectListItem
                    {
                        Value = i.ToString(),
                        Text = characteristicNames[i],
                        Selected = false
                    };
                }

                var transformations = new Dictionary <int, string>();
                for (int i = 0; i < transformationsSequence.Length; i++)
                {
                    transformations.Add(i, transformationsSequence[i].GetDisplayValue());
                }

                var result = new Dictionary <string, object>
                {
                    { "characteristics", mattersCharacteristics },
                    { "characteristicNames", characteristicNames },
                    { "characteristicsList", characteristicsList },
                    { "transformationsList", transformations },
                    { "iterationsCount", iterationsCount }
                };

                return new Dictionary <string, object>
                {
                    { "data", JsonConvert.SerializeObject(result) }
                };
            }));
        }
Exemplo n.º 19
0
        public ActionResult Index(
            long[] matterIds,
            OrderTransformation[] transformationsSequence,
            int iterationsCount,
            short characteristicLinkId,
            Notation notation,
            Language?language,
            Translator?translator,
            PauseTreatment?pauseTreatment,
            bool?sequentialTransfer)
        {
            return(CreateTask(() =>
            {
                var db = new LibiadaWebEntities();
                var characteristicTypeLinkRepository = FullCharacteristicRepository.Instance;
                var commonSequenceRepository = new CommonSequenceRepository(db);
                var mattersCharacteristics = new object[matterIds.Length];
                matterIds = matterIds.OrderBy(m => m).ToArray();
                Dictionary <long, Matter> matters = db.Matter.Where(m => matterIds.Contains(m.Id)).ToDictionary(m => m.Id);

                for (int i = 0; i < matterIds.Length; i++)
                {
                    long matterId = matterIds[i];
                    long sequenceId;
                    switch (matters[matterId].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;
                    }

                    Link link = characteristicTypeLinkRepository.GetLinkForCharacteristic(characteristicLinkId);
                    FullCharacteristic characteristic = characteristicTypeLinkRepository.GetCharacteristic(characteristicLinkId);
                    IFullCalculator calculator = FullCalculatorsFactory.CreateCalculator(characteristic);

                    Chain sequence = commonSequenceRepository.GetLibiadaChain(sequenceId);

                    var characteristics = new double[transformationsSequence.Length * iterationsCount];
                    for (int j = 0; j < iterationsCount; j++)
                    {
                        for (int k = 0; k < transformationsSequence.Length; k++)
                        {
                            sequence = transformationsSequence[k] == OrderTransformation.Dissimilar ? DissimilarChainFactory.Create(sequence)
                                                                 : HighOrderFactory.Create(sequence, transformationsSequence[k].GetLink());
                            characteristics[transformationsSequence.Length * j + k] = calculator.Calculate(sequence, link);
                        }
                    }

                    mattersCharacteristics[i] = new { matterName = matters[matterId].Name, characteristics };
                }

                string characteristicName = characteristicTypeLinkRepository.GetCharacteristicName(characteristicLinkId, notation);


                var result = new Dictionary <string, object>
                {
                    { "characteristics", mattersCharacteristics },
                    { "characteristicName", characteristicName },
                    { "transformationsList", transformationsSequence.Select(ts => ts.GetDisplayValue()) },
                    { "iterationsCount", iterationsCount }
                };

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