Beispiel #1
0
        public void TestSequenceCTor()
        {
            byte[] b = new byte[6];
            b[0] = (byte)'C';
            b[1] = (byte)'A';
            b[2] = (byte)'A';
            b[3] = (byte)'G';
            b[4] = (byte)'C';
            b[5] = (byte)'T';

            string expectedSequence = "CAAGCT";
           ISequence sequence = new Sequence(Alphabets.DNA, b);

            string actual = "";
            foreach (byte bt in sequence)
            {
                actual += (char)bt;
            }
            Assert.AreEqual(expectedSequence, actual);

            Assert.AreEqual(sequence.Alphabet,Alphabets.DNA);
            Assert.AreEqual(sequence.Count, 6);
            // 
            // Test for indexer
            Assert.AreEqual(sequence[0], (byte)'C');
            Assert.AreEqual(sequence[1], (byte)'A');
            Assert.AreEqual(sequence[2], (byte)'A');
            Assert.AreEqual(sequence[3], (byte)'G');
            Assert.AreEqual(sequence[4], (byte)'C');
            Assert.AreEqual(sequence[5], (byte)'T');

        }
        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            if (sequenceTextBox.Text != null)
            {
                InitializeSaveSequenceFileDialog();

                if (saveSequenceFileDialog.ShowDialog() == true)
                {
                    try
                    {
                        Fragment toSave = new Fragment();
                        toSave.Name = sequenceName;
                        ISequence seq = new Bio.Sequence(Alphabets.DNA, sequence);
                        toSave.Sequence = seq;
                        toSave.Length   = sequence.Length;
                        ISequenceFormatter formatter = SequenceFormatters.FindFormatterByFileName(saveSequenceFileDialog.FileName);
                        formatter.Write(seq);
                        formatter.Close();
                        //toSave.Construct.SaveAsBio(saveSequenceFileDialog.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBoxResult result = ModernDialog.ShowMessage(ex.Message, "Exception", MessageBoxButton.OK);
                    }
                }
            }
        }
Beispiel #3
0
 public void TestSparseSequenceEnumerator()
 {
     int i = 0;
     ISequence seq = new Sequence(Alphabets.DNA, "ATGC");
     var sparseSeq = new SparseSequence(Alphabets.DNA, 0, seq);
     foreach (byte item in sparseSeq)
     {
         Assert.AreEqual(sparseSeq[i++], item);
     }
 }
Beispiel #4
0
        public void SimpleFindOneOutputPatternTest()
        {
            ISequence sequence = new Sequence(DnaAlphabet.Instance, "AGCT");
            IPatternFinder patternFinder = new BoyerMoore();
            IList<int> actual = patternFinder.FindMatch(sequence, "AGCT");

            HashSet<int> expected = new HashSet<int>();
            expected.Add(0);

            Assert.IsTrue(Compare(expected, actual));
        }
Beispiel #5
0
        public void TestTranscriptionAmbiguousData()
        {
            ISequence seq = new Sequence(Alphabets.AmbiguousDNA, "MSRWY");
            ISequence transcript = Transcription.Transcribe(seq);
            Assert.IsTrue(CompareSequenceToString("MSRWY", transcript));

            Assert.AreEqual(Alphabets.AmbiguousRNA, transcript.Alphabet);

            ISequence reverseTranscript = Transcription.ReverseTranscribe(transcript);
            Assert.IsTrue(CompareSequenceToString("MSRWY", reverseTranscript));
            Assert.AreEqual(Alphabets.AmbiguousDNA, reverseTranscript.Alphabet);
        }
Beispiel #6
0
        public void TestTranscription()
        {
            ISequence seq = new Sequence(Alphabets.DNA, "ATGGCG");
            ISequence transcript = Transcription.Transcribe(seq);
            Assert.IsTrue(CompareSequenceToString("AUGGCG", transcript));
            
            Assert.AreEqual(Alphabets.RNA, transcript.Alphabet);

            ISequence reverseTranscript = Transcription.ReverseTranscribe(transcript);
            Assert.IsTrue(CompareSequenceToString("ATGGCG", reverseTranscript));
            Assert.AreEqual(Alphabets.DNA, reverseTranscript.Alphabet);
        }
Beispiel #7
0
        public void TestTranscriptionSmallCase()
        {
            ISequence seq = new Sequence(Alphabets.DNA, "atggcg");
            ISequence transcript = Transcription.Transcribe(seq);
            Assert.IsTrue(CompareSequenceToString("auggcg", transcript));

            Assert.AreEqual(Alphabets.RNA, transcript.Alphabet);

            ISequence reverseTranscript = Transcription.ReverseTranscribe(transcript);
            Assert.IsTrue(CompareSequenceToString("atggcg", reverseTranscript));
            Assert.AreEqual(Alphabets.DNA, reverseTranscript.Alphabet);
        }
        public void PairwiseOverlapProteinSeqAffineGap()
        {
            string sequenceString1 = "HEAGAWGHEE";
            string sequenceString2 = "PAWHEAE";

            Sequence sequence1 = new Sequence(Alphabets.Protein, sequenceString1);
            Sequence sequence2 = new Sequence(Alphabets.Protein, sequenceString2);

            SimilarityMatrix sm = new SimilarityMatrix(SimilarityMatrix.StandardSimilarityMatrix.Blosum50);
            int gapPenalty = -8;

            PairwiseOverlapAligner overlap = new PairwiseOverlapAligner();
            overlap.SimilarityMatrix = sm;
            overlap.GapOpenCost = gapPenalty;
            overlap.GapExtensionCost = -1;
            IList<IPairwiseSequenceAlignment> result = overlap.Align(sequence1, sequence2);

            ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
            "{0}, Affine; Matrix {1}; GapOpenCost {2}; GapExtenstionCost {3}",
            overlap.Name, overlap.SimilarityMatrix.Name, overlap.GapOpenCost, overlap.GapExtensionCost));
            foreach (IPairwiseSequenceAlignment sequenceResult in result)
            {
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "score {0}", sequenceResult.PairwiseAlignedSequences[0].Score));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "input 0     {0}", sequenceResult.FirstSequence.ToString()));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "input 1     {0}", sequenceResult.SecondSequence.ToString()));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "result 0    {0}", sequenceResult.PairwiseAlignedSequences[0].FirstSequence.ToString()));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "result 1    {0}", sequenceResult.PairwiseAlignedSequences[0].SecondSequence.ToString()));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "consesus    {0}", sequenceResult.PairwiseAlignedSequences[0].Consensus.ToString()));
            }

            IList<IPairwiseSequenceAlignment> expectedOutput = new List<IPairwiseSequenceAlignment>();
            IPairwiseSequenceAlignment align = new PairwiseSequenceAlignment();
            PairwiseAlignedSequence alignedSeq = new PairwiseAlignedSequence();
            alignedSeq.FirstSequence = new Sequence(Alphabets.Protein, "GAWGHEE");
            alignedSeq.SecondSequence = new Sequence(Alphabets.Protein, "PAW-HEA");
            alignedSeq.Consensus = new Sequence(Alphabets.AmbiguousProtein, "XAWGHEX");
            alignedSeq.Score = 25;
            alignedSeq.FirstOffset = 0;
            alignedSeq.SecondOffset = 3;
            align.PairwiseAlignedSequences.Add(alignedSeq);
            expectedOutput.Add(align);
            Assert.IsTrue(CompareAlignment(result, expectedOutput));
        }
        /// <summary>
        /// The extract chains.
        /// </summary>
        /// <param name="subsequences">
        /// The subsequences.
        /// </param>
        /// <param name="chainId">
        /// The sequence id.
        /// </param>
        /// <returns>
        /// The <see cref="List{Chain}"/>.
        /// </returns>
        public Chain[] ExtractChains(Subsequence[] subsequences, long chainId)
        {
            var parentChain = commonSequenceRepository.ToLibiadaBaseChain(chainId).ToString();
            var sourceSequence = new Sequence(Alphabets.DNA, parentChain);
            var result = new Chain[subsequences.Length];

            for (int i = 0; i < subsequences.Length; i++)
            {
                result[i] = subsequences[i].Position.Count == 0
                        ? ExtractSimpleSubsequence(sourceSequence, subsequences[i])
                        : ExtractJoinedSubsequence(sourceSequence, subsequences[i]);
            }

            return result;
        }
