/// <summary>
        /// Initializes a new instance of the <see cref="ChemicalBasedAnalysisResult"/> class.
        /// </summary>
        /// <param name="result">
        /// The result.
        /// </param>
        /// <param name="newWorkflowResult">
        /// The new workflow result.
        /// </param>
        public ChemicalBasedAnalysisResult(ChemicalBasedAnalysisResult result, CrossSectionWorkflowResult newWorkflowResult)
        {
            // previous results inconclusive, new result conclusive
            if (!IsConclusive(result.AnalysisStatus))
            {
                this.InitiateFromWorkflowResult(newWorkflowResult);
            }

            // new result inconclusive, previous result conclusive or not conclusive
            else if (!IsConclusive(newWorkflowResult.AnalysisStatus))
            {
                this.AnalysisStatus = result.AnalysisStatus;
                this.FusionNumber = result.FusionNumber;
                this.DetectedIsomers = result.DetectedIsomers;
                this.Target = result.Target;
            }

            // both result conclusive, conflict
            if (CheckConflict(result, newWorkflowResult))
            {
                this.AnalysisStatus = AnalysisStatus.ConflictRuns;
                this.FusionNumber = result.FusionNumber;
                this.DetectedIsomers = result.DetectedIsomers;
                this.Target = result.Target;
            }

            // both result conclusive, no conflict
            IEnumerable<IdentifiedIsomerInfo> newIsomerList = result.DetectedIsomers.Zip(newWorkflowResult.IdentifiedIsomers, (A, B) => FuseIsomerResult(A, B, result.FusionNumber, 1));

            this.AnalysisStatus = result.AnalysisStatus;
            this.FusionNumber = result.FusionNumber + 1;
            this.DetectedIsomers = newIsomerList;
            this.Target = result.Target;
        }
Beispiel #2
0
        public async static void AnalysisDBTest()
        {
            var snapshot1 = new ArrivalTimeSnapShot();
            snapshot1.DriftTubeVoltageInVolt = 1000;
            snapshot1.MeasuredArrivalTimeInMs = 22;
            snapshot1.PressureInTorr = 4;
            snapshot1.TemperatureInKelvin = 10;
            var iso1 = new IdentifiedIsomerInfo(2 ,222, 0.9, 10.5, 115, 123, new List<ArrivalTimeSnapShot>(){snapshot1}, 100, AnalysisStatus.Positive, new PeakScores(1.0, 0.8, 0.7), new MolecularTarget("C2H4O16P2", IonizationMethod.Protonated, "testamin"), 0.1, 0);
            var idens = new List<IdentifiedIsomerInfo>() {iso1};
            
            PeakScores scores = new PeakScores(0, 0.5, 1);
            CrossSectionWorkflowResult result1 = new CrossSectionWorkflowResult("ABC_Dataset_01", new MolecularTarget("C2H4O16P2", IonizationMethod.Protonated, "testamin"), AnalysisStatus.Positive, new AssociationHypothesisInfo(0.1, 0.2), scores, 0.5, OutputFileDir, "123");
            CrossSectionWorkflowResult result2 = new CrossSectionWorkflowResult("ABC_Dataset_02", new MolecularTarget("C2H4O16P2", IonizationMethod.Protonated, "testamin"), AnalysisStatus.Positive, new AssociationHypothesisInfo(0.1, 0.4), scores, 0.8, OutputFileDir, "123");
            CrossSectionWorkflowResult result3 = new CrossSectionWorkflowResult("ABC_Dataset_03", new MolecularTarget("C2H4O16P2", IonizationMethod.Deprotonated, "testamin"), AnalysisStatus.Positive, new AssociationHypothesisInfo(0.1, 0.4), idens, scores, 0.8, OutputFileDir, "123");
            CrossSectionWorkflowResult result4 = new CrossSectionWorkflowResult("ABC_Dataset_03", new MolecularTarget("C2H4O16P2", IonizationMethod.Sodiumated, "testamin"), AnalysisStatus.Positive, new AssociationHypothesisInfo(0.1, 0.4), idens, scores, 0.8, OutputFileDir, "123");
            CrossSectionWorkflowResult result5 = new CrossSectionWorkflowResult("ABC_Dataset_03", new MolecularTarget("C10H40", IonizationMethod.Protonated, "googlin"), AnalysisStatus.Positive, new AssociationHypothesisInfo(0.1, 0.4), idens, scores, 0.8, OutputFileDir, "123");
            CrossSectionWorkflowResult result6 = new CrossSectionWorkflowResult("ABC_Dataset_03", new MolecularTarget("C10H40", IonizationMethod.Protonated, "googlin"), AnalysisStatus.Negative, null, idens, scores, 0.8, OutputFileDir, "123");

            string fileName = @"output\test.sqlite";
            AnalysisLibrary lib = new AnalysisLibrary(fileName);
            await lib.CreateTables();
            await lib.InsertResult(result1);
            await lib.InsertResult(result2);
            await lib.InsertResult(result3);
            await lib.InsertResult(result4);
            await lib.InsertResult(result5);
            await lib.InsertResult(result6);
        }
