Example #1
0
        public void FastaParserForManyFiles()
        {
            string path = @"TestUtils\FASTA";

            Assert.IsTrue(Directory.Exists(path));
            int            count     = 0;
            FastaParser    parser    = new FastaParser();
            FastaFormatter formatter = new FastaFormatter();
            DirectoryInfo  di        = new DirectoryInfo(path);

            foreach (FileInfo fi in di.GetFiles("*.fasta"))
            {
                using (StreamReader reader = File.OpenText(fi.FullName))
                {
                    ApplicationLog.WriteLine("parsing file {0}...", fi.FullName);
                    foreach (Sequence seq in parser.Parse(reader))
                    {
                        ApplicationLog.Write(formatter.FormatString(seq));
                        count++;
                    }
                }
                ApplicationLog.WriteLine("parsing file {0}...", fi.FullName);
            }
            Assert.IsTrue(count >= 3);
            ((FastaParser)parser).Dispose();
        }
Example #2
0
        /// <summary>
        /// Get the blast service request object with all the request parameter set
        /// </summary>
        /// <param name="sequence">Input sequece</param>
        /// <param name="parameters">Blast parameters</param>
        /// <returns>Blast service request object</returns>
        private static BlastSerivceRequest GetRequestParameter(
            ISequence sequence,
            BlastParameters parameters)
        {
            BlastSerivceRequest blastParameter = new BlastSerivceRequest();

            // Sets the format of output expected from Azure Blast service
            blastParameter.OptionM = OPTIONMVALUE;

            // Sets the name of Job owner
            blastParameter.Owner          = Resources.OWNERVALUE;
            blastParameter.ParitionNumber = PARTITIONVALUE;

            // Convert string to byte
            ISequenceFormatter formatter     = new FastaFormatter();
            string             inputContent  = formatter.FormatString(sequence);
            ASCIIEncoding      asciiEncoding = new ASCIIEncoding();

            blastParameter.InputContent = asciiEncoding.GetBytes(inputContent);

            // Other parameters
            // Set the Title of Job
            blastParameter.Title = sequence.ID;

            // Name of the database to be searched in
            blastParameter.DatabaseName = parameters.Settings[PARAMETERDATABASE];

            // Type of search program to be executed
            blastParameter.ProgramName = parameters.Settings[PARAMETERPROGRAM];

            return(blastParameter);
        }
Example #3
0
        private void WriteAlignment(SequenceAlignment alignment)
        {
            FastaFormatter formatter = new FastaFormatter();
            StreamWriter   alnoutput = new StreamWriter(_tempDirectory + CRWSequenceAlignmentFormatTags.AlignmentFileName);

            alnoutput.AutoFlush = true;
            foreach (ISequence sequence in alignment.Sequences)
            {
                alnoutput.Write(formatter.FormatString(sequence));
            }
            alnoutput.Close();
        }
Example #4
0
        /// <summary>
        /// CreateJob() to get job id and control id and Submit job
        /// using input sequence with job id and control id
        /// </summary>
        /// <param name="sequence">input sequences</param>
        /// <param name="parameters">input params</param>
        /// <returns>result params with job id and control id</returns>
        public ServiceParameters SubmitRequest(IList <ISequence> sequence, ClustalWParameters parameters)
        {
            ServiceParameters result = new ServiceParameters();

            // ClusterOption = biosim cbsum1 cbsum2k8 cbsusrv05 cbsum2 or Auto
            string[] output = _baseClient.CreateJob(tAppId.P_CLUSTALW, "test_BioHPC_Job", "1", parameters.Values[ClustalWParameters.Email].ToString(),
                                                    string.Empty, parameters.Values[ClustalWParameters.ClusterOption].ToString());

            if (!output[0].Contains(ERROR))
            {
                result.JobId = output[1];
                result.Parameters.Add(CONTROLID, output[2]);

                AppInputData   inputData     = _baseClient.InitializeApplicationParams(tAppId.P_CLUSTALW, "test_BioHPC_Job");
                FastaFormatter formatter     = new FastaFormatter();
                StringBuilder  inputSequence = new StringBuilder();
                foreach (ISequence seq in sequence)
                {
                    inputSequence.AppendLine(formatter.FormatString(seq));
                }

                //formatter.Format(sequence, "temp");
                //StreamReader reader = new StreamReader("temp");
                inputData.clustalw.inputsource = QuerySrcType.paste;
                inputData.clustalw.inputstring = inputSequence.ToString();
                inputData.clustalw.isDNA       = false;
                inputData.clustalw.action      = (ClwActions)Enum.Parse(typeof(ClwActions),
                                                                        parameters.Values[ClustalWParameters.ActionAlign].ToString());
                inputData.clustalw.email_notify = true;

                _baseClient.SubmitJob(result.JobId, result.Parameters[CONTROLID].ToString(), inputData);
                result.Parameters.Add(SUBMISSONRESULT, SUCCESS);

                // Only if the event is registered, invoke the thread
                if (null != RequestCompleted)
                {
                    // Start the BackGroundThread to check the status of job
                    _workerThread = new BackgroundWorker();
                    _workerThread.WorkerSupportsCancellation = true;
                    _workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                    _workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                    _workerThread.RunWorkerAsync(result);
                }
            }
            else
            {
                result.Parameters.Add(SUBMISSONRESULT, output[0]);
            }

            return(result);
        }