Beispiel #10
0
        public void TestPcaStep3DeletionInReference()
        {
            Sequence r = new Sequence(DnaAlphabet.Instance, "CTACGATCGGGG");
            //                                               CTACGTGC         //   TGCGCA is deleted from reference
            //                                                    GCATCG
            //                                                       GGGG
            Sequence q = new Sequence(DnaAlphabet.Instance, "CTACGTGC");
            Sequence q2 = new Sequence(DnaAlphabet.Instance, "GCATCG");
            Sequence q3 = new Sequence(DnaAlphabet.Instance, "GGGG");

            ComparativeGenomeAssembler asm = new ComparativeGenomeAssembler() { LengthOfMum = 3 };
            var output = asm.Assemble(new List<ISequence> { r }, new List<ISequence> { q, q2, q3 });
            string res = new string(output.ElementAt(0).Select(a => (char)a).ToArray());

            Assert.AreEqual("CTACGTGCATCGGGG", res);
        }
        /// <summary>
        /// This method takes in a MBF sequence and converts it to BioPatML sequence.
        /// </summary>
        /// <param name="mbfseq">The MBF sequence one is interested in.</param>
        /// <returns>Returns the converted BioPatML sequence.</returns>
        public QUT.Bio.BioPatML.Sequences.Sequence ParseMBFSequence
                                                            (Sequence mbfseq)
        {
            GenBankMetadata metaData;

            #region If sequence is complex type e.g. Genbank file with features 
            if (mbfseq.Metadata.ContainsKey(Helper.GenBankMetadataKey))
            {
                //Retrieves our meta data out
                metaData = (GenBankMetadata)mbfseq.Metadata[Helper.GenBankMetadataKey];

                //Create our BioPatML sequence
                QUT.Bio.BioPatML.Sequences.Sequence bioSequence = new QUT.Bio.BioPatML.Sequences.Sequence
                                            (ParseAlphabet(mbfseq), mbfseq.ToString(),
                                                        IsCircularStrand(metaData.Locus));

                #region Top the BioPatML Sequence with Feature data and sequence name

                //Add features to sequence
                bioSequence.AddFeatures(ExtractFeatures(metaData));

                //Add mbf sequence name to BioPatML sequence
                //Create annotation to put in our sequence data like name
                AnnotationList jacobiMeta = new AnnotationList();
                jacobiMeta.Add("SequenceName", metaData.Locus.Name);
                bioSequence.AddAnnotations(jacobiMeta);

                #endregion

                return bioSequence;

            }
            #endregion
            #region Else we assume it is a simple type e.g. Fasta files
            else
            {
                QUT.Bio.BioPatML.Sequences.Sequence bioSequence = new QUT.Bio.BioPatML.Sequences.Sequence
                                            (ParseAlphabet(mbfseq), mbfseq.ToString(),
                                                        false);

                AnnotationList jacobiMeta = new AnnotationList();
                jacobiMeta.Add("SequenceName", mbfseq.DisplayID);
                bioSequence.AddAnnotations(jacobiMeta);
                return bioSequence;
            }
            #endregion
        }
Beispiel #12
0
        public void MultipleFindOneOutputPatternTest()
        {
            ISequence sequence = new Sequence(DnaAlphabet.Instance, "AGCTAGGTTGGCC");
            IList<string> patterns = new List<string>();
            patterns.Add("AGCT");
            patterns.Add("AAAAA");
            IPatternFinder patternFinder = new BoyerMoore();
            IDictionary<string, IList<int>> actual = patternFinder.FindMatch(sequence, patterns);

            IDictionary<string, HashSet<int>> expected = new Dictionary<string, HashSet<int>>();
            HashSet<int> indices = new HashSet<int>();
            indices.Add(0);
            expected.Add("AGCT", indices);

            indices = new HashSet<int>();
            expected.Add("AAAAA", indices);

            Assert.IsTrue(Compare(expected, actual));
        }
Beispiel #13
0
        public void TestTranscriptionInvalidData()
        {
            try
            {
                ISequence seq = new Sequence(Alphabets.AmbiguousRNA, "MSRWY");
                ISequence transcript = Transcription.Transcribe(seq);
                Assert.Fail();
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                ISequence seq = new Sequence(Alphabets.RNA, "AUGGCG");
                ISequence transcript = Transcription.Transcribe(seq);
                Assert.Fail();
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                ISequence seq = new Sequence(Alphabets.DNA, "ATGGCG");
                ISequence transcript = Transcription.ReverseTranscribe(seq);
                Assert.Fail();
            }
            catch (InvalidOperationException)
            {
            }

            try
            {
                ISequence seq = new Sequence(Alphabets.AmbiguousDNA, "MSRWY");
                ISequence transcript = Transcription.ReverseTranscribe(seq);
                Assert.Fail();
            }
            catch (InvalidOperationException)
            {
            }
        }
