Set() public method

Sets item in provided position.
public Set ( IBaseObject item, int index ) : void
item IBaseObject /// The item. ///
index int /// The index. ///
return void
        /// <summary>
        /// The create.
        /// </summary>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="link">
        /// The link.
        /// </param>
        /// <returns>
        /// The <see cref="Chain"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// Thrown if link is unacceptable.
        /// </exception>
        public static Chain Create(Chain source, Link link)
        {
            if (link != Link.Start && link != Link.End && link != Link.CycleEnd && link != Link.CycleStart)
            {
                throw new ArgumentException("Unknown link", "link");
            }

            var result = new Chain(source.GetLength());
            Alphabet sourceAlphabet = source.Alphabet;
            var entries = new int[sourceAlphabet.Cardinality];

            var intervals = new int[sourceAlphabet.Cardinality][];

            for (int j = 0; j < sourceAlphabet.Cardinality; j++)
            {
                var intervalsManager = new CongenericIntervalsManager(source.CongenericChain(j));
                intervals[j] = intervalsManager.GetIntervals(link);
            }

            for (int i = 0; i < source.GetLength(); i++)
            {
                var elementIndex = sourceAlphabet.IndexOf(source[i]);
                int entry = entries[elementIndex]++;
                var interval = intervals[elementIndex][entry];
                result.Set(new ValueInt(interval), i);
            }

            return result;
        }
 public void Initialize()
 {
     testChain = new Chain(8);
     testChain.Set((ValueString)"A", 0);
     testChain.Set((ValueString)"G", 1);
     testChain.Set((ValueString)"T", 2);
     testChain.Set((ValueString)"A", 3);
     testChain.Set((ValueString)"A", 4);
     testChain.Set((ValueString)"G", 5);
     testChain.Set((ValueString)"T", 6);
     testChain.Set((ValueString)"C", 7);
 }
        /// <summary>
        /// Method that creates chain of "first occurrences of different elements".
        /// </summary>
        /// <param name="source">
        /// Source chain.
        /// </param>
        /// <returns>/
        /// Dissimilar chain.
        /// </returns>
        public static Chain Create(BaseChain source)
        {
            var result = new Chain(source.GetLength());
            Alphabet sourceAlphabet = source.Alphabet;
            var entries = new int[sourceAlphabet.Cardinality];

            for (int i = 0; i < source.GetLength(); i++)
            {
                int elementIndex = sourceAlphabet.IndexOf(source[i]);
                int entry = ++entries[elementIndex];
                result.Set(new ValueInt(entry), i);
            }

            return result;
        }
        public void MarkovChainNotCongenericDynamicOneRangTwoTest()
        {
            // using mock of random generator
            IGenerator generator = new MockGenerator();

            // rank of markov chain is 2 (each element depends on one previous element)
            int markovChainRank = 2;

            // heterogeneity is 1 (there are 2 models - for odd and even positions)
            int notCongenericRank = 1;

            // creating markov chain
            // MarkovChainNotCongenericDynamic<Chain, Chain> MarkovChain = new MarkovChainNotCongenericDynamic<Chain, Chain>(markovChainRank, notCongenericRank, generator);

            // length of generated sequence
            int length = 12;

            // teaching markov chain (TeachingMethod.None means there is no preprocessing)
            // MarkovChain.Teach(TestChain, TeachingMethod.None);

            // Chain Temp = MarkovChain.Generate(length);

            /**
             * Внутри неоднородной марковской цепи существует n однородных марковских цепей. n - порядок неоднородности цепи
             * порядок данных однородных цепей равен порядку неоднородной цепи
             * однородные цепи используются по очереди как при обучении так и  при генерации.
             *
             * В данном тесте внутри неоднородной марковской цепи есть 2 однородные цепи.
             * Матрицы переходных вероятностей (в скобках указано кол-во входений при обучении) в них такие
             *
             * 1. Sequence
             *   first level (unconditional probability)
             *
             *    a| 1/2 (3) |
             *    b| 1/3 (2) |
             *    c| 1/6 (1) |
             *    d| 0 (0)   |
             *
             *   second level (conditional probability taking into account 1 previous element)
             *
             *    |   a  |   b  |  с   |  d   |
             * ---|------|------|------|------|
             *  a |0,3(1)| 0(0) |0,3(1)|0,3(1)|
             * ---|------|------|------|------|
             *  b |0,5(1)|0,5(1)| 0(0) | 0(0) |
             * ---|------|------|------|------|
             *  c | 1(1) | 0(0) | 0(0) | 0(0) |
             * ---|------|------|------|------|
             *  d | 0(0) | 0(0) | 0(0) | 0(0) |
             * ---|------|------|------|------|
             *
             * 2. Sequence
             *   first level (unconditional probability)
             *
             *    a| 2/5 (2) |
             *    b| 1/5 (1) |
             *    c| 1/5 (1) |
             *    d| 1/5 (1) |
             *
             *   second level (conditional probability taking into account 1 previous element)
             *
             *    |   a  |   b  |  с   |  d   |
             * ---|------|------|------|------|
             *  a |0,5(1)| 0(0) |0,5(1)| 0(0) |
             * ---|------|------|------|------|
             *  b | 1(1) | 0(0) | 0(0) | 0(0) |
             * ---|------|------|------|------|
             *  c | 0(0) | 1(1) | 0(0) | 0(0) |
             * ---|------|------|------|------|
             *  d | 0(0) | 1(1) | 0(0) | 0(0) |
             * ---|------|------|------|------|
             *
             *
             * During teaching pairs are added as folowing
             *   |-| |-| |-| |-| |-|   <>- In second markov chain
             * a d b a a c b b a a c a
             * |_| |_| |_| |_| |_| |_| <>- In first markov chain
             *
             */

            // expected result of generation
            var result = new Chain(12);
            result.Set((ValueString)"b", 0); // 1 chain. вероятность по первому уровню. выпало  0,77 Получаем b
            result.Set((ValueString)"a", 1); // 2 chain. вероятность по второму уровню. выпало  0.15 Получаем a
            result.Set((ValueString)"c", 2); // 1 chain. вероятность по второму уровню. выпало  0.96 Получаем с
            result.Set((ValueString)"b", 3); // 2 chain. вероятность по второму уровню. выпало  0.61 Получаем b
            result.Set((ValueString)"a", 4); // 1 chain. вероятность по второму уровню. выпало  0.15 Получаем a
            result.Set((ValueString)"c", 5); // 2 chain. вероятность по второму уровню. выпало  0.85 Получаем c
            result.Set((ValueString)"a", 6); // 1 chain. вероятность по второму уровню. выпало  0.67 Получаем a
            result.Set((ValueString)"c", 7); // 2 chain. вероятность по второму уровню. выпало  0.51 Получаем c
            result.Set((ValueString)"a", 8); // 1 chain. вероятность по второму уровню. выпало  0.71 Получаем a
            result.Set((ValueString)"a", 9); // 2 chain. вероятность по второму уровню. выпало  0.2 Получаем a
            result.Set((ValueString)"c", 10); // 1 chain. вероятность по второму уровню. выпало  0.77 Получаем с
            result.Set((ValueString)"b", 11); // 2 chain. вероятность по второму уровню. выпало  0.15 Получаем b
        }
        public void Initialize()
        {
            // Creating sequence containing 12 elements.
            // |a|d|b|a|a|c|b|b|a|a|c|a|
            testChain = new Chain(12);
            testChain.Set((ValueString)"a", 0);
            testChain.Set((ValueString)"d", 1);
            testChain.Set((ValueString)"b", 2);
            testChain.Set((ValueString)"a", 3);
            testChain.Set((ValueString)"a", 4);
            testChain.Set((ValueString)"c", 5);
            testChain.Set((ValueString)"b", 6);
            testChain.Set((ValueString)"b", 7);
            testChain.Set((ValueString)"a", 8);
            testChain.Set((ValueString)"a", 9);
            testChain.Set((ValueString)"c", 10);
            testChain.Set((ValueString)"a", 11);

            secondTestChain = new Chain(12);
            secondTestChain.Set((ValueString)"a", 0);
            secondTestChain.Set((ValueString)"a", 1);
            secondTestChain.Set((ValueString)"a", 2);
            secondTestChain.Set((ValueString)"a", 3);
            secondTestChain.Set((ValueString)"a", 4);
            secondTestChain.Set((ValueString)"a", 5);
            secondTestChain.Set((ValueString)"b", 6);
            secondTestChain.Set((ValueString)"a", 7);
            secondTestChain.Set((ValueString)"a", 8);
            secondTestChain.Set((ValueString)"a", 9);
            secondTestChain.Set((ValueString)"b", 10);
            secondTestChain.Set((ValueString)"a", 11);
        }
        public void GetBinaryIntervalIncompleteChainTest()
        {
            // A C A _ C C _ A A A C C A
            // A _ A _ _ _ _ A A A _ _ A
            // _ C _ _ C C _ _ _ _ C C _
            var chain = new Chain(13);

            chain.Set(elements["A"], 0);
            chain.Set(elements["C"], 1);
            chain.Set(elements["A"], 2);

            chain.Set(elements["C"], 4);
            chain.Set(elements["C"], 5);

            chain.Set(elements["A"], 7);
            chain.Set(elements["A"], 8);
            chain.Set(elements["A"], 9);
            chain.Set(elements["C"], 10);
            chain.Set(elements["C"], 11);
            chain.Set(elements["A"], 12);

            var intervalManager = chain.GetRelationIntervalsManager(elements["A"], elements["C"]);
            Assert.AreEqual(1, intervalManager.GetBinaryInterval(1));
            Assert.AreEqual(2, intervalManager.GetBinaryInterval(2));
            Assert.AreEqual(-1, intervalManager.GetBinaryInterval(3));
            Assert.AreEqual(-1, intervalManager.GetBinaryInterval(4));
            Assert.AreEqual(1, intervalManager.GetBinaryInterval(5));
            Assert.AreEqual(-1, intervalManager.GetBinaryInterval(6));
            Assert.AreEqual(-1, intervalManager.GetBinaryInterval(7));

            intervalManager = chain.GetRelationIntervalsManager(elements["C"], elements["A"]);
            Assert.AreEqual(1, intervalManager.GetBinaryInterval(1));
            Assert.AreEqual(-1, intervalManager.GetBinaryInterval(2));
            Assert.AreEqual(2, intervalManager.GetBinaryInterval(3));
            Assert.AreEqual(-1, intervalManager.GetBinaryInterval(4));
            Assert.AreEqual(1, intervalManager.GetBinaryInterval(5));
            Assert.AreEqual(-1, intervalManager.GetBinaryInterval(6));
        }
        public ActionResult Index(
            long[] matterIds,
            int[] characteristicTypeLinkIds,
            int? languageId,
            int? translatorId,
            int notationId,
            int length,
            int step,
            bool delta,
            bool fourier,
            bool growingWindow,
            bool autocorrelation)
        {
            return Action(() =>
            {
                var characteristicNames = new string[characteristicTypeLinkIds.Length];
                var partNames = new List<string>[matterIds.Length];
                var starts = new List<int>[matterIds.Length];
                var lengthes = new List<int>[matterIds.Length];
                var chains = new Chain[matterIds.Length];
                var mattersCharacteristics = new object[matterIds.Length];

                var calculators = new List<IFullCalculator>();
                var links = new List<Link>();
                matterIds = matterIds.OrderBy(m => m).ToArray();
                var matters = db.Matter.Where(m => matterIds.Contains(m.Id)).ToDictionary(m => m.Id);

                for (int k = 0; k < matterIds.Length; k++)
                {
                    long matterId = matterIds[k];
                    Nature nature = db.Matter.Single(m => m.Id == matterId).Nature;

                    long sequenceId;
                    switch (nature)
                    {
                        case Nature.Literature:
                            sequenceId = db.LiteratureSequence.Single(l => l.MatterId == matterId
                                                                        && l.NotationId == notationId
                                                                        && l.LanguageId == languageId
                                                                        && l.TranslatorId == translatorId).Id;
                            break;
                        default:
                            var id = notationId;
                            sequenceId = db.CommonSequence.Single(c => c.MatterId == matterId
                                                                    && c.NotationId == id).Id;
                            break;
                    }

                    chains[k] = commonSequenceRepository.ToLibiadaChain(sequenceId);
                }

                foreach (int characteristicTypeLinkId in characteristicTypeLinkIds)
                {
                    string className = characteristicTypeLinkRepository.GetCharacteristicType(characteristicTypeLinkId).ClassName;
                    calculators.Add(CalculatorsFactory.CreateFullCalculator(className));
                    links.Add(characteristicTypeLinkRepository.GetLibiadaLink(characteristicTypeLinkId));
                }

                for (int i = 0; i < chains.Length; i++)
                {
                    CutRule cutRule = growingWindow
                            ? (CutRule)new CutRuleWithFixedStart(chains[i].GetLength(), step)
                            : new SimpleCutRule(chains[i].GetLength(), step, length);

                    CutRuleIterator iter = cutRule.GetIterator();

                    List<Chain> fragments = new List<Chain>();
                    partNames[i] = new List<string>();
                    starts[i] = new List<int>();
                    lengthes[i] = new List<int>();

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

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

                        fragments.Add(fragment);
                        partNames[i].Add(fragment.ToString());
                        starts[i].Add(iter.GetStartPosition());
                        lengthes[i].Add(fragment.GetLength());
                    }

                    var fragmentsData = new FragmentData[fragments.Count];
                    for (int k = 0; k < fragments.Count; k++)
                    {
                        var characteristics = new double[calculators.Count];
                        for (int j = 0; j < calculators.Count; j++)
                        {
                            characteristics[j] = calculators[j].Calculate(fragments[k], links[j]);
                        }

                        fragmentsData[k] = new FragmentData(characteristics, fragments[k].ToString(), starts[i][k], fragments[k].GetLength());
                    }

                    double[][] differenceData = null;
                    double[][] fourierData = null;
                    double[][] autocorrelationData = null;

                    if (delta)
                    {
                        differenceData = CalculateDifference(fragmentsData.Select(f => f.Characteristics).ToArray());
                    }

                    if (fourier)
                    {
                        fourierData = FastFourierTransform.CalculateFastFourierTransform(fragmentsData.Select(f => f.Characteristics).ToArray());
                    }

                    if (autocorrelation)
                    {
                        autocorrelationData = AutoCorrelation.CalculateAutocorrelation(fragmentsData.Select(f => f.Characteristics).ToArray());
                    }

                    mattersCharacteristics[i] = new { matterName = matters[matterIds[i]].Name, fragmentsData, differenceData, fourierData, autocorrelationData };
                }

                for (int l = 0; l < characteristicTypeLinkIds.Length; l++)
                {
                    characteristicNames[l] = characteristicTypeLinkRepository.GetCharacteristicType(characteristicTypeLinkIds[l]).Name;
                }

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

                string notationName = db.Notation.Single(n => n.Id == notationId).Name;

                var result = new Dictionary<string, object>
                {
                    { "characteristics", mattersCharacteristics },
                    { "notationName", notationName },
                    { "starts", starts },
                    { "partNames", partNames },
                    { "lengthes", lengthes },
                    { "characteristicNames", characteristicNames },
                    { "matterIds", matterIds },
                    { "characteristicsList", characteristicsList }
                };

                return new Dictionary<string, object> { { "data", JsonConvert.SerializeObject(result) } };
            });
        }
        /// <summary>
        /// The generate chain.
        /// </summary>
        /// <param name="alphabet">
        /// Generated sequence alphabet.
        /// </param>
        /// <param name="i">
        /// The i.
        /// </param>
        /// <param name="length">
        /// Generated sequence length.
        /// </param>
        /// <returns>
        /// The <see cref="Chain"/>.
        /// </returns>
        private Chain GenerateChain(Alphabet alphabet, int i, int length)
        {
            // next sequence
            var chain = new Chain(length);

            // Переменная для хранения остатка от деления на основание системы счисления (Мощность алфавита)
            int temp = i;

            // index of currently generated sequence
            int index = 0;

            // cycle through elements
            for (int j = length - 1; j >= 0; j--)
            {
                var element = (int)(temp / Math.Pow(alphabet.Cardinality, j));
                chain.Set(alphabet[element], index);
                temp = (int)(temp % Math.Pow(alphabet.Cardinality, j));
                index++;
            }

            return chain;
        }