Example #5
0
        public void FastaFormatterWithParseValidateFormatString()
        {
            // Gets the expected sequence from the Xml
            string filePath = Utility._xmlUtil.GetTextValue(
                Constants.SimpleFastaNodeName,
                Constants.FilePathNode);

            Assert.IsTrue(File.Exists(filePath));

            // Logs information to the log file
            ApplicationLog.WriteLine(string.Format(null,
                                                   "FastA Formatter BVT: File Exists in the Path '{0}'.", filePath));

            FastaParser    parser    = new FastaParser();
            FastaFormatter formatter = new FastaFormatter();

            // Read the original file
            IList <ISequence> seqsOriginal = null;

            parser       = new FastaParser();
            seqsOriginal = parser.Parse(filePath);
            Assert.IsNotNull(seqsOriginal);

            string formatStrOrginal = Utility._xmlUtil.GetTextValue(
                Constants.SimpleFastaNodeName,
                Constants.FormatStringNode);
            string formatStr = formatter.FormatString(seqsOriginal[0]).Trim();

            formatStr = formatStr.Replace("\r", "").Replace("\n", "");

            Assert.AreEqual(formatStrOrginal, formatStr);
            Console.WriteLine(string.Format(null,
                                            "FastA Formatter BVT: The FASTA sequences '{0}' are matching with FormatString() method and is as expected.",
                                            formatStrOrginal));
            ApplicationLog.WriteLine(string.Format(null,
                                                   "FastA Formatter BVT: The FASTA sequences '{0}' are matching with FormatString() method.",
                                                   formatStrOrginal));
        }
Example #6
0
        public void FastaFormatterValidateFormatString()
        {
            FastaFormatter formatter = new FastaFormatter();

            // Gets the actual sequence and the alphabet from the Xml
            string actualSequence = Utility._xmlUtil.GetTextValue(Constants.SimpleFastaNodeName,
                                                                  Constants.ExpectedSequenceNode);
            string alpName = Utility._xmlUtil.GetTextValue(Constants.SimpleFastaNodeName,
                                                           Constants.AlphabetNameNode);

            // Logs information to the log file
            ApplicationLog.WriteLine(string.Format(null,
                                                   "FastA Formatter BVT: Validating with Sequence '{0}' and Alphabet '{1}'.",
                                                   actualSequence, alpName));

            Sequence seqOriginal = new Sequence(Utility.GetAlphabet(alpName),
                                                actualSequence);

            Assert.IsNotNull(seqOriginal);
            seqOriginal.ID = Utility._xmlUtil.GetTextValue(Constants.SimpleFastaNodeName,
                                                           Constants.SequenceIdNode);

            string formatStrOrginal = Utility._xmlUtil.GetTextValue(
                Constants.SimpleFastaNodeName, Constants.FormatStringNode);
            string formatStr = formatter.FormatString(seqOriginal);

            formatStr = formatStr.Replace("\r", "").Replace("\n", "");

            Assert.AreEqual(formatStrOrginal, formatStr);
            Console.WriteLine(
                string.Format(null,
                              "FastA Formatter BVT: The FASTA sequences '{0}' are matching with FormatString() method and is as expected.",
                              formatStrOrginal));
            ApplicationLog.WriteLine(string.Format(null,
                                                   "FastA Formatter BVT: The FASTA sequences '{0}' are matching with FormatString() method.",
                                                   formatStrOrginal));
        }