Beispiel #14
0
        public CCSDataSet(Sequence ccs, List<Sequence> subreads, BWAPairwiseAlignment aln)
        {
            // Call Variants
            var results = VariantCaller.LeftAlignIndelsAndCallVariants (aln);
            Variants = results.Item2;
            Variants.ForEach (p => {
                p.StartPosition += aln.AlignedSAMSequence.Pos;
                p.RefName = aln.Reference;
            });

            // Get the ungapped reference
            var ccs_aligned = results.Item1.SecondSequence;

            // Generate an ungapped reference
            var refseq = results.Item1.PairwiseAlignedSequences.First().FirstSequence;
            var reference = new Sequence (DnaAlphabet.Instance,
                                refseq.Where (bp => bp != '-').ToArray (),
                                false)
            { ID = aln.Reference + "/" + aln.AlignedSAMSequence.Pos + "-" + aln.AlignedSAMSequence.RefEndPos };

            var reference_rc = reference.GetReverseComplementedSequence () as Sequence;

            Reads = subreads.Select(z => new AlignedSequence(z, reference, reference_rc)).Where( x => (Math.Abs((x.Sequence.Length - reference.Count)) / (double) reference.Count) < 0.2).ToList();

            Reads.Insert (0, new AlignedSequence (reference, reference, reference_rc));

            ccs.ID = "CCS";
            Reads.Insert(1, new AlignedSequence(ccs, reference, reference_rc));

            // Now to rejigger the alignments
            int[] metaOffSets = Enumerable.Range(0, (int)reference.Count).
                Select (i => Reads.Max( r => r.GetInsertsBeforePosition(i))).
                ToArray();
            Reads.ForEach(r => {
                r.ReJiggerAlignment(metaOffSets);
                Console.WriteLine(r.Sequence);});

            CCS = ccs;
            Reference = reference;
            Aln = aln;
        }
Beispiel #15
0
        public void TestPcaStep2WithTwoReads()
        {
            ComparativeGenomeAssembler asm = new ComparativeGenomeAssembler() { LengthOfMum = 9, KmerLength = 9 };

            Sequence q = new Sequence(DnaAlphabet.Instance, "AACCTTGGCC");
            q.ID = ">read.F:TestPcaStep2WithTwoReads";

            Sequence p = new Sequence(DnaAlphabet.Instance, "GGGGGGGGGG");
            p.ID = ">read.R:TestPcaStep2WithTwoReads";

            CloneLibrary.Instance.AddLibrary("TestPcaStep2WithTwoReads", (float)61, (float)1);

            TestPcaAssemble(asm,
                new List<Sequence>{
                    new Sequence(DnaAlphabet.Instance, "AACCTTGGCCCCCACGATCGCGCTAGATCGCATCGATCCCCAACCTTGGCCGGGGGGGGGG", false)
                },
                new List<ISequence> { q,p },
                new List<string> { 
                    "AACCTTGGCC",
                    "GGGGGGGGGG"
                });
        }
        private void save_Click(object sender, RoutedEventArgs e)
        {
            if (changeTextBox.Text != null)
            {
                InitializeSaveSequenceFileDialog();

                if (saveEditSequenceFileDialog.ShowDialog() == true)
                {
                    try
                    {
                        string             sequenceToSave = changeTextBox.Text;
                        ISequence          seq            = new Bio.Sequence(Alphabets.DNA, sequenceToSave);
                        ISequenceFormatter formatter      = SequenceFormatters.FindFormatterByFileName(saveEditSequenceFileDialog.FileName);
                        formatter.Write(seq);
                        formatter.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBoxResult result = ModernDialog.ShowMessage(ex.Message, "Exception", MessageBoxButton.OK);
                    }
                }
            }
        }