Beispiel #3
0
 /// <summary>
 /// The add result to scores table.
 /// </summary>
 /// <param name="dataset">
 /// The dataset.
 /// </param>
 /// <param name="chemicalResult">
 /// The chemical result.
 /// </param>
 /// <param name="target">
 /// The target.
 /// </param>
 /// <param name="table">
 /// The table.
 /// </param>
 /// <param name="colDef">
 /// The col def.
 /// </param>
 /// <returns>
 /// The <see cref="int"/>.
 /// </returns>
 public static int AddResultToScoresTable(string dataset, CrossSectionWorkflowResult chemicalResult, IImsTarget target, NumericTable table, IList<string> colDef)
 {
     TableRow dict = new TableRow(dataset + target);
     dict.Name += "(" + chemicalResult.AnalysisStatus + ")";
     dict.Add(colDef[1], chemicalResult.AverageObservedPeakStatistics.IntensityScore);
     dict.Add(colDef[2], chemicalResult.AverageObservedPeakStatistics.IsotopicScore);
     dict.Add(colDef[3], chemicalResult.AverageObservedPeakStatistics.PeakShapeScore);
     dict.Add(colDef[0], chemicalResult.AverageVoltageGroupStability);
     dict.Add(colDef[4], chemicalResult.AssociationHypothesisInfo.ProbabilityOfHypothesisGivenData);
     table.Add(dict);
     return 1;
 }