Example #7
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the MBF.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null == sequence)
            {
                throw new ArgumentNullException("sequence");
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            if (!string.IsNullOrEmpty(Configuration.EmailAddress))
            {
                if (!parameters.Settings.ContainsKey(ParameterEmail))
                {
                    parameters.Add(ParameterEmail, Configuration.EmailAddress);
                }
            }

            string requestIdentifier = string.Empty;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            // Submit the job to server
            inputParams blastRequest = GetRequestParameter(parameters);

            blastRequest.appxml = AppXmlYes;
            blastRequest.async  = true;

            data[] mydata = new data[1];
            mydata[0]      = new data();
            mydata[0].type = SequenceType;

            FastaFormatter formatter = new FastaFormatter();

            mydata[0].content = formatter.FormatString(sequence);

            requestIdentifier = _blastClient.runWUBlast(blastRequest, mydata);

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                ThreadParameter threadParameter = new ThreadParameter(
                    requestIdentifier,
                    sequence,
                    parameters);

                // Start the BackGroundThread to check the status of job
                _workerThread = new BackgroundWorker();
                _workerThread.WorkerSupportsCancellation = true;
                _workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                _workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                _workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }
Example #8
0
        /// <summary>
        /// Submit the search request with the user supplied configuration parameters
        /// and sequence. Implementation should make use of the MBF.IO formatters
        /// to convert the sequence into the web interface compliant sequence format.
        /// This method performs parameter validation and throw Exception on invalid input.
        /// </summary>
        /// <remarks>An exception is thrown if the request does not succeed.</remarks>
        /// <param name="sequence">The sequence to search with</param>
        /// <param name="parameters">Blast input parameters</param>
        /// <returns>Request Identifier</returns>
        public string SubmitRequest(ISequence sequence, BlastParameters parameters)
        {
            if (null != sequence)
            {
                FastaFormatter formatter = new FastaFormatter();
                parameters.Add("Query", formatter.FormatString(sequence));
            }

            if (null == parameters)
            {
                throw new ArgumentNullException("parameters");
            }

            if (!string.IsNullOrEmpty(Configuration.EmailAddress))
            {
                if (!parameters.Settings.ContainsKey(PARAMETEREMAIL))
                {
                    parameters.Add(PARAMETEREMAIL, Configuration.EmailAddress);
                }
            }

            string requestIdentifier = string.Empty;

            // Validate the Parameter
            ParameterValidationResult valid = ValidateParameters(parameters);

            if (!valid.IsValid)
            {
                throw new Exception(valid.ValidationErrors);
            }

            parameters.Add(PARAMETERCOMMAND, COMMANDPUT);

            WebAccessor         accessor = new WebAccessor();
            WebAccessorResponse webAccessorResponse;

            if (Configuration.UseBrowserProxy)
            {
                accessor.GetBrowserProxy();
            }

            webAccessorResponse = accessor.SubmitHttpRequest(
                ServiceUri,
                true,                       // do POST
                parameters.Settings);       // request parameters
            if (!webAccessorResponse.IsSuccessful)
            {
                // failed
                accessor.Close();
                throw new Exception(String.Format(CultureInfo.InvariantCulture,
                                                  Resources.HTTPSUBMITFAILED,
                                                  webAccessorResponse.StatusDescription));
            }

            string info = ExtractInfoSection(webAccessorResponse.ResponseString);

            if (!String.IsNullOrEmpty(info))
            {
                int ridStart = info.IndexOf("RID = ", StringComparison.OrdinalIgnoreCase);
                if (ridStart >= 0)
                {
                    ridStart += "RID = ".Length;
                    int ridEnd = info.IndexOf('\n', ridStart);
                    if (ridEnd >= 0)
                    {
                        requestIdentifier = info.Substring(ridStart, ridEnd - ridStart);
                    }
                }
            }

            accessor.Close();
            if (string.IsNullOrEmpty(requestIdentifier))
            {
                string message = String.Format(CultureInfo.InvariantCulture,
                                               Resources.RIDEXTRACTFAILED,
                                               ExtractError(webAccessorResponse.ResponseString));
                throw new Exception(message);
            }

            // Only if the event is registered, invoke the thread
            if (null != RequestCompleted)
            {
                ThreadParameter threadParameter = new ThreadParameter(
                    requestIdentifier,
                    sequence,
                    parameters);

                // Start the BackGroundThread to check the status of job
                _workerThread = new BackgroundWorker();
                _workerThread.WorkerSupportsCancellation = true;
                _workerThread.DoWork             += new DoWorkEventHandler(ProcessRequestThread);
                _workerThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompletedRequestThread);
                _workerThread.RunWorkerAsync(threadParameter);
            }

            return(requestIdentifier);
        }