Beispiel #17
0
 public static void Test1BPDeletionCall()
 {
     string seq1seq = "ATACCCCTT";
     string seq2seq = "ATA-CCCTT".Replace("-", String.Empty);
     int[] seq2qual = new int[] { 30, 30, 30, 2, 30, 30, 30, 30 };
     var refseq = new Sequence(AmbiguousDnaAlphabet.Instance, seq1seq, false);
     var query = new Sequence (AmbiguousDnaAlphabet.Instance, seq2seq, false);
     NeedlemanWunschAligner aligner = new NeedlemanWunschAligner ();
     var aln = aligner.Align (refseq, query).First();
     // Need to add in the QV Values.
     ConvertAlignedSequenceToQualSeq(aln, seq2qual);
     var variants = VariantCaller.CallVariants (aln);
     Assert.AreEqual (variants.Count, 1);
     var variant = variants.First ();
     Assert.AreEqual (2, variant.QV);
     Assert.AreEqual (2, variant.StartPosition);
     Assert.AreEqual (VariantType.INDEL, variant.Type);
     var vi = variant as IndelVariant;
     Assert.AreEqual ("C", vi.InsertedOrDeletedBases);
     Assert.AreEqual ('C', vi.HomopolymerBase);
     Assert.AreEqual (4, vi.HomopolymerLengthInReference);
     Assert.AreEqual (true, vi.InHomopolymer);
     Assert.AreEqual (vi.InsertionOrDeletion, IndelType.Deletion);
 }
        public AlignedSequence(Sequence read, Sequence reference, Sequence reference_rc)
        {
            // Align the read and reference
            var algo = new NeedlemanWunschAligner ();
            algo.GapOpenCost = -20;
            algo.GapExtensionCost = -19;
            algo.SimilarityMatrix = new DiagonalSimilarityMatrix (20, -20);
            var aln = algo.Align (read, reference).First ().AlignedSequences.First () as PairwiseAlignedSequence;
            var reverse_aln = algo.Align (read, reference_rc).First ().AlignedSequences.First () as PairwiseAlignedSequence;
            Sequence Ref, Query;
            Name = read.ID;
            if (aln.Score < reverse_aln.Score) {
                aln = reverse_aln;
                Query = (aln.Sequences [0] as Sequence).GetReverseComplementedSequence () as Sequence;
                Ref = (aln.Sequences [1] as Sequence).GetReverseComplementedSequence () as Sequence;
                Name = Name + "_RC";
            } else {
                Query = (aln.Sequences [0] as Sequence);
                Ref = (aln.Sequences [1] as Sequence);
            }

            // Now calculate the offsets
            OffSets = new int[reference.Count];
            int refBases = -1;
            for (int i = 0; i < Ref.Count; i++) {
                if (Ref [i] != '-') {
                    refBases++;
                    OffSets [refBases] = i;
                }
            }
            Sequence = Query.ConvertToString ();

            //Console.WriteLine (read.ID);
            //Console.WriteLine ((aln.Sequences [0] as Sequence).ConvertToString ());
            //Console.WriteLine ((aln.Sequences [1] as Sequence).ConvertToString ());
        }
        public void ValidateBioHPCCtor()
        {
            // Gets the search query parameter and their values.
            string alphabetName = utilityObj.xmlUtil.GetTextValue(Constants.BioHPCAsynchronousResultsNode, Constants.AlphabetNameNode);
            string querySequence = utilityObj.xmlUtil.GetTextValue(Constants.BioHPCAsynchronousResultsNode, Constants.QuerySequency);
            string queryDatabaseValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode,
                Constants.DatabaseValue);
            string email = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode,
                Constants.EmailAdress);
            string queryProgramValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode,
                Constants.ProgramValue);
            string queryDatabaseParameter = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode,
                Constants.DatabaseParameter);
            string queryProgramParameter = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode,
                Constants.ProgramParameter);
            string expect = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.Expectparameter);
            string emailNotify = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.EmailNotifyParameterNode);
            string jobName = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.JobNameParameterNode);
            string expectValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.ExpectNode);
            string emailNotifyValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.EmailNotifyNode);
            string jobNameValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.JobNameNode);

            Sequence seq = new Sequence(Utility.GetAlphabet(alphabetName),
                querySequence);

            // create BioHPC Blast Web Service object.
            IBlastServiceHandler service = new BioHPCBlastHandler();
            ConfigParameters configParams = new ConfigParameters();
            configParams.EmailAddress = email;
            configParams.Password = string.Empty;
            //configParams.UseBrowserProxy = true;
            service.Configuration = configParams;

            BlastParameters searchParams = new BlastParameters();

            // Set Request parameters.
            searchParams.Add(queryDatabaseParameter, queryDatabaseValue);
            searchParams.Add(queryProgramParameter, queryProgramValue);
            searchParams.Add(expect, expectValue);
            searchParams.Add(emailNotify, emailNotifyValue);
            searchParams.Add(jobName, jobNameValue);

            try
            {
                // Create a request without passing sequence.
                string reqId = service.SubmitRequest(seq, searchParams);
                Assert.IsNotNull(reqId);
            }
            catch (WebException ex)
            {
                Assert.Fail();
                Console.WriteLine(string.Format((IFormatProvider)null,
                    "BioHPC Blast Bvt : Connection not successful with error '{0}'",
                    ex.Message));
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "BioHPC Blast Bvt : Connection not successful with error '{0}'",
                    ex.Message));
            }
            finally
            {
                if (service != null)
                    ((IDisposable)service).Dispose();
            }
        }
        /// <summary>
        /// Validate Cancel submitted job by passing job id.
        /// <param name="nodeName">different alphabet node name</param>
        /// </summary>
        void ValidateCancelSubmittedJob(
            string nodeName,
            RequestType type)
        {
            // Gets the search query parameter and their values.
            string alphabetName = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.AlphabetNameNode);
            string querySequence = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.QuerySequency);
            string queryDatabaseValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.DatabaseValue);
            string email = Constants.EmailForWS; ;
            string queryProgramValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ProgramValue);
            string queryDatabaseParameter = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.DatabaseParameter);
            string queryProgramParameter = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ProgramParameter);
            string expect = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.Expectparameter);
            string emailNotify = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailNotifyParameterNode);
            string jobName = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.JobNameParameterNode);
            string expectValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ExpectNode);
            string emailNotifyValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailNotifyNode);
            string jobNameValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.JobNameNode);

            // Set Blast Parameters
            Sequence seq = new Sequence(Utility.GetAlphabet(alphabetName),
                querySequence);

            IBlastServiceHandler service = new BioHPCBlastHandler();
            ConfigParameters configParameters = new ConfigParameters();
            configParameters.EmailAddress = email;
            configParameters.Password = String.Empty;
            configParameters.UseBrowserProxy = true;
            service.Configuration = configParameters;

            BlastParameters searchParams = new BlastParameters();

            // Set Request parameters.
            searchParams.Add(queryDatabaseParameter, queryDatabaseValue);
            searchParams.Add(queryProgramParameter, queryProgramValue);
            searchParams.Add(expect, expectValue);
            searchParams.Add(emailNotify, emailNotifyValue);
            searchParams.Add(jobName, jobNameValue);

            string reqId = String.Empty;

            // Waiting for the any previous request to get completed.
            Thread.Sleep(150000);

            // Create a request without passing sequence.
            switch (type)
            {
                case RequestType.StrSubmit:
                    reqId = service.SubmitRequest(seq, searchParams);
                    break;
                case RequestType.LstSubmit:
                    IList<ISequence> lstSeq = new List<ISequence>();
                    lstSeq.Add(seq);
                    reqId = service.SubmitRequest(lstSeq, searchParams);
                    break;
            }

            // Cancel subitted job.
            bool result = service.CancelRequest(reqId);

            // validate the cancelled job.
            Assert.IsTrue(result);

            Console.WriteLine(string.Concat(
                "BioHPC Blast Bvt : Submitted job cancelled was successfully. ",
                queryProgramValue));
        }
        /// <summary>
        /// Validate general http request status by
        /// differnt parameters for BioHPC Blast Web Service.
        /// <param name="nodeName">different alphabet node name</param>
        /// </summary>
        void ValidateBioHPCGeneralGetRequestStatusMethod(string nodeName,
            string moleculeType)
        {
            // Gets the search query parameter and their values.
            string alphabetName = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.AlphabetNameNode);
            string querySequence = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.QuerySequency);
            string queryDatabaseValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.DatabaseValue);
            string queryProgramValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ProgramValue);
            string queryDatabaseParameter = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.DatabaseParameter);
            string queryProgramParameter = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ProgramParameter);
            string email = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailAdress);
            string expect = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.Expectparameter);
            string emailNotify = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailNotifyParameterNode);
            string jobName = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.JobNameParameterNode);
            string expectValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ExpectNode);
            string emailNotifyValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailNotifyNode);
            string jobNameValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.JobNameNode);

            // Create a sequence.
            Sequence seq = new Sequence(Utility.GetAlphabet(alphabetName),
                querySequence);

            // Set Service confiruration parameters true.
            IBlastServiceHandler service = new BioHPCBlastHandler();

            ConfigParameters configParameters = new ConfigParameters();
            configParameters.EmailAddress = email;
            configParameters.Password = String.Empty;
            configParameters.UseBrowserProxy = true;
            service.Configuration = configParameters;

            // Create search parameters object.
            BlastParameters queryParams = new BlastParameters();

            // Add mandatory parameter values to search query parameters.
            queryParams.Add(queryDatabaseParameter, queryDatabaseValue);
            queryParams.Add(queryProgramParameter, queryProgramValue);
            queryParams.Add(expect, expectValue);
            queryParams.Add(emailNotify, emailNotifyValue);
            queryParams.Add(jobName, jobNameValue);

            // Create a request 
            // Waiting for the any previous request to get completed.
            Thread.Sleep(150000);
            string reqId = service.SubmitRequest(seq, queryParams);

            // validate request identifier.
            Assert.IsNotNull(reqId);

            // submit request identifier and get the status
            ServiceRequestInformation reqInfo =
                service.GetRequestStatus(reqId);

            // Validate job status.
            if (reqInfo.Status != ServiceRequestStatus.Waiting
                && reqInfo.Status != ServiceRequestStatus.Ready
                && reqInfo.Status != ServiceRequestStatus.Queued)
            {
                string error = ApplicationLog.WriteLine(string.Concat(
                    "Unexpected error ", reqInfo.Status));
                Assert.Fail(error);
                Console.WriteLine(string.Concat(
                    "Unexpected error ", reqInfo.Status));
            }
            else
            {
                Console.WriteLine(string.Concat(
                    "Request status ", reqInfo.Status));
            }
        }
        /// <summary>
        /// Validate general fetching results.by passing 
        /// differnt parameters for BioHPC Blast web service.
        /// <param name="nodeName">xml node name.</param>
        /// <param name="isFetchSynchronous">Is Fetch Synchronous?</param>
        /// </summary>
        void ValidateBioHPCBlastResultsFetch(
            string nodeName, bool isFetchSynchronous)
        {
            // Gets the search query parameter and their values.
            string alphabetName = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.AlphabetNameNode);
            string querySequence = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.QuerySequency);
            string queryDatabaseValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.DatabaseValue);
            string email = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailAdress);
            string queryProgramValue = utilityObj.xmlUtil.GetTextValue(
                nodeName,
                Constants.ProgramValue);
            string queryDatabaseParameter = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.DatabaseParameter);
            string queryProgramParameter = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ProgramParameter);
            string expectedHitId = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.HitID);
            string expectedAccession = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.HitAccession);
            string expectedResultCount = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ResultsCount);
            string expectedHitsCount = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.HitsCount);
            string expectedEntropyStatistics =
                utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EntropyStatistics);
            string expectedKappaStatistics = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.KappaStatistics);
            string expectedLambdaStatistics = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.LambdaStatistics);
            string expectedLength = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.Length);
            int maxAttempts = int.Parse(utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.MaxAttemptsNode), (IFormatProvider)null);
            int waitingTime = int.Parse(utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.WaitTimeNode), (IFormatProvider)null);
            string expect = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.Expectparameter);
            string emailNotify = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailNotifyParameterNode);
            string jobName = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.JobNameParameterNode);
            string expectValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.ExpectNode);
            string emailNotifyValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.EmailNotifyNode);
            string jobNameValue = utilityObj.xmlUtil.GetTextValue(
                nodeName, Constants.JobNameNode);

            object responseResults = null;
            Sequence seq = new Sequence(
                Utility.GetAlphabet(alphabetName),
                querySequence);

            // create BioHPC Blast Web Service object.
            IBlastServiceHandler service = new BioHPCBlastHandler();
            ConfigParameters configPams = new ConfigParameters();
            configPams.EmailAddress = email;
            configPams.Password = String.Empty;
            configPams.UseBrowserProxy = true;
            service.Configuration = configPams;

            BlastParameters searchParams = new BlastParameters();

            // Set Request parameters.
            searchParams.Add(queryDatabaseParameter, queryDatabaseValue);
            searchParams.Add(queryProgramParameter, queryProgramValue);
            searchParams.Add(expect, expectValue);
            searchParams.Add(emailNotify, emailNotifyValue);
            searchParams.Add(jobName, jobNameValue);

            // Create a request without passing sequence.
            string reqId = service.SubmitRequest(seq, searchParams);

            // validate request identifier.
            Assert.IsNotNull(reqId);

            ServiceRequestInformation info = service.GetRequestStatus(reqId);
            if (info.Status != ServiceRequestStatus.Waiting
                && info.Status != ServiceRequestStatus.Ready
                && info.Status != ServiceRequestStatus.Queued)
            {
                string err =
                    ApplicationLog.WriteLine("Unexpected status: '{0}'",
                    info.Status);
                Assert.Fail(err);
            }

            // get async results, poll until ready
            int attempt = 1;
            while (attempt <= maxAttempts
                    && info.Status != ServiceRequestStatus.Error
                    && info.Status != ServiceRequestStatus.Ready)
            {
                ++attempt;
                if (isFetchSynchronous)
                {
                    info = service.GetRequestStatus(reqId);
                    Thread.Sleep(
                        info.Status == ServiceRequestStatus.Waiting
                        || info.Status == ServiceRequestStatus.Queued
                        ? waitingTime * attempt : 0);
                }
                else
                {
                    Thread.Sleep(
                        info.Status == ServiceRequestStatus.Waiting
                        || info.Status == ServiceRequestStatus.Queued ?
                        waitingTime * attempt : 0);
                    info = service.GetRequestStatus(reqId);
                }

            }

            IBlastParser blastXmlParser = new BlastXmlParser();
            responseResults = blastXmlParser.Parse(
                    new StringReader(service.GetResult(reqId, searchParams)));


            Assert.IsNotNull(responseResults);
            List<BlastResult> eBlastResults =
                responseResults as List<BlastResult>;
            Assert.IsNotNull(eBlastResults);
            Assert.AreEqual(eBlastResults.Count.ToString(
                (IFormatProvider)null), expectedResultCount);
            Assert.AreEqual(eBlastResults[0].Records.Count.ToString((
                IFormatProvider)null), expectedResultCount);
            BlastSearchRecord record = eBlastResults[0].Records[0];
            Assert.AreEqual(record.Statistics.Kappa.ToString(
                (IFormatProvider)null), expectedKappaStatistics);
            Assert.AreEqual(record.Statistics.Lambda.ToString(
                (IFormatProvider)null), expectedLambdaStatistics);
            Assert.AreEqual(record.Statistics.Entropy.ToString(
                (IFormatProvider)null), expectedEntropyStatistics);
            Assert.AreEqual(record.Hits.Count.ToString(
                (IFormatProvider)null), expectedHitsCount);
            Hit hit = record.Hits[0];
            Assert.AreEqual(hit.Accession, expectedAccession);
            Assert.AreEqual(hit.Length.ToString((IFormatProvider)null),
                expectedLength);
            Assert.AreEqual(hit.Id.ToString((IFormatProvider)null),
                expectedHitId);
            Assert.AreEqual(hit.Hsps.Count.ToString((IFormatProvider)null),
                expectedResultCount);
            Console.WriteLine(string.Format((IFormatProvider)null,
               "BioHPC Blast BVT : Hits count '{0}'.", eBlastResults.Count));
            Console.WriteLine(string.Format((IFormatProvider)null,
                "BioHPC Blast BVT : Accession '{0}'.", hit.Accession));
            Console.WriteLine(string.Format((IFormatProvider)null,
                "BioHPC Blast BVT : Hit Id '{0}'.", hit.Id));
            Console.WriteLine(string.Format((IFormatProvider)null,
                "BioHPC Blast BVT : Hits Count '{0}'.", hit.Hsps.Count));
            // Validate the results Synchronously with the results got earlier.
            if (isFetchSynchronous)
            {
                IList<BlastResult> syncBlastResults =
                    service.FetchResultsSync(reqId, searchParams) as List<BlastResult>;
                Assert.IsNotNull(syncBlastResults);
                if (null != eBlastResults[0].Records[0].Hits
                    && 0 < eBlastResults[0].Records[0].Hits.Count
                    && null != eBlastResults[0].Records[0].Hits[0].Hsps
                    && 0 < eBlastResults[0].Records[0].Hits[0].Hsps.Count)
                {
                    Assert.AreEqual(
                        eBlastResults[0].Records[0].Hits[0].Hsps[0].QuerySequence,
                        syncBlastResults[0].Records[0].Hits[0].Hsps[0].QuerySequence);
                }
                else
                {
                    ApplicationLog.WriteLine(
                        "No significant hits found with the these parameters.");
                    Console.WriteLine(
                        "No significant hits found with the these parameters.");
                }
            }
        }
        public void InValidateSubSequenceWithComplimentOperator()
        {
            // Get Values from XML node.
            string sequence = utilityObj.xmlUtil.GetTextValue(
                Constants.InvalidLocationWithComplementOperatorNode,
                Constants.ExpectedSequence);
            string location = utilityObj.xmlUtil.GetTextValue(
                Constants.InvalidLocationWithComplementOperatorNode,
                Constants.Location);
            string alphabet = utilityObj.xmlUtil.GetTextValue(
                Constants.InvalidLocationWithComplementOperatorNode,
                Constants.AlphabetNameNode);

            // Create a sequence object.
            ISequence seqObj = new Sequence(Utility.GetAlphabet(alphabet),
                sequence);

            // Build a location.
            ILocationBuilder locBuilder = new LocationBuilder();
            ILocation loc = locBuilder.GetLocation(location);
            LocationResolver locResolver = new LocationResolver();

            // Get sequence using location of the sequence with operator.
            try
            {
                loc.GetSubSequence(seqObj);
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                LogExceptionMessage();
            }

            // Validate sub sequence exception for an invalid sequence.
            try
            {
                locResolver.GetSubSequence(loc, null);
                Assert.Fail();
            }
            catch (ArgumentNullException)
            {
                LogExceptionMessage();
            }

            // Validate GetSubSequence method with null location.
            try
            {
                locResolver.GetSubSequence(null, seqObj);
                Assert.Fail();
            }
            catch (ArgumentNullException)
            {
                LogExceptionMessage();
            }

            // Validate sub sequence exception for an invalid sequence.
            try
            {
                locResolver.GetSubSequence(loc, null, null);
                Assert.Fail();
            }
            catch (ArgumentNullException)
            {
                LogExceptionMessage();
            }

            // Validate GetSubSequence method with null location.
            try
            {
                locResolver.GetSubSequence(null, seqObj, null);
                Assert.Fail();
            }
            catch (ArgumentNullException)
            {
                LogExceptionMessage();
            }

            // Validate GetSubSequence method with null location.
            try
            {
                loc.GetSubSequence(null);
                Assert.Fail();
            }
            catch (ArgumentNullException)
            {
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                       "GenBankFeatures P2 : Validate the exception successfully"));
            }

        }