Beispiel #4
0
        public static void SerializerDeserializerTest()
        {
            IList<CrossSectionWorkflowResult> results = new List<CrossSectionWorkflowResult>();

            // create fake result 1
            IdentifiedIsomerInfo holyGrail1 = new IdentifiedIsomerInfo(10, 250, 6, 10, 22, 4, null, 5, AnalysisStatus.Positive, new PeakScores(1,2,3), new MolecularTarget("C2H34", IonizationMethod.APCI, "Carbon"), 1, 2);
            PeakScores averageFeatureScores1 = new PeakScores(3, 4, 5);

            IImsTarget target1 = new MolecularTarget("C2H5OH", IonizationMethod.Deprotonated, "Ginger ale");
            IImsTarget target2 = new MolecularTarget("C2H5OH", IonizationMethod.Sodiumated, "Volka");

            CrossSectionWorkflowResult result1 = new CrossSectionWorkflowResult(
                "France", 
                target1,
                AnalysisStatus.Positive,
                null,averageFeatureScores1,
                4,
                "",
                "");

            results.Add(result1);

            // Serialize fake result struct
            IFormatter formatter = new BinaryFormatter();
            using (Stream stream = new FileStream("serialized_result.bin", FileMode.Create, FileAccess.Write, FileShare.None))
            {
                formatter.Serialize(stream, results);
            }

            IList<CrossSectionWorkflowResult> newResults;

            // deserialize fake result struct
            using (Stream stream = new FileStream("serialized_result.bin", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                newResults = (IList<CrossSectionWorkflowResult>)formatter.Deserialize(stream);
            }

            CrossSectionWorkflowResult result2 = newResults.First();

            // Compare it
            var result = newResults.First();
            Assert.AreEqual(result.AnalysisStatus, result1.AnalysisStatus);
            Assert.AreEqual(result.DatasetName, result2.DatasetName);
            Assert.AreEqual(result.AverageObservedPeakStatistics.IntensityScore, result2.AverageObservedPeakStatistics.IntensityScore);
        }
        internal static CrossSectionWorkflowResult CreateResultFromAssociationHypothesis(CrossSectionSearchParameters parameters, AssociationHypothesis optimalHypothesis, IImsTarget target, IEnumerable<VoltageGroup> allVoltageGroups, IEnumerable<ObservedPeak> allPeaks, string datasetPath, string analysisPath, string  sampleCollectionDate, double viperCompatibleMass = 0)
        {
            // Initialize the result struct.
            AssociationHypothesisInfo associationHypothesisInfo = new AssociationHypothesisInfo(optimalHypothesis.ProbabilityOfDataGivenHypothesis, optimalHypothesis.ProbabilityOfHypothesisGivenData);

            double averageVoltageGroupScore = VoltageGroupScoring.ComputeAverageVoltageGroupStabilityScore(allVoltageGroups);
            IEnumerable<PeakScores> allFeatureStatistics = allPeaks.Select(x => x.Statistics);
            PeakScores averageObservedPeakStatistics = FeatureScoreUtilities.AverageFeatureStatistics(allFeatureStatistics);

            IEnumerable<IsomerTrack> tracks = optimalHypothesis.Tracks.ToList();

            // Find the conformer with the closest m/z
            IsomerTrack trackWithBestMz = tracks.OrderBy(x => Math.Abs(Metrics.DaltonToPpm(x.AverageMzInDalton - target.MassWithAdduct, target.MassWithAdduct))).First();
            double bestMzInPpm = Metrics.DaltonToPpm(trackWithBestMz.AverageMzInDalton - target.MassWithAdduct, target.MassWithAdduct);
            IList<IdentifiedIsomerInfo> isomersInfo = tracks.Select(x => x.ExportIdentifiedIsomerInfo(viperCompatibleMass, allVoltageGroups.Count() - parameters.MaxOutliers, parameters.MinR2,  target, bestMzInPpm)).ToList();

            AnalysisStatus finalStatus = TrackToHypothesisConclusionLogic(isomersInfo.Select(info => info.AnalysisStatus));

            CrossSectionWorkflowResult informedResult = new CrossSectionWorkflowResult(
            datasetPath,
            target,
            finalStatus,
            associationHypothesisInfo,
            isomersInfo,
            averageObservedPeakStatistics,
            averageVoltageGroupScore,
            analysisPath,
            sampleCollectionDate
            );

            return informedResult;
        }
        /// <summary>
        /// The create negative result.
        /// </summary>
        /// <param name="rejectedPeaks">
        /// The rejected peaks.
        /// </param>
        /// <param name="rejectedVoltageGroups">
        /// The rejected voltage groups.
        /// </param>
        /// <param name="datasetName">
        /// The dataset name.
        /// </param>
        /// <param name="target">
        /// The target.
        /// </param>
        /// <returns>
        /// The <see cref="CrossSectionWorkflowResult"/>.
        /// </returns>
        internal static CrossSectionWorkflowResult CreateNegativeResult(IEnumerable<ObservedPeak> rejectedPeaks, IEnumerable<VoltageGroup> rejectedVoltageGroups, IImsTarget target, string datasetPath, string analysisPath, string sampleCollectionTime)
        {
            // No valid feature peaks were identified. No hypothesis.
            double voltageGroupScore = VoltageGroupScoring.ComputeAverageVoltageGroupStabilityScore(rejectedVoltageGroups);

            // quantize the VG score from VGs in the removal list.
            IEnumerable<PeakScores> featureStats = rejectedPeaks.Select(x => x.Statistics);
            PeakScores averagePeakScores = FeatureScoreUtilities.AverageFeatureStatistics(featureStats);
            CrossSectionWorkflowResult informedResult = new CrossSectionWorkflowResult(
                datasetPath,
                target,
                AnalysisStatus.Negative,
                null,
                averagePeakScores,
                voltageGroupScore,
                analysisPath,
                sampleCollectionTime);

            return informedResult;
        }
 private async Task<long> InsertAnalysis(SQLiteCommand cmd, CrossSectionWorkflowResult result, long targetID, long datasetID)
 {
     // Insert analysis info to chemicals table
     cmd.CommandText = "INSERT INTO analyses (analyzed_dataset , analyzed_target, analysis_status, average_intensity_score, average_peak_shape_score, average_isotopic_score, environment_stability_score, data_likelihood, a_posteriori_probability, qc_plot) VALUES      (@analyzed_dataset , @analyzed_target, @analysis_status, @average_intensity_score, @average_peak_shape_score, @average_isotopic_score, @environment_stability_score, @data_likelihood, @a_posteriori_probability, @qc_plot)";
     cmd.Parameters.AddWithValue("@analyzed_dataset", datasetID);
     cmd.Parameters.AddWithValue("@analyzed_target", targetID);
     cmd.Parameters.AddWithValue("@analysis_status", result.AnalysisStatus.ToString());
     cmd.Parameters.AddWithValue("@average_intensity_score", result.AssociationHypothesisInfo != null ? 
         result.AverageObservedPeakStatistics.IntensityScore : 0);
     cmd.Parameters.AddWithValue("@average_peak_shape_score", result.AssociationHypothesisInfo != null ?
         result.AverageObservedPeakStatistics.PeakShapeScore : 0);
     cmd.Parameters.AddWithValue("@average_isotopic_score", result.AssociationHypothesisInfo != null ?
         result.AverageObservedPeakStatistics.IsotopicScore : 0);
     cmd.Parameters.AddWithValue("@environment_stability_score", result.AverageVoltageGroupStability);
     cmd.Parameters.AddWithValue("@data_likelihood", result.AssociationHypothesisInfo != null ? 
         result.AssociationHypothesisInfo.ProbabilityOfDataGivenHypothesis : 0);
     cmd.Parameters.AddWithValue("@a_posteriori_probability", result.AssociationHypothesisInfo != null ?result.AssociationHypothesisInfo.ProbabilityOfHypothesisGivenData : 0);
     cmd.Parameters.AddWithValue("@qc_plot", "");
     await Task.Run(() => cmd.ExecuteNonQuery());
     return await this.LastID(cmd);
 }
 private async Task<long> InsertDataset(SQLiteCommand cmd, CrossSectionWorkflowResult result)
 {
     cmd.CommandText = string.Format("SELECT count(*) FROM datasets WHERE name='{0}'", result.DatasetName);
     int count = Convert.ToInt32(cmd.ExecuteScalar());
     if(count == 0)
     {
         // Insert dataset info to chemicals table
         cmd.CommandText = "INSERT INTO datasets (name, path, date) VALUES      (@name, @path, @date)";
         cmd.Parameters.AddWithValue("@name", result.DatasetName);
         cmd.Parameters.AddWithValue("@path", result.DatasetPath);
         cmd.Parameters.AddWithValue("@date", result.DateTime);
         await Task.Run(() => cmd.ExecuteNonQuery());
         return await this.LastID(cmd);
     }
     else
     {
         cmd.CommandText = string.Format("SELECT id FROM datasets WHERE name='{0}'", result.DatasetName);
         var id =  cmd.ExecuteScalar();
         return (long)id;
     }
     
     // Return the datasetID
 }
        private async Task InsertResult(SQLiteCommand cmd, CrossSectionWorkflowResult result)
        {
            // Insert chemical info to chemicals table
            await this.InsertChemical(cmd, result.Target);
            
            // Insert dataset info to datasets table
            long datasetId = await this.InsertDataset(cmd, result);

            // Insert target info th targets table
            long targetId = await this.InsertTarget(cmd, result.Target);

            // Insert analysis info the analyses table
            long analysisID = await this.InsertAnalysis(cmd, result, targetId, datasetId);

            // Insert identification info to identifications table

            if (result.IdentifiedIsomers != null)
            {
                foreach (var detection in result.IdentifiedIsomers)
                {
                    long detectionId = await this.InsertIdentifications(cmd, detection, analysisID);
                    foreach (var snapshot in detection.ArrivalTimeSnapShots)
                    {
                        // Insert snapshot info to peaks table
                        await this.InsertSnapshots(cmd, snapshot, detectionId);
                    }
                }
            }
        }
 /// <summary>
 /// Insert a single result
 /// </summary>
 /// <param name="result"></param>
 /// <returns></returns>
 public async Task InsertResult(CrossSectionWorkflowResult result)
 {
     using (await this.dbLock.LockAsync())
     {
         this.dbConnection.Open();
         
         using (SQLiteCommand cmd = new SQLiteCommand(this.dbConnection))
         {
             await this.InsertResult(cmd, result);
         }
         
         this.dbConnection.Close();
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ChemicalBasedAnalysisResult"/> class. 
 /// The initiate chemical based analysis result.
 /// </summary>
 /// <param name="result">
 /// The result ionization result to initiate from.
 /// </param>
 /// <returns>
 /// The <see cref="ChemicalBasedAnalysisResult"/>.
 /// </returns>
 public ChemicalBasedAnalysisResult(CrossSectionWorkflowResult result)
 {
     this.InitiateFromWorkflowResult(result);
 }
 /// <summary>
 /// The initiate from workflow result.
 /// </summary>
 /// <param name="result">
 /// The result.
 /// </param>
 private void InitiateFromWorkflowResult(CrossSectionWorkflowResult result)
 {
     this.Target = result.Target;
     this.AnalysisStatus = result.AnalysisStatus;
     this.FusionNumber = 1;
     this.DetectedIsomers = result.IdentifiedIsomers;
 }
        /// <summary>
        /// Check if there are conflicts in 
        /// </summary>
        /// <param name="result">
        /// The result.
        /// </param>
        /// <param name="newWorkflowResult">
        /// The new workflow result.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// </exception>
        private static bool CheckConflict(ChemicalBasedAnalysisResult result, CrossSectionWorkflowResult newWorkflowResult)
        {
            if (!newWorkflowResult.Target.Equals(result.Target))
            {
                throw new InvalidOperationException("Cannot check conflict for results from different chemicals or with different ionization methods");
            }

            if (result.DetectedIsomers.Count() != newWorkflowResult.IdentifiedIsomers.Count())
            {
                return true;
            }

            if (result.AnalysisStatus != newWorkflowResult.AnalysisStatus)
            {
                return true;
            }

            IEnumerable<bool> r = result.DetectedIsomers.Zip(newWorkflowResult.IdentifiedIsomers, CheckConflict);
            return !r.Select(b => b == false).Any();
        }
        /// <summary>
        /// The report anslysis result and metrics.
        /// </summary>
        /// <param name="informedResult">
        /// The informed Result.
        /// </param>
        /// <param name="detailedVerbose">
        /// The detailed verbose.
        /// </param>
        private static void ReportAnslysisResultAndMetrics(CrossSectionWorkflowResult informedResult, bool detailedVerbose = true)
        {
            Trace.WriteLine("Analysis result");
            Trace.WriteLine(string.Format("    Analysis Conclusion: {0}", informedResult.AnalysisStatus));
            if (informedResult.AnalysisStatus == AnalysisStatus.Positive)
            {
                Trace.WriteLine(string.Format("    P(T|X): {0:F4}", informedResult.AssociationHypothesisInfo.ProbabilityOfDataGivenHypothesis));
                Trace.WriteLine(string.Format("    P(X|T): {0:F4}", informedResult.AssociationHypothesisInfo.ProbabilityOfDataGivenHypothesis));
            }

            if (detailedVerbose)
            {
                Trace.WriteLine(string.Format("    Average Voltage Group Stability Score: {0:F4}", informedResult.AverageVoltageGroupStability));

                if (informedResult.AnalysisStatus == AnalysisStatus.Positive)
                {
                    ReportIsomersInfo(informedResult.IdentifiedIsomers);
                }
            }
        }