public void InitializeSpectrumSourceFiles(SrmDocument document) { if (!IsDDASearch) { if (DocLib == null) { return; } var measuredResults = document.Settings.MeasuredResults; foreach (var dataFile in DocLib.LibraryFiles.FilePaths) { var msDataFilePath = new MsDataFilePath(dataFile); SpectrumSourceFiles[dataFile] = new FoundResultsFilePossibilities(msDataFilePath.GetFileNameWithoutExtension()); // If a matching file is already in the document, then don't include // this library spectrum source in the set of files to find. if (measuredResults != null && measuredResults.FindMatchingMSDataFile(MsDataFileUri.Parse(dataFile)) != null) { continue; } if (File.Exists(dataFile) && DataSourceUtil.IsDataSource(dataFile)) { // We've found the dataFile in the exact location // specified in the document library, so just add it // to the "FOUND" list. SpectrumSourceFiles[dataFile].ExactMatch = msDataFilePath.ToString(); } } DocLib.ReadStream.CloseStream(); } }
private void upOneLevelButton_Click(object sender, EventArgs e) { MsDataFileUri parent = null; var dataFilePath = _currentDirectory as MsDataFilePath; if (dataFilePath != null && !string.IsNullOrEmpty(dataFilePath.FilePath)) { DirectoryInfo parentDirectory = Directory.GetParent(dataFilePath.FilePath); if (parentDirectory != null) { parent = new MsDataFilePath(parentDirectory.FullName); } } else { if (_previousDirectories.Any()) { CurrentDirectory = _previousDirectories.Pop(); return; } } if (null != parent && !Equals(parent, _currentDirectory)) { _previousDirectories.Push(_currentDirectory); CurrentDirectory = parent; } }
public KeyValuePair <string, MsDataFileUri[]>[] GetDataSourcePathsFileReplicates(IEnumerable <MsDataFileUri> dataSources) { var listNamedPaths = new List <KeyValuePair <string, MsDataFileUri[]> >(); foreach (var dataSource in dataSources) { MsDataFilePath msDataFilePath = dataSource as MsDataFilePath; // Only .wiff files currently support multiple samples per file. // Keep from doing the extra work on other types. if (null != msDataFilePath && DataSourceUtil.IsWiffFile(msDataFilePath.FilePath)) { var paths = GetWiffSubPaths(msDataFilePath.FilePath); if (paths == null) { return(null); // An error or user cancelation occurred } // Multiple paths then add as samples if (paths.Length > 1 || // If just one, make sure it has a sample part. Otherwise, // drop through to add the entire file. (paths.Length == 1 && paths[0].SampleName != null)) { foreach (var path in paths) { listNamedPaths.Add(new KeyValuePair <string, MsDataFileUri[]>( path.SampleName, new MsDataFileUri[] { path })); } continue; } } listNamedPaths.Add(new KeyValuePair <string, MsDataFileUri[]>( dataSource.GetFileNameWithoutExtension(), new[] { dataSource })); } return(listNamedPaths.ToArray()); }
private string[] FindMissingFiles(IEnumerable <ChromatogramSet> chromatogramSets) { string documentPath = DocumentUIContainer.DocumentFilePath; string cachePath = ChromatogramCache.FinalPathForName(documentPath, null); // Collect all missing paths var listPathsMissing = new List <string>(); // Avoid checking paths multiple times for existence var setPaths = new HashSet <string>(); foreach (var filePath in chromatogramSets.SelectMany(set => set.MSDataFilePaths)) { MsDataFilePath msDataFilePath = filePath as MsDataFilePath; if (null == msDataFilePath) { continue; } string filePathPart = msDataFilePath.FilePath; if (setPaths.Contains(filePathPart)) { continue; } setPaths.Add(filePathPart); if (ChromatogramSet.GetExistingDataFilePath(cachePath, msDataFilePath) != null) { continue; } listPathsMissing.Add(filePathPart); } listPathsMissing.Sort(); return(listPathsMissing.ToArray()); }
public KeyValuePair <string, MsDataFileUri[]>[] GetDataSourcePathsFileSingle(string name, IEnumerable <MsDataFileUri> dataSources) { var listPaths = new List <MsDataFileUri>(); foreach (var dataSource in dataSources) { MsDataFilePath msDataFilePath = dataSource as MsDataFilePath; // Only .wiff files currently support multiple samples per file. // Keep from doing the extra work on other types. if (null != msDataFilePath && DataSourceUtil.IsWiffFile(msDataFilePath.FilePath)) { var paths = GetWiffSubPaths(msDataFilePath.FilePath); if (paths == null) { return(null); // An error or user cancelation occurred } listPaths.AddRange(paths); } else { listPaths.Add(dataSource); } } return(new[] { new KeyValuePair <string, MsDataFileUri[]>(name, listPaths.ToArray()) }); }
private void ExportImport(ResultsTestDocumentContainer docContainer, string resultsPath) { var optRegression = docContainer.Document.Settings.TransitionSettings.Prediction.CollisionEnergy; int optSteps = optRegression.StepCount * 2 + 1; int optSteps1 = optSteps - 1; // First precursor is below 10 volts CE for 1 step int optSteps2 = optSteps - 3; // Second precursor is below 10 volts CE for 3 steps // First export var exporter = new AbiMassListExporter(docContainer.Document) { OptimizeType = ExportOptimize.CE, OptimizeStepCount = optRegression.StepCount, OptimizeStepSize = optRegression.StepSize }; string tranListPath = Path.ChangeExtension(docContainer.DocumentFilePath, TextUtil.EXT_CSV); exporter.Export(tranListPath); // Make sure line count matches expectations for steps below 10 volts CE Assert.AreEqual(5 * optSteps1 + 5 * optSteps2, File.ReadAllLines(tranListPath).Length); // Then import var resultsUri = new MsDataFilePath(resultsPath); var chromSet = new ChromatogramSet("Optimize", new[] { resultsUri }, Annotations.EMPTY, optRegression); var measuredResults = new MeasuredResults(new[] { chromSet }); docContainer.ChangeMeasuredResults(measuredResults, 2, optSteps1 + optSteps2, 5 * optSteps1 + 5 * optSteps2); // Check expected optimization data with missing values for steps below 10 volts CE int expectedMissingSteps = optSteps - optSteps1; foreach (var nodeGroup in docContainer.Document.MoleculeTransitionGroups) { foreach (var nodeTran in nodeGroup.Transitions) { Assert.IsTrue(nodeTran.HasResults, "No results for transition Mz: {0}", nodeTran.Mz); Assert.IsNotNull(nodeTran.Results[0]); Assert.AreEqual(optSteps, nodeTran.Results[0].Count); for (int i = 0; i < optSteps; i++) { if (i < expectedMissingSteps) { Assert.IsTrue(nodeTran.Results[0][i].IsEmpty); } else { Assert.IsFalse(nodeTran.Results[0][i].IsEmpty); } } } expectedMissingSteps = optSteps - optSteps2; } }
private void sourcePathTextBox_KeyUp(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Enter: if (Directory.Exists(sourcePathTextBox.Text)) { CurrentDirectory = new MsDataFilePath(sourcePathTextBox.Text); } else if (CurrentDirectory is MsDataFilePath && Directory.Exists(Path.Combine(((MsDataFilePath)CurrentDirectory).FilePath, sourcePathTextBox.Text))) { CurrentDirectory = new MsDataFilePath(Path.Combine(((MsDataFilePath)CurrentDirectory).FilePath, sourcePathTextBox.Text)); } else if (CurrentDirectory is MsDataFilePath) { // check that all manually-entered paths are valid string[] sourcePaths = sourcePathTextBox.Text.Split(" ".ToCharArray()); // Not L10N List <string> invalidPaths = new List <string>(); foreach (string path in sourcePaths) { if (!File.Exists(path) && !File.Exists(Path.Combine(((MsDataFilePath)CurrentDirectory).FilePath, path))) { invalidPaths.Add(path); } } if (invalidPaths.Count == 0) { DataSources = sourcePaths.Select(MsDataFileUri.Parse).ToArray(); DialogResult = DialogResult.OK; Close(); } else { MessageBox.Show(this, TextUtil.LineSeparate(invalidPaths), Resources.OpenDataSourceDialog_sourcePathTextBox_KeyUp_Some_source_paths_are_invalid); } } break; case Keys.F5: _abortPopulateList = true; populateListViewFromDirectory(_currentDirectory); // refresh break; } }
private void Import(ResultsTestDocumentContainer docContainer, string resultsPath, bool optFlag) { var optRegression = optFlag ? docContainer.Document.Settings.TransitionSettings.Prediction.CollisionEnergy : null; int optSteps = optRegression != null ? optRegression.StepCount * 2 + 1 : 1; var resultsUri = new MsDataFilePath(resultsPath); var chromSet = new ChromatogramSet("Optimize", new[] { resultsUri }, Annotations.EMPTY, optRegression); var measuredResults = new MeasuredResults(new[] { chromSet }); docContainer.ChangeMeasuredResults(measuredResults, 1, 1 * optSteps, 3 * optSteps); // Check expected optimization data. foreach (var nodeTran in docContainer.Document.MoleculeTransitions) { Assert.IsTrue(nodeTran.HasResults, "No results for transition Mz: {0}", nodeTran.Mz); Assert.IsNotNull(nodeTran.Results[0]); Assert.AreEqual(optSteps, nodeTran.Results[0].Count); } }
private void ImportResults(string prefix, string[] paths, string optimization, bool addNew = true) { var importResultsDlg = ShowDialog <ImportResultsDlg>(SkylineWindow.ImportResults); RunUI(() => { if (addNew) { importResultsDlg.RadioAddNewChecked = true; importResultsDlg.ReplicateName = prefix; importResultsDlg.OptimizationName = optimization; } var files = new MsDataFileUri[paths.Length]; for (int i = 0; i < paths.Length; i++) { files[i] = new MsDataFilePath(GetTestPath(paths[i])); } var keyPair = new KeyValuePair <string, MsDataFileUri[]>(prefix, files); KeyValuePair <string, MsDataFileUri[]>[] pathHolder = addNew ? new[] { keyPair } : importResultsDlg.GetDataSourcePathsFileReplicates(files); importResultsDlg.NamedPathSets = pathHolder; }); if (addNew) { OkDialog(importResultsDlg, importResultsDlg.OkDialog); } else { var keepPrefixDlg = ShowDialog <ImportResultsNameDlg>(importResultsDlg.OkDialog); RunUI(keepPrefixDlg.NoDialog); WaitForClosedForm(keepPrefixDlg); WaitForClosedForm(importResultsDlg); } WaitForDocumentLoaded(); WaitForClosedForm <AllChromatogramsGraph>(); }
public void Open() { List <MsDataFileUri> dataSourceList = new List <MsDataFileUri>(); foreach (ListViewItem item in listView.SelectedItems) { if (!DataSourceUtil.IsFolderType(item.SubItems[1].Text)) { dataSourceList.Add(((SourceInfo)item.Tag).MsDataFileUri); } } if (dataSourceList.Count > 0) { DataSources = dataSourceList.ToArray(); _abortPopulateList = true; DialogResult = DialogResult.OK; return; } // No files selected: see if there is a folder selected that we // should navigate to foreach (ListViewItem item in listView.SelectedItems) { if (DataSourceUtil.IsFolderType(item.SubItems[1].Text)) { OpenFolderItem(item); return; } } try { // perhaps the user has typed an entire filename into the text box - or just garbage var fileOrDirName = sourcePathTextBox.Text; bool exists; bool triedAddingDirectory = false; while (!(exists = ((File.Exists(fileOrDirName) || Directory.Exists(fileOrDirName))))) { if (triedAddingDirectory) { break; } MsDataFilePath currentDirectoryPath = CurrentDirectory as MsDataFilePath; if (null == currentDirectoryPath) { break; } fileOrDirName = Path.Combine(currentDirectoryPath.FilePath, fileOrDirName); triedAddingDirectory = true; } if (exists) { if (DataSourceUtil.IsDataSource(fileOrDirName)) { DataSources = new[] { MsDataFileUri.Parse(fileOrDirName) }; DialogResult = DialogResult.OK; return; } else if (Directory.Exists(fileOrDirName)) { OpenFolder(new MsDataFilePath(fileOrDirName)); return; } } } // ReSharper disable once EmptyGeneralCatchClause catch {} // guard against user typed-in-garbage // No files or folders selected: Show an error message. MessageDlg.Show(this, Resources.OpenDataSourceDialog_Open_Please_select_one_or_more_data_sources); }
private void populateComboBoxFromDirectory(MsDataFileUri directory) { lookInComboBox.SuspendLayout(); // remove old drive entries while (lookInComboBox.Items.Count > _specialFolderCount) { lookInComboBox.Items.RemoveAt(_specialFolderCount); } TreeNode myComputerNode = (TreeNode)lookInComboBox.Items[_myComputerIndex]; DirectoryInfo dirInfo = null; if (directory is MsDataFilePath) { MsDataFilePath msDataFilePath = (MsDataFilePath)directory; if (!string.IsNullOrEmpty(msDataFilePath.FilePath)) { dirInfo = new DirectoryInfo(msDataFilePath.FilePath); } } if (dirInfo == null) { if (directory is RemoteUrl) { lookInComboBox.SelectedIndex = _remoteIndex; } else { lookInComboBox.SelectedIndex = _myComputerIndex; } } int driveCount = 0; foreach (DriveInfo driveInfo in DriveInfo.GetDrives()) { string label = string.Empty; string sublabel = driveInfo.Name; ImageIndex imageIndex = ImageIndex.Folder; ++driveCount; _driveReadiness[sublabel] = false; try { switch (driveInfo.DriveType) { case DriveType.Fixed: imageIndex = ImageIndex.LocalDrive; label = Resources.OpenDataSourceDialog_populateComboBoxFromDirectory_Local_Drive; if (driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.CDRom: imageIndex = ImageIndex.OpticalDrive; label = Resources.OpenDataSourceDialog_populateComboBoxFromDirectory_Optical_Drive; if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.Removable: imageIndex = ImageIndex.OpticalDrive; label = Resources.OpenDataSourceDialog_populateComboBoxFromDirectory_Removable_Drive; if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.Network: label = Resources.OpenDataSourceDialog_populateComboBoxFromDirectory_Network_Share; break; } _driveReadiness[sublabel] = IsDriveReady(driveInfo); } catch (Exception) { label += string.Format(@" ({0})", Resources.OpenDataSourceDialog_populateComboBoxFromDirectory_access_failure); } TreeNode driveNode = myComputerNode.Nodes.Add(sublabel, label.Length > 0 ? String.Format(@"{0} ({1})", label, sublabel) : sublabel, (int)imageIndex, (int)imageIndex); driveNode.Tag = new MsDataFilePath(sublabel); lookInComboBox.Items.Insert(_specialFolderCount + driveCount - 1, driveNode); if (dirInfo != null && sublabel == dirInfo.Root.Name) { List <string> branches = new List <string>(((MsDataFilePath)directory).FilePath.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries)); TreeNode pathNode = driveNode; for (int i = 1; i < branches.Count; ++i) { ++driveCount; pathNode = pathNode.Nodes.Add(branches[i], branches[i], 8, 8); pathNode.Tag = new MsDataFilePath(String.Join(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), branches.GetRange(0, i + 1).ToArray())); lookInComboBox.Items.Insert(_specialFolderCount + driveCount - 1, pathNode); } lookInComboBox.SelectedIndex = _specialFolderCount + driveCount - 1; } } //desktopNode.Nodes.Add( "My Network Places", "My Network Places", 4, 4 ).Tag = "My Network Places"; lookInComboBox.DropDownHeight = lookInComboBox.Items.Count * 18 + 2; lookInComboBox.ResumeLayout(); }
private void populateListViewFromDirectory(MsDataFileUri directory) { _abortPopulateList = false; listView.Cursor = Cursors.Default; _waitingForData = false; listView.Items.Clear(); var listSourceInfo = new List <SourceInfo>(); if (null == directory || directory is MsDataFilePath && string.IsNullOrEmpty(((MsDataFilePath)directory).FilePath)) { foreach (DriveInfo driveInfo in DriveInfo.GetDrives()) { string label = string.Empty; string sublabel = driveInfo.Name; ImageIndex imageIndex = ImageIndex.Folder; _driveReadiness[sublabel] = false; try { switch (driveInfo.DriveType) { case DriveType.Fixed: imageIndex = ImageIndex.LocalDrive; label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Local_Drive; if (driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.CDRom: imageIndex = ImageIndex.OpticalDrive; label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Optical_Drive; if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.Removable: imageIndex = ImageIndex.OpticalDrive; label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Removable_Drive; if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0) { label = driveInfo.VolumeLabel; } break; case DriveType.Network: label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Network_Share; break; } _driveReadiness[sublabel] = IsDriveReady(driveInfo); } catch (Exception) { label += string.Format(@" ({0})", Resources.OpenDataSourceDialog_populateListViewFromDirectory_access_failure); } string name = driveInfo.Name; if (label != string.Empty) { name = string.Format(@"{0} ({1})", label, name); } listSourceInfo.Add(new SourceInfo(new MsDataFilePath(driveInfo.RootDirectory.FullName)) { type = DataSourceUtil.FOLDER_TYPE, imageIndex = imageIndex, name = name, dateModified = GetDriveModifiedTime(driveInfo) }); } } else if (directory is RemoteUrl) { RemoteUrl remoteUrl = directory as RemoteUrl; if (string.IsNullOrEmpty(remoteUrl.ServerUrl)) { foreach (var remoteAccount in _remoteAccounts) { listSourceInfo.Add(new SourceInfo(remoteAccount.GetRootUrl()) { name = remoteAccount.GetKey(), type = DataSourceUtil.FOLDER_TYPE, imageIndex = ImageIndex.MyNetworkPlaces, }); } } else { RemoteAccount remoteAccount = GetRemoteAccount(remoteUrl); if (RemoteSession == null || !Equals(remoteAccount, RemoteSession.Account)) { RemoteSession = RemoteSession.CreateSession(remoteAccount); } RemoteServerException exception; bool isComplete = _remoteSession.AsyncFetchContents(remoteUrl, out exception); foreach (var item in _remoteSession.ListContents(remoteUrl)) { var imageIndex = DataSourceUtil.IsFolderType(item.Type) ? ImageIndex.Folder : ImageIndex.MassSpecFile; listSourceInfo.Add(new SourceInfo(item.MsDataFileUri) { name = item.Label, type = item.Type, imageIndex = imageIndex, dateModified = item.LastModified, size = item.FileSize }); } if (null != exception) { if (MultiButtonMsgDlg.Show(this, exception.Message, Resources.OpenDataSourceDialog_populateListViewFromDirectory_Retry) != DialogResult.Cancel) { RemoteSession.RetryFetchContents(remoteUrl); isComplete = false; } } if (!isComplete) { listView.Cursor = Cursors.WaitCursor; _waitingForData = true; } } } else if (directory is MsDataFilePath) { MsDataFilePath msDataFilePath = (MsDataFilePath)directory; DirectoryInfo dirInfo = new DirectoryInfo(msDataFilePath.FilePath); try { // subitems: Name, Type, Spectra, Size, Date Modified var arraySubDirInfo = dirInfo.GetDirectories(); Array.Sort(arraySubDirInfo, (d1, d2) => string.Compare(d1.Name, d2.Name, StringComparison.CurrentCultureIgnoreCase)); var arrayFileInfo = dirInfo.GetFiles(); Array.Sort(arrayFileInfo, (f1, f2) => string.Compare(f1.Name, f2.Name, StringComparison.CurrentCultureIgnoreCase)); // Calculate information about the files, allowing the user to cancel foreach (var info in arraySubDirInfo) { listSourceInfo.Add(getSourceInfo(info)); Application.DoEvents(); if (_abortPopulateList) { //MessageBox.Show( "abort" ); break; } } if (!_abortPopulateList) { foreach (var info in arrayFileInfo) { listSourceInfo.Add(getSourceInfo(info)); Application.DoEvents(); if (_abortPopulateList) { //MessageBox.Show( "abort" ); break; } } } } catch (Exception x) { var message = TextUtil.LineSeparate( Resources.OpenDataSourceDialog_populateListViewFromDirectory_An_error_occurred_attempting_to_retrieve_the_contents_of_this_directory, x.Message); // Might throw access violation. MessageDlg.ShowWithException(this, message, x); return; } } // Populate the list var items = new List <ListViewItem>(); foreach (var sourceInfo in listSourceInfo) { if (sourceInfo != null && (sourceTypeComboBox.SelectedIndex == 0 || sourceTypeComboBox.SelectedItem.ToString() == sourceInfo.type || // Always show folders sourceInfo.isFolder)) { ListViewItem item = new ListViewItem(sourceInfo.ToArray(), (int)sourceInfo.imageIndex) { Tag = sourceInfo, }; item.SubItems[2].Tag = sourceInfo.size; item.SubItems[3].Tag = sourceInfo.dateModified; items.Add(item); } } listView.Items.AddRange(items.ToArray()); }
private void recentDocumentsButton_Click(object sender, EventArgs e) { CurrentDirectory = new MsDataFilePath(Environment.GetFolderPath(Environment.SpecialFolder.Recent)); }
private void desktopButton_Click(object sender, EventArgs e) { CurrentDirectory = new MsDataFilePath(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)); }
public static bool IsWiffFile(MsDataFileUri fileName) { MsDataFilePath msDataFilePath = fileName as MsDataFilePath; return(null != msDataFilePath && IsWiffFile(msDataFilePath.FilePath)); }
private void myComputerButton_Click(object sender, EventArgs e) { CurrentDirectory = new MsDataFilePath(Environment.GetFolderPath(Environment.SpecialFolder.MyComputer)); }
public SrmDocument Import(TextReader reader, IProgressMonitor progressMonitor, long lineCount, bool isMinutes, bool removeMissing = false, bool changePeaks = true) { IProgressStatus status = new ProgressStatus(Resources.PeakBoundaryImporter_Import_Importing_Peak_Boundaries); double timeConversionFactor = isMinutes ? 1.0 : 60.0; int linesRead = 0; int progressPercent = 0; var docNew = (SrmDocument)Document.ChangeIgnoreChangingChildren(true); var docReference = docNew; var sequenceToNode = MakeSequenceDictionary(Document); var fileNameToFileMatch = new Dictionary <Tuple <string, string>, ChromSetFileMatch>(); var trackAdjustedResults = new HashSet <ResultsKey>(); var modMatcher = new ModificationMatcher(); var canonicalSequenceDict = new Dictionary <string, string>(); // Add annotations as possible columns var allFieldNames = new List <string[]>(FIELD_NAMES); allFieldNames.AddRange(from def in Document.Settings.DataSettings.AnnotationDefs where def.AnnotationTargets.Contains(AnnotationDef.AnnotationTarget.precursor_result) select new[] { def.Name }); string line = reader.ReadLine(); linesRead++; int[] fieldIndices; int fieldsTotal; // If we aren't changing peaks, allow start and end time to be missing var requiredFields = changePeaks ? REQUIRED_FIELDS : REQUIRED_NO_CHROM; char correctSeparator = ReadFirstLine(line, allFieldNames, requiredFields, out fieldIndices, out fieldsTotal); while ((line = reader.ReadLine()) != null) { linesRead++; if (progressMonitor != null) { if (progressMonitor.IsCanceled) { return(Document); } int progressNew = (int)(linesRead * 100 / lineCount); if (progressPercent != progressNew) { progressMonitor.UpdateProgress(status = status.ChangePercentComplete(progressNew)); progressPercent = progressNew; } } var dataFields = new DataFields(fieldIndices, line.ParseDsvFields(correctSeparator), allFieldNames); if (dataFields.Length != fieldsTotal) { throw new IOException(string.Format(Resources.PeakBoundaryImporter_Import_Line__0__field_count__1__differs_from_the_first_line__which_has__2_, linesRead, dataFields.Length, fieldsTotal)); } string modifiedPeptideString = dataFields.GetField(Field.modified_peptide); string fileName = dataFields.GetField(Field.filename); bool isDecoy = dataFields.IsDecoy(linesRead); IList <IdentityPath> pepPaths; if (!sequenceToNode.TryGetValue(Tuple.Create(modifiedPeptideString, isDecoy), out pepPaths)) { string canonicalSequence; if (!canonicalSequenceDict.TryGetValue(modifiedPeptideString, out canonicalSequence)) { if (modifiedPeptideString.Any(c => c < 'A' || c > 'Z')) { modMatcher.CreateMatches(Document.Settings, new List <string> { modifiedPeptideString }, Settings.Default.StaticModList, Settings.Default.HeavyModList); var nodeForModPep = modMatcher.GetModifiedNode(modifiedPeptideString); if (nodeForModPep == null) { throw new IOException(string.Format(Resources.PeakBoundaryImporter_Import_Peptide_has_unrecognized_modifications__0__at_line__1_, modifiedPeptideString, linesRead)); } nodeForModPep = nodeForModPep.ChangeSettings(Document.Settings, SrmSettingsDiff.ALL); // Convert the modified peptide string into a standardized form that // converts unimod, names, etc, into masses, eg [+57.0] canonicalSequence = nodeForModPep.ModifiedTarget.Sequence; canonicalSequenceDict.Add(modifiedPeptideString, canonicalSequence); } } if (null != canonicalSequence) { sequenceToNode.TryGetValue(Tuple.Create(canonicalSequence, isDecoy), out pepPaths); } } if (null == pepPaths) { UnrecognizedPeptides.Add(modifiedPeptideString); continue; } Adduct charge; bool chargeSpecified = dataFields.TryGetCharge(linesRead, out charge); string sampleName = dataFields.GetField(Field.sample_name); double?apexTime = dataFields.GetTime(Field.apex_time, timeConversionFactor, Resources.PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_time_, linesRead); double?startTime = dataFields.GetTime(Field.start_time, timeConversionFactor, Resources.PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_start_time_, linesRead); double?endTime = dataFields.GetTime(Field.end_time, timeConversionFactor, Resources.PeakBoundaryImporter_Import_The_value___0___on_line__1__is_not_a_valid_end_time_, linesRead); // Error if only one of startTime and endTime is null if (startTime == null && endTime != null) { if (changePeaks) { throw new IOException(string.Format(Resources.PeakBoundaryImporter_Import_Missing_start_time_on_line__0_, linesRead)); } endTime = null; } if (startTime != null && endTime == null) { if (changePeaks) { throw new IOException(string.Format(Resources.PeakBoundaryImporter_Import_Missing_end_time_on_line__0_, linesRead)); } startTime = null; } Tuple <string, string> fileKey = Tuple.Create(fileName, sampleName); // Add filename to second dictionary if not yet encountered ChromSetFileMatch fileMatch; if (!fileNameToFileMatch.TryGetValue(fileKey, out fileMatch) && Document.Settings.HasResults) { var dataFileUri = MsDataFileUri.Parse(fileName); if (sampleName != null && dataFileUri is MsDataFilePath msDataFilePath) { var uriWithSample = new MsDataFilePath(msDataFilePath.FilePath, sampleName, msDataFilePath.SampleIndex, msDataFilePath.LockMassParameters); fileMatch = Document.Settings.MeasuredResults.FindMatchingMSDataFile(uriWithSample); if (fileMatch == null) { var bareFileMatch = Document.Settings.MeasuredResults.FindMatchingMSDataFile(dataFileUri); if (bareFileMatch != null) { throw new IOException(string.Format(Resources.PeakBoundaryImporter_Import_Sample__0__on_line__1__does_not_match_the_file__2__, sampleName, linesRead, fileName)); } } } else { fileMatch = Document.Settings.MeasuredResults.FindMatchingMSDataFile(dataFileUri); } fileNameToFileMatch.Add(fileKey, fileMatch); } if (fileMatch == null) { UnrecognizedFiles.Add(fileName); continue; } var chromSet = fileMatch.Chromatograms; string nameSet = chromSet.Name; var fileId = chromSet.FindFile(fileMatch.FilePath); // Define the annotations to be added var annotations = dataFields.GetAnnotations(); if (!changePeaks) { if (apexTime.HasValue) { annotations.Add(ComparePeakBoundaries.APEX_ANNOTATION, dataFields.GetField(Field.apex_time)); } if (startTime.HasValue && endTime.HasValue) { annotations.Add(ComparePeakBoundaries.START_TIME_ANNOTATION, dataFields.GetField(Field.start_time)); annotations.Add(ComparePeakBoundaries.END_TIME_ANNOTATION, dataFields.GetField(Field.end_time)); } } AnnotationsAdded = annotations.Keys.ToList(); // Loop over all the transition groups in that peptide to find matching charge, // or use all transition groups if charge not specified bool foundSample = false; foreach (var pepPath in pepPaths) { var nodePep = (PeptideDocNode)docNew.FindNode(pepPath); foreach (TransitionGroupDocNode groupNode in nodePep.Children) { if (chargeSpecified && charge != groupNode.TransitionGroup.PrecursorAdduct) { continue; } // Loop over the files in this groupNode to find the correct sample // Change peak boundaries for the transition group if (!groupNode.ChromInfos.Any(info => ReferenceEquals(info.FileId, fileId))) { continue; } var groupPath = new IdentityPath(pepPath, groupNode.Id); // Attach annotations if (annotations.Any()) { docNew = docNew.AddPrecursorResultsAnnotations(groupPath, fileId, annotations); } // Change peak var filePath = chromSet.GetFileInfo(fileId).FilePath; if (changePeaks) { docNew = docNew.ChangePeak(groupPath, nameSet, filePath, null, startTime, endTime, UserSet.IMPORTED, null, false); } // For removing peaks that are not in the file, if removeMissing = true trackAdjustedResults.Add(new ResultsKey(fileId.GlobalIndex, groupNode.Id)); foundSample = true; } } if (!foundSample) { UnrecognizedChargeStates.Add(new UnrecognizedChargeState(charge, fileName, modifiedPeptideString)); } } // Remove peaks from the document that weren't in the file. if (removeMissing) { docNew = RemoveMissing(docNew, trackAdjustedResults, changePeaks); } // If nothing has changed, return the old Document before ChangeIgnoreChangingChildren was turned off if (!ReferenceEquals(docNew, docReference)) { Document = (SrmDocument)Document.ChangeIgnoreChangingChildren(false).ChangeChildrenChecked(docNew.Children); } return(Document); }