Beispiel #24
0
        /// <summary>
        /// Return a new sequence representing this sequence with the orientation reversed.
        /// </summary>
        public ISequence GetReversedSequence()
        {
            byte[] values = new byte[this.Count];

            Helper.Copy(this._sequenceData, values, this._sequenceData.GetLongLength());

            Array.Reverse(values);
            Sequence seq = new Sequence { _sequenceData = values, Alphabet = this.Alphabet, ID = this.ID, Count = this.Count };
            if (this._metadata != null)
                seq._metadata = new Dictionary<string, object>(this._metadata);

            return seq;
        }
        /// <summary>
        /// Calculation method.
        /// </summary>
        /// <param name="chains">
        /// The chains.
        /// </param>
        /// <param name="calculators">
        /// The calculators.
        /// </param>
        /// <param name="links">
        /// The links.
        /// </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(Chain[][] chains, IFullCalculator[] calculators, Link[] links, bool rotate, bool complementary, uint? rotationLength)
        {
            var characteristics = new double[chains.Length][];

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

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

                    if (rotate)
                    {
                        var building = chains[i][j].Building.Rotate(rotationLength ?? 0);
                        var newSequence = building.Select(t => new ValueInt(t)).Cast<IBaseObject>().ToList();
                        chains[i][j] = new Chain(newSequence);
                    }

                    chains[i][j].FillIntervalManagers();

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

            return characteristics;
        }
Beispiel #26
0
        /// <summary>
        /// Return a new sequence representing a range (subsequence) of this sequence.
        /// </summary>
        /// <param name="start">The index of the first symbol in the range.</param>
        /// <param name="length">The number of symbols in the range.</param>
        /// <returns>The sub-sequence.</returns>
        public ISequence GetSubSequence(long start, long length)
        {
            if (start >= this.Count)
            {
                throw new ArgumentOutOfRangeException("start");
            }

            if (start + length > this.Count)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            byte[] subSequence = new byte[length];
            for (long index = 0; index < length; index++)
            {
                subSequence[index] = this._sequenceData[start + index];
            }

            Sequence seq = new Sequence { _sequenceData = subSequence, Alphabet = this.Alphabet, ID = this.ID, Count = subSequence.Length };
            if (this._metadata != null)
                seq._metadata = new Dictionary<string, object>(this._metadata);
            return seq;
        }
Beispiel #27
0
        /// <summary>
        /// Return a new sequence representing the reverse complement of this sequence.
        /// </summary>
        public ISequence GetReverseComplementedSequence()
        {
            if (!this.Alphabet.IsComplementSupported)
            {
                throw new InvalidOperationException(Properties.Resource.ComplementNotFound);
            }

            byte[] reverseComplemented = new byte[this.Count];
            this.Alphabet.TryGetComplementSymbol(this._sequenceData, out reverseComplemented);
            Array.Reverse(reverseComplemented);
            Sequence seq = new Sequence { _sequenceData = reverseComplemented, Alphabet = this.Alphabet, ID = this.ID, Count = this.Count };
            if (this._metadata != null)
                seq._metadata = new Dictionary<string, object>(this._metadata);

            return seq;
        }
Beispiel #28
0
        /// <summary>
        /// Convert given range containing any sequence (other than BED) to Bio.Sequence object
        /// </summary>
        /// <param name="userSelectedRanges">Range of cells</param>
        /// <param name="treatBlankCellsAsGaps">Flag to treat blank cells as gaps</param>
        /// <param name="alphabetType">Molecule Type</param>
        /// <param name="sequenceId">Sequence Identifier</param>
        /// <returns>Sequence object</returns>
        public static ISequence RangeToSequence(IList<Range> userSelectedRanges, bool treatBlankCellsAsGaps, string alphabetType, string sequenceId)
        {
            StringBuilder builder = new StringBuilder();
            string cellValue = string.Empty;

            foreach (Range range in userSelectedRanges)
            {
                foreach (Range currentCell in range.Cells)
                {
                    // if cell has value, and its row and column is not hidden
                    if (currentCell != null && currentCell.Value2 != null && !(currentCell.EntireColumn.Hidden || currentCell.EntireRow.Hidden))
                    {
                        cellValue = currentCell.Value2.ToString();
                        if (string.IsNullOrWhiteSpace(cellValue))
                        {
                            if (treatBlankCellsAsGaps)
                            {
                                builder.Append(Gap);
                            }
                        }
                        else
                        {
                            builder.Append(cellValue);
                        }
                    }
                    else if (treatBlankCellsAsGaps && !(currentCell.EntireColumn.Hidden || currentCell.EntireRow.Hidden))
                    {
                        builder.Append(Gap);
                    }
                }
            }

            string sequenceString = builder.ToString();

            IAlphabet alphabet = null;
            foreach (IAlphabet alphabetSet in Alphabets.All)
            {
                if (0 == string.Compare(alphabetSet.Name, alphabetType, true))
                {
                    alphabet = alphabetSet;
                    break;
                }
            }

            if (null == alphabet)
            {
                byte[] sequenceBytes = sequenceString.Select(a => (byte)a).ToArray();
                alphabet = Alphabets.AutoDetectAlphabet(sequenceBytes, 0, sequenceBytes.Length, null);
            }

            if (alphabet == null)
            {
                throw new Exception(Properties.Resources.CannotFindMatchingAlphabet);
            }

            Sequence sequence = new Sequence(alphabet, sequenceString);
            sequence.ID = sequenceId;
            return sequence;
        }
        public void InValidateSubSequenceWithInvalidAccessionID()
        {
            // Get Values from XML node.
            string sequence = utilityObj.xmlUtil.GetTextValue(
                Constants.LocationWithDotOperatorNode,
                Constants.ExpectedSequence);
            string location = utilityObj.xmlUtil.GetTextValue(
                Constants.LocationWithDotOperatorNode,
                Constants.Location);
            string alphabet = utilityObj.xmlUtil.GetTextValue(
                Constants.LocationWithDotOperatorNode,
                Constants.AlphabetNameNode);

            // Create a sequence object.
            ISequence seqObj = new Sequence(Utility.GetAlphabet(alphabet),
                sequence);

            // Build a location.
            ILocationBuilder locBuilder = new LocationBuilder();
            ILocation loc = locBuilder.GetLocation(location);
            loc.Accession = "Invalid";

            // Get sequence using location of the sequence with operator.
            try
            {
                loc.GetSubSequence(seqObj);
                Assert.Fail();
            }
            catch (ArgumentException)
            {
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "GenBankFeatures P2 : Validate the exception successfully"));
            }

            Dictionary<string, ISequence> refSeq = null;

            // Validate GetSubSequence method with null location.
            try
            {
                loc.GetSubSequence(null, refSeq);
                Assert.Fail();
            }
            catch (ArgumentNullException)
            {
                ApplicationLog.WriteLine(string.Format((IFormatProvider)null,
                    "GenBankFeatures P2 : Validate the exception successfully"));
            }

        }
Beispiel #30
0
        /// <summary>
        /// Given two byte arrays representing a pairwise alignment, shift them so 
        /// that all deletions start as early as possible.  For example:
        /// 
        /// <code>
        /// TTTTAAAATTTT  -> Converts to ->  TTTTAAAATTTT
        /// TTTTAA--TTTT                     TTTT--AATTTT
        /// </code>
        /// 
        /// This function takes a IPairwiseSequenceAlignment and assumes that the first sequence is the reference and second
        /// sequence is the query.  It returns a new Pairwise sequence alignment with all of the indels left aligned as well as a list of variants.
        /// </summary>
        /// <param name="aln">Aln. The second sequence should be of type QualitativeSequence or Sequence</param>
        /// <param name="callVariants">callVariants.  If true, it will call variants, otherwise the second half of tuple will be null. </param>
        public static Tuple<IPairwiseSequenceAlignment, List<Variant>> LeftAlignIndelsAndCallVariants(IPairwiseSequenceAlignment aln, bool callVariants = true) {

            if (aln == null) {
                throw new NullReferenceException ("aln");
            }
            if (aln.PairwiseAlignedSequences == null || aln.PairwiseAlignedSequences.Count != 1) {
                throw new ArgumentException ("The pairwise aligned sequence should only have one alignment");
            }
            var frstAln = aln.PairwiseAlignedSequences.First ();
            var seq1 = frstAln.FirstSequence;
            var seq2 = frstAln.SecondSequence;
            if (seq1 == null) {
                throw new NullReferenceException ("seq1");
            } else if (seq2 == null) {
                throw new NullReferenceException ("seq2");
            }

            //TODO: Might implement an ambiguity check later.
            #if FALSE
            if (seq1.Alphabet.HasAmbiguity || seq2.Alphabet.HasAmbiguity) {
                throw new ArgumentException ("Cannot left align sequences with ambiguous symbols.");
            }
            #endif

            // Note we have to copy unless we can guarantee the array will not be mutated.
            byte[] refseq = seq1.ToArray ();
            ISequence newQuery;
            List<Variant> variants = null;
            // Call variants for a qualitative sequence
            if (seq2 is QualitativeSequence) {
                var qs = seq2 as QualitativeSequence;
                var query = Enumerable.Zip (qs, qs.GetQualityScores (), (bp, qv) => new BPandQV (bp, (byte)qv, false)).ToArray ();
                AlignmentUtils.LeftAlignIndels (refseq, query);
                AlignmentUtils.VerifyNoGapsOnEnds (refseq, query);
                if (callVariants) {
                    variants = VariantCaller.CallVariants (refseq, query, seq2.IsMarkedAsReverseComplement());
                }
                var newQueryQS = new QualitativeSequence (qs.Alphabet, 
                    qs.FormatType,
                    query.Select (z => z.BP).ToArray (),
                    query.Select (p => p.QV).ToArray (),
                    false);
                newQueryQS.Metadata = seq2.Metadata;
                newQuery = newQueryQS;
                
            } else if (seq2 is Sequence) {  // For a sequence with no QV values.
                var qs = seq2 as Sequence;
                var query = qs.Select (v => new BPandQV (v, 0, false)).ToArray();
                AlignmentUtils.LeftAlignIndels (refseq, query);
                AlignmentUtils.VerifyNoGapsOnEnds (refseq, query);
                // ISequence does not have a setable metadata
                var newQueryS = new Sequence(qs.Alphabet, query.Select(z=>z.BP).ToArray(), false);
                newQueryS.Metadata = seq2.Metadata;
                if (callVariants) {
                    variants = VariantCaller.CallVariants (refseq, query, seq2.IsMarkedAsReverseComplement());
                }
                newQuery = newQueryS;
            } else {
                throw new ArgumentException ("Can only left align indels if the query sequence is of type Sequence or QualitativeSequence.");
            }

            if (aln.FirstSequence != null && aln.FirstSequence.ID != null) {
                foreach (var v in variants) {
                    v.RefName = aln.FirstSequence.ID;
                }
            }

            var newRef = new Sequence (seq1.Alphabet, refseq, false);
            newRef.ID = seq1.ID;
            newRef.Metadata = seq1.Metadata;

            newQuery.ID = seq2.ID;

            var newaln = new PairwiseSequenceAlignment (aln.FirstSequence, aln.SecondSequence);
            var pas = new PairwiseAlignedSequence ();
            pas.FirstSequence = newRef;
            pas.SecondSequence = newQuery;
            newaln.Add (pas);
            return new Tuple<IPairwiseSequenceAlignment, List<Variant>> (newaln, variants);
        }
Beispiel #31
0
        /// <summary>
        /// Compute overlap's simple-style melting temperature.
        /// </summary>
        /// <returns>Overlap's Tm.</returns>
        public double GetSimpleMeltingTemperature()
        {
            double T = 0.0;
            Sequence upper = null;
            upper = new Sequence(Alphabets.AmbiguousDNA, this.Sequence.ToString().ToUpper());

            for (long index = 0; index < upper.Count; index++)
            {
                T += SimpleT[upper[index]];
            }
            return T;
        }
        public void ValidateProcessRequestThread()
        {
            // Gets the search query parameter and their values.
            string alphabetName = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.AlphabetNameNode);
            string querySequence = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.QuerySequency);
            string queryDatabaseValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.DatabaseValue);
            string email = Constants.EmailForWS;
            string queryProgramValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.ProgramValue);
            string queryDatabaseParameter = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.DatabaseParameter);
            string queryProgramParameter = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.ProgramParameter);
            string expect = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.Expectparameter);
            string emailNotify = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.EmailNotifyParameterNode);
            string jobName = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.JobNameParameterNode);
            string expectValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.ExpectNode);
            string emailNotifyValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.EmailNotifyNode);
            string jobNameValue = utilityObj.xmlUtil.GetTextValue(
                Constants.BioHPCAsynchronousResultsNode, Constants.JobNameNode);

            // Set Blast Parameters
            Sequence seq = new Sequence(Utility.GetAlphabet(alphabetName),
                querySequence);
                BioHPCBlastHandler service = new BioHPCBlastHandler();
            try
            {
                ConfigParameters configParameters = new ConfigParameters();
                configParameters.EmailAddress = email;
                configParameters.Password = String.Empty;
                configParameters.UseBrowserProxy = true;
                service.Configuration = configParameters;

                service.RequestCompleted += new EventHandler<BlastRequestCompletedEventArgs>(service_RequestCompleted);

                BlastParameters searchParams = new BlastParameters();

                // Set Request parameters.
                searchParams.Add(queryDatabaseParameter, queryDatabaseValue);
                searchParams.Add(queryProgramParameter, queryProgramValue);
                searchParams.Add(expect, expectValue);
                searchParams.Add(emailNotify, emailNotifyValue);
                searchParams.Add(jobName, jobNameValue);

                string reqId = String.Empty;

                // Waiting for the any previous request to get completed.
                Thread.Sleep(150000);

                // Create a request without passing sequence.
                reqId = service.SubmitRequest(seq, searchParams);

                // Cancel subitted job.
                bool result = service.CancelRequest(reqId);

                // validate the cancelled job.
                Assert.IsTrue(result);
            }
            finally
            {
                if (service != null)
                    service.Dispose();
            }
        }