public double?CalculateIonRatio(Replicate replicate, Peptide peptide)
        {
            var numerator   = new List <double>();
            var denominator = new List <double>();

            foreach (var transition in peptide.Precursors.SelectMany(precursor => precursor.Transitions))
            {
                var transitionDocNode = transition.DocNode;
                var chromInfo         = transitionDocNode.Results[replicate.ReplicateIndex].FirstOrDefault();
                if (chromInfo == null || chromInfo.IsEmpty || chromInfo.IsTruncated.GetValueOrDefault())
                {
                    continue;
                }

                if (transition.Quantitative)
                {
                    denominator.Add(chromInfo.Area);
                }
                else
                {
                    numerator.Add(chromInfo.Area);
                }
            }

            if (numerator.Count == 0 || denominator.Count == 0)
            {
                return(null);
            }

            return(numerator.Sum() / denominator.Sum());
        }
        public MeasuredResults UpdateReplicateAnnotations(MeasuredResults measuredResults)
        {
            if (measuredResults == null)
            {
                return(null);
            }

            AnnotationUpdater updater;

            if (!_annotationUpdaters.TryGetValue(AnnotationDef.AnnotationTarget.replicate, out updater))
            {
                return(measuredResults);
            }

            var chromatograms = measuredResults.Chromatograms.ToArray();

            for (int replicateIndex = 0; replicateIndex < measuredResults.Chromatograms.Count; replicateIndex++)
            {
                var chromatogramSet = chromatograms[replicateIndex];
                var replicate       = new Replicate(SkylineDataSchema, replicateIndex);
                var annotations     = updater.UpdateAnnotations(chromatogramSet.Annotations, replicate);
                if (!Equals(annotations, chromatogramSet.Annotations))
                {
                    chromatograms[replicateIndex] = chromatogramSet.ChangeAnnotations(annotations);
                }
            }

            if (ArrayUtil.ReferencesEqual(measuredResults.Chromatograms, chromatograms))
            {
                return(measuredResults);
            }

            return(measuredResults.ChangeChromatograms(chromatograms));
        }
            public Results <TItem> Update(Results <TItem> results, IDictionary <ResultKey, TResult> resultObjects)
            {
                if (results == null)
                {
                    return(null);
                }

                var newChromInfos = new List <IList <TItem> >();

                for (int replicateIndex = 0; replicateIndex < results.Count; replicateIndex++)
                {
                    var replicate = new Replicate(SkylineDataSchema, replicateIndex);
                    var list      = new List <TItem>();
                    for (int fileIndex = 0; fileIndex < results[replicateIndex].Count; fileIndex++)
                    {
                        var chromInfo = results[replicateIndex][fileIndex];
                        if (chromInfo != null)
                        {
                            var     resultKey = new ResultKey(replicate, fileIndex);
                            TResult resultObject;
                            if (resultObjects.TryGetValue(resultKey, out resultObject))
                            {
                                var newAnnotations =
                                    AnnotationUpdater.UpdateAnnotations(GetAnnotations(chromInfo), resultObject);
                                chromInfo = ChangeAnnotations(chromInfo, newAnnotations);
                            }
                        }

                        list.Add(chromInfo);
                    }
                    newChromInfos.Add(list);
                }

                return(Results <TItem> .Merge(results, newChromInfos));
            }
 public ReplicateRow(Replicate replicate, GroupIdentifier groupIdentifier, String identity, double?abundance)
 {
     Replicate               = replicate;
     ReplicateGroup          = groupIdentifier;
     ReplicateSampleIdentity = identity;
     Abundance               = abundance;
 }
        private void VerifyQuantificationResults(bool hasBatchNames)
        {
            var documentGrid = FindOpenForm <DocumentGridForm>();

            RunUI(() => documentGrid.ChooseView("PeptideQuantificationResults"));
            WaitForConditionUI(() => documentGrid.IsComplete);
            var propertyPathResults = PropertyPath.Root
                                      .Property(nameof(Peptide.Results)).LookupAllItems()
                                      .Property(nameof(KeyValuePair <ResultKey, PeptideResult> .Value));
            var colPeptide   = documentGrid.FindColumn(PropertyPath.Root);
            var colReplicate = documentGrid.FindColumn(propertyPathResults
                                                       .Property(nameof(PeptideResult.ResultFile))
                                                       .Property(nameof(ResultFile.Replicate)));
            var colCalibrationCurve =
                documentGrid.FindColumn(PropertyPath.Root.Property(nameof(Peptide.CalibrationCurve)));
            var colReplicateCalibrationCurve =
                documentGrid.FindColumn(propertyPathResults.Property(nameof(PeptideResult.ReplicateCalibrationCurve)));
            var colQuantification =
                documentGrid.FindColumn(propertyPathResults.Property(nameof(PeptideResult.Quantification)));

            for (int iRow = 0; iRow < documentGrid.RowCount; iRow++)
            {
                Peptide   peptide                   = null;
                Replicate replicate                 = null;
                var       calibrationCurve          = default(LinkValue <CalibrationCurve>);
                var       replicateCalibrationCurve = default(LinkValue <CalibrationCurve>);
                RunUI(() =>
                {
                    var row                   = documentGrid.DataGridView.Rows[iRow];
                    peptide                   = (Peptide)row.Cells[colPeptide.Index].Value;
                    replicate                 = (Replicate)row.Cells[colReplicate.Index].Value;
                    calibrationCurve          = (LinkValue <CalibrationCurve>)row.Cells[colCalibrationCurve.Index].Value;
                    replicateCalibrationCurve =
                        (LinkValue <CalibrationCurve>)row.Cells[colReplicateCalibrationCurve.Index].Value;
                });
                if (hasBatchNames)
                {
                    Assert.AreNotEqual(calibrationCurve.Value.PointCount, replicateCalibrationCurve.Value.PointCount);
                }
                else
                {
                    Assert.AreEqual(calibrationCurve.Value.PointCount, replicateCalibrationCurve.Value.PointCount);
                    Assert.AreEqual(calibrationCurve.Value.Slope, replicateCalibrationCurve.Value.Slope);
                }

                int selectedResultsIndexOld = SkylineWindow.SelectedResultsIndex;
                RunUI(() => calibrationCurve.ClickEventHandler(new object(), new EventArgs()));
                var calibrationForm = FindOpenForm <CalibrationForm>();
                Assert.IsNotNull(calibrationForm);
                WaitForGraphs();
                Assert.AreEqual(peptide.IdentityPath, SkylineWindow.SelectedPath);
                Assert.AreEqual(selectedResultsIndexOld, SkylineWindow.SelectedResultsIndex);
                RunUI(() => replicateCalibrationCurve.ClickEventHandler(new object(), new EventArgs()));
                Assert.AreEqual(peptide.IdentityPath, SkylineWindow.SelectedPath);
                Assert.AreEqual(replicate.ReplicateIndex, SkylineWindow.SelectedResultsIndex);
            }
        }
        public void Class_Test()
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.Contains("StaticCode"));

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes().Where(t => t.IsClass))
                {
                    var fakeClass = Replicate.Class(type);
                }
            }
        }
Exemple #7
0
        public string GenerateDeclaration(Replicate replicate)
        {
            Indentation.Level = 0;

            if (replicate.Value == "null")
            {
                return(String.Concat("var ", replicate.Name, " = null;"));
            }
            else
            {
                return(String.Concat("var ", replicate.Name, " = ", replicate.Declaration, ";"));
            }
        }
Exemple #8
0
        public string GenerateDeclaration(Replicate replicate)
        {
            Indentation.Level = 0;

            if (replicate.Value == "Nothing")
            {
                return(String.Concat("Dim ", replicate.Name, " = Nothing"));
            }
            else
            {
                return(String.Concat("Dim ", replicate.Name, " As ", replicate.Declaration));
            }
        }
Exemple #9
0
        public override IEnumerable <ResultFile> ListAllElements()
        {
            int replicateCount = SrmDocument.Settings.HasResults
                ? SrmDocument.Settings.MeasuredResults.Chromatograms.Count
                : 0;

            for (int replicateIndex = 0; replicateIndex < replicateCount; replicateIndex++)
            {
                var replicate = new Replicate(DataSchema, replicateIndex);
                foreach (var chromFileInfo in replicate.ChromatogramSet.MSDataFileInfos)
                {
                    yield return(new ResultFile(replicate, chromFileInfo.FileId, 0));
                }
            }
        }
        protected override List <Replicate> GetListMembers(string variableName)
        {
            var members = new List <Replicate>();

            var itemsCount = Int32.Parse(Debugger.GetExpression(String.Concat(variableName, ".Count()")).Value);

            for (int i = 0; i < itemsCount; i++)
            {
                Replicate member = CreateReplicate(String.Concat(variableName, "[", i.ToString(), "]"));

                members.Add(member);
            }

            return(members);
        }
        public void Property_Test()
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.Contains("ModelManager"));

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    foreach (var property in type.GetProperties().Where(m => m.DeclaringType == type))
                    {
                        var propertyBlock = Replicate.Property(property);
                    }
                }
            }
        }
        public void Method_Test()
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.Contains("ModelManager"));

            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    foreach (var method in type.GetMethods().Where(m => m.DeclaringType == type && !m.IsSpecialName))
                    {
                        var methodBlock = Replicate.Method(method);
                    }
                }
            }
        }
Exemple #13
0
        private ImmutableSortedList <ResultKey, Replicate> CreateReplicateList()
        {
            var srmDocument = Document;

            if (!srmDocument.Settings.HasResults)
            {
                return(ImmutableSortedList <ResultKey, Replicate> .EMPTY);
            }
            return(ImmutableSortedList <ResultKey, Replicate> .FromValues(
                       Enumerable.Range(0, srmDocument.Settings.MeasuredResults.Chromatograms.Count)
                       .Select(replicateIndex =>
            {
                var replicate = new Replicate(this, replicateIndex);
                return new KeyValuePair <ResultKey, Replicate>(new ResultKey(replicate, 0), replicate);
            }), Comparer <ResultKey> .Default));
        }
        protected override List <Replicate> GetListMembers(string variableName)
        {
            var members = new List <Replicate>();

            var itemsCount = Int32.Parse(Debugger.GetExpression(String.Concat(variableName, ".Count")).Value);

            for (int i = 0; i < itemsCount; i++)
            {
                //todo: créer replicate à part, setter le bon type, name du replicate, puis ajouter le membre?
                Replicate member = CreateReplicate(String.Concat(variableName, "(", i.ToString(), ")"));

                members.Add(member);
            }

            return(members);
        }
Exemple #15
0
        public static void UpdateLogic(EventArgs args)
        {
            if (!MenuManager.IsEnable)
            {
                return;
            }
            if (_updater == null)
            {
                _updater = new Sleeper();
            }
            if (_updater.Sleeping)
            {
                return;
            }
            _updater.Sleep(500);
            var illus =
                ObjectManager.GetEntities <Hero>().Where(x => x.IsValid && x.IsIllusion && x.IsControllable && x.IsAlive).ToArray();
            var replicate = illus.FirstOrDefault(x => x.HasModifier("modifier_morph_replicate"));
            var hybrid    = illus.FirstOrDefault(x => x.HasModifier("modifier_morph_hybrid_special"));

            if (MainHero == null || !MainHero.IsValid)
            {
                if (Members.MainHero != null && Members.MainHero.IsValid)
                {
                    MainHero = new MainHero(Members.MainHero);
                }
            }

            if (Replicate == null || !Replicate.IsValid)
            {
                if (replicate != null)
                {
                    Replicate = new Replicate(replicate);
                }
            }

            if (Hybrid == null || !Hybrid.IsValid)
            {
                if (hybrid != null)
                {
                    Hybrid = new Hybrid(hybrid);
                }
            }
        }
Exemple #16
0
 private void DoUpdate(uint value, int primary, int secondary, bool isFloat)
 {
     if (Values[primary, secondary] == null)
     {
         Values[primary, secondary] = new Replicate
         {
             Value   = value,
             IsFloat = isFloat,
             Changed = true
         };
         Changed = true;
     }
     else if (Values[primary, secondary].Value != value)
     {
         Values[primary, secondary].IsFloat = isFloat;
         Values[primary, secondary].Value   = value;
         Values[primary, secondary].Changed = true;
         Changed = true;
     }
 }
Exemple #17
0
 public ResultKey(Replicate replicate, int fileIndex) : this(replicate.Name, replicate.ReplicateIndex, fileIndex)
 {
 }
Exemple #18
0
        protected override void DoTest()
        {
            RunUI(() =>
            {
                SkylineWindow.OpenFile(TestFilesDir.GetTestPath("p180test_calibration_DukeApril2016.sky"));
                SkylineWindow.ShowDocumentGrid(true);
            });
            WaitForDocumentLoaded();

            var documentGrid = FindOpenForm <DocumentGridForm>();

            RunUI(() => documentGrid.ChooseView("NormalizedAreas"));
            WaitForConditionUI(() => documentGrid.IsComplete);

            // Read the Normalized Area and Calculated Concentration for each peptide from the Document Grid

            // Dictionary of <IdentityPath, Replicate Name> to <Normalized Area, Calculated Concentration>
            var normalizedAreas = new Dictionary <Tuple <IdentityPath, string>, Tuple <double?, double?> >();

            RunUI(() =>
            {
                var colMolecule        = documentGrid.FindColumn(PropertyPath.Root);
                PropertyPath ppResults = PropertyPath.Root
                                         .Property(nameof(Skyline.Model.Databinding.Entities.Peptide.Results)).DictionaryValues();
                var colReplicate = documentGrid.FindColumn(ppResults.Property(nameof(PeptideResult.ResultFile))
                                                           .Property(nameof(ResultFile.Replicate)));

                PropertyPath ppQuantification = ppResults.Property(nameof(PeptideResult.Quantification));
                var colNormalizedArea         =
                    documentGrid.FindColumn(ppQuantification.Property(nameof(QuantificationResult.NormalizedArea)));
                var colCalculatedConcentration =
                    documentGrid.FindColumn(
                        ppQuantification.Property(nameof(QuantificationResult.CalculatedConcentration)));

                for (int rowIndex = 0; rowIndex < documentGrid.RowCount; rowIndex++)
                {
                    var row = documentGrid.DataGridView.Rows[rowIndex];
                    Skyline.Model.Databinding.Entities.Peptide molecule =
                        (Skyline.Model.Databinding.Entities.Peptide)row.Cells[colMolecule.Index].Value;
                    Assert.IsNotNull(molecule);
                    Replicate replicate            = (Replicate)row.Cells[colReplicate.Index].Value;
                    double?normalizedArea          = (double?)row.Cells[colNormalizedArea.Index].Value;
                    double?calculatedConcentration = (double?)row.Cells[colCalculatedConcentration.Index].Value;
                    normalizedAreas.Add(Tuple.Create(molecule.IdentityPath, replicate.Name), Tuple.Create(normalizedArea, calculatedConcentration));
                }
            });

            // Show the PeakAreaCVHistogram graph
            RunUI(() => SkylineWindow.ShowPeakAreaCVHistogram());
            WaitForConditionUI(() => null != FindGraphPane <AreaCVHistogramGraphPane>());
            AreaCVHistogramGraphPane areaCVHistogramGraphPane = FindGraphPane <AreaCVHistogramGraphPane>();

            // Change "Normalize To" to "Calibration Curve"
            RunUI(() => SkylineWindow.NormalizeAreaGraphTo(NormalizeOption.CALIBRATED));
            WaitForConditionUI(() =>
                               areaCVHistogramGraphPane.CurrentData?.GraphSettings?.NormalizeOption == NormalizeOption.CALIBRATED);

            // Verify that the CVs that the histogram is displaying are correct for the calculated concentrations
            var graphData = areaCVHistogramGraphPane.CurrentData;

            foreach (var cvData in graphData.Data)
            {
                var peptideAnnotationPair = cvData.PeptideAnnotationPairs.First();
                var identityPath          = new IdentityPath(peptideAnnotationPair.PeptideGroup.PeptideGroup, peptideAnnotationPair.Peptide.Peptide);
                var entries    = normalizedAreas.Where(entry => Equals(entry.Key.Item1, identityPath)).ToList();
                var statistics = new Statistics(entries.Select(entry => entry.Value.Item2).OfType <double>());
                var cv         = statistics.StdDev() / statistics.Mean();
                var cvBucketed = Math.Floor(cv / graphData.GraphSettings.BinWidth) * graphData.GraphSettings.BinWidth;
                AssertEx.AreEqual(cvBucketed, cvData.CV);
            }

            // Change "Normalize To" to "Default Normalization Method"
            RunUI(() => SkylineWindow.NormalizeAreaGraphTo(NormalizeOption.DEFAULT));
            WaitForConditionUI(() =>
                               areaCVHistogramGraphPane.CurrentData?.GraphSettings?.NormalizeOption == NormalizeOption.DEFAULT);
            graphData = areaCVHistogramGraphPane.CurrentData;

            // Verify that the CVs are correct for the Normalized Area values.
            foreach (var cvData in graphData.Data)
            {
                var peptideAnnotationPair = cvData.PeptideAnnotationPairs.First();
                var identityPath          = new IdentityPath(peptideAnnotationPair.PeptideGroup.PeptideGroup, peptideAnnotationPair.Peptide.Peptide);
                var entries    = normalizedAreas.Where(entry => Equals(entry.Key.Item1, identityPath)).ToList();
                var statistics = new Statistics(entries.Select(entry => entry.Value.Item1).OfType <double>());
                var cv         = statistics.StdDev() / statistics.Mean();
                var cvBucketed = Math.Floor(cv / graphData.GraphSettings.BinWidth) * graphData.GraphSettings.BinWidth;
                AssertEx.AreEqual(cvBucketed, cvData.CV);
            }

            // Show the Peak Area Replicate Comparison graph
            RunUI(() =>
            {
                SkylineWindow.NormalizeAreaGraphTo(NormalizeOption.CALIBRATED);
                SkylineWindow.ShowPeakAreaReplicateComparison();
            });
            var peakAreaGraph = FindGraphPane <AreaReplicateGraphPane>();

            // Make sure that the calculated concentrations displayed in the graph are correct for each molecule in the document
            foreach (var moleculeGroup in SkylineWindow.Document.MoleculeGroups)
            {
                foreach (var molecule in moleculeGroup.Molecules)
                {
                    var idPath = new IdentityPath(moleculeGroup.Id, molecule.Id);
                    RunUI(() => SkylineWindow.SelectedPath = idPath);
                    WaitForGraphs();
                    RunUI(() =>
                    {
                        var curve      = peakAreaGraph.CurveList.First();
                        var textLabels = peakAreaGraph.XAxis.Scale.TextLabels;
                        Assert.IsNotNull(textLabels);
                        Assert.AreEqual(textLabels.Length, curve.Points.Count);
                        Assert.AreEqual(SkylineWindow.Document.Settings.MeasuredResults.Chromatograms.Count, curve.Points.Count);
                        for (int i = 0; i < curve.Points.Count; i++)
                        {
                            var replicateName = SkylineWindow.Document.Settings.MeasuredResults.Chromatograms[i].Name;
                            var value         = curve.Points[i].Y;
                            Tuple <double?, double?> expected;
                            Assert.IsTrue(normalizedAreas.TryGetValue(Tuple.Create(idPath, replicateName), out expected));
                            if (expected.Item2.HasValue && !double.IsInfinity(expected.Item2.Value))
                            {
                                AssertEx.AreEqual(expected.Item2.Value, value);
                            }
                            else
                            {
                                AssertEx.IsTrue(double.IsNaN(value) || Equals(value, PointPairBase.Missing));
                            }
                        }
                    });
                }
            }
        }
        private void UpdateResults()
        {
            var results = GroupComparisonModel.Results;
            var rows    = new List <FoldChangeRow>();

            if (null != results)
            {
                var controlGroupIdentifier =
                    GroupComparisonModel.GroupComparisonDef.GetControlGroupIdentifier(_skylineDataSchema.Document
                                                                                      .Settings);
                Dictionary <int, double> criticalValuesByDegreesOfFreedom = new Dictionary <int, double>();
                var groupComparisonDef = results.GroupComparer.ComparisonDef;
                var adjustedPValues    = PValues.AdjustPValues(results.ResultRows.Select(
                                                                   row => row.LinearFitResult.PValue)).ToArray();
                for (int iRow = 0; iRow < results.ResultRows.Count; iRow++)
                {
                    var resultRow = results.ResultRows[iRow];
                    var protein   = new Protein(_skylineDataSchema, new IdentityPath(resultRow.Selector.Protein.Id));
                    Model.Databinding.Entities.Peptide peptide = null;
                    if (null != resultRow.Selector.Peptide)
                    {
                        peptide = new Model.Databinding.Entities.Peptide(_skylineDataSchema,
                                                                         new IdentityPath(protein.IdentityPath, resultRow.Selector.Peptide.Id));
                    }
                    double criticalValue;
                    if (!criticalValuesByDegreesOfFreedom.TryGetValue(resultRow.LinearFitResult.DegreesOfFreedom,
                                                                      out criticalValue))
                    {
                        criticalValue = FoldChangeResult.GetCriticalValue(groupComparisonDef.ConfidenceLevel,
                                                                          resultRow.LinearFitResult.DegreesOfFreedom);
                        criticalValuesByDegreesOfFreedom.Add(resultRow.LinearFitResult.DegreesOfFreedom, criticalValue);
                    }
                    FoldChangeResult foldChangeResult = new FoldChangeResult(groupComparisonDef.ConfidenceLevel,
                                                                             adjustedPValues[iRow], resultRow.LinearFitResult, criticalValue);
                    var runAbundances = new Dictionary <Replicate, ReplicateRow>();

                    foreach (var runAbundance in resultRow.RunAbundances)
                    {
                        Replicate replicate = new Replicate(_skylineDataSchema, runAbundance.ReplicateIndex);
                        runAbundances.Add(replicate, new ReplicateRow(replicate, runAbundance.Control ?
                                                                      controlGroupIdentifier : resultRow.Selector.GroupIdentifier
                                                                      , runAbundance.BioReplicate, Math.Pow(2, runAbundance.Log2Abundance)));
                    }
                    rows.Add(new FoldChangeRow(protein, peptide, resultRow.Selector.LabelType,
                                               resultRow.Selector.MsLevel, resultRow.Selector.GroupIdentifier, resultRow.ReplicateCount, foldChangeResult, runAbundances));
                }
            }

            var detailRows = new List <FoldChangeDetailRow>();

            foreach (var grouping in rows.ToLookup(row =>
                                                   Tuple.Create(row.Protein, row.Peptide, row.IsotopeLabelType, row.MsLevel)))
            {
                var foldChangeResults = grouping.ToDictionary(row => row.Group, row => row.FoldChangeResult);
                var runAbundances     = new Dictionary <Replicate, ReplicateRow>();
                foreach (var abundance in grouping.SelectMany(row => row.ReplicateAbundances))
                {
                    runAbundances[abundance.Key] = abundance.Value;
                }
                detailRows.Add(new FoldChangeDetailRow(grouping.Key.Item1, grouping.Key.Item2, grouping.Key.Item3, grouping.Key.Item4, foldChangeResults, runAbundances));
            }
            var defaultViewSpec   = GetDefaultViewSpec(rows);
            var clusteredViewSpec = GetClusteredViewSpec(defaultViewSpec);

            var rowSourceInfos = new List <RowSourceInfo>()
            {
                new RowSourceInfo(new StaticRowSource(rows),
                                  new ViewInfo(_skylineDataSchema, typeof(FoldChangeRow), defaultViewSpec).ChangeViewGroup(ViewGroup.BUILT_IN)),
                new RowSourceInfo(new StaticRowSource(detailRows),
                                  new ViewInfo(_skylineDataSchema, typeof(FoldChangeDetailRow), clusteredViewSpec).ChangeViewGroup(ViewGroup.BUILT_IN))
            };

            SetRowSourceInfos(rowSourceInfos);
        }