// To match this
        // 	    New File  		 2008/02/06 09:16:49	E:\copytest\src\file2.txt
        Modification ParseAddedFile(
			string logLine)
        {
            Match match = ParseAddedFileRegex.Match(logLine);

            if (match.Success)
            {
                if (match.Groups.Count == 3)
                {
                    string date = match.Groups["Date"].Captures[0].ToString();
                    string path = match.Groups["Path"].Captures[0].ToString();

                    Modification mod = new Modification();

                    mod.Type = "added";

                    mod.FileName = Path.GetFileName(path);
                    mod.FolderName = Path.GetDirectoryName(path);

                    mod.ModifiedTime = CreateDate(date);

                    return mod;
                }
            }

            throw new Exception("Failed to match regex");
        }
 /// <summary>
 /// Setups the modification.	
 /// </summary>
 /// <param name="modifications">The modifications.</param>
 /// <remarks></remarks>
 public void SetupModification(Modification[] modifications)
 {            
     foreach (IModificationUrlBuilder modificationUrlBuilder in _issueTrackers)
     {
         modificationUrlBuilder.SetupModification(modifications);          
     }            
 }
        /// <summary>
		/// Construct and return an array of Modifications describing the changes in
		/// the AccuRev workspace, based on the output of the "accurev hist" command.
		/// </summary>
        /// <param name="history">the stream of <code>&lt;modifications&gt;</code> input</param>
		/// <param name="from">the starting date and time for the range of modifications we want.</param>
		/// <param name="to">the ending date and time for the range of modifications we want.</param>
		/// <returns>the changes in the specified time range.</returns>
		public Modification[] Parse(TextReader history, DateTime from, DateTime to)
        {
        	XmlSerializer serializer = new XmlSerializer(typeof (Modification[]));
			Modification[] mods = new Modification[0];
        	try
        	{
        		// return 0 modifications if "history" is empty.
        		if (history.Peek() == -1)
					return mods;

        		mods = (Modification[]) serializer.Deserialize(history);
        	}
        	catch (InvalidOperationException e)
        	{
				Log.Error(e);

        		if (e.InnerException is XmlException)
					return mods;

        		throw;
        	}
            var results = new List<Modification>();

        	foreach (Modification mod in mods)
        	{
        		if ((mod.ModifiedTime >= from) & (mod.ModifiedTime <= to))
        			results.Add(mod);
        	}
        	return results.ToArray();
        }
		/// <summary>
		/// Setups the modification.
		/// </summary>
		/// <param name="modifications">The modifications.</param>
		/// <remarks></remarks>
		public void SetupModification(Modification[] modifications)
		{
			foreach (Modification modification in modifications)
			{
				modification.Url = Url + "rev/" + modification.Version;
			}
		}
        /// <summary>
        /// Gets the modifications from the source control provider
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
		public Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
		{
            if (FailGetModifications)
            {
                throw new System.Exception("Failing GetModifications");
            }
            else if (AlwaysModified)
            {
                Modification[] mods = new Modification[1];
                Modification mod = new Modification();
                mod.FileName = "AlwaysModified";
                mod.FolderName = "NullSourceControl";
                mod.ModifiedTime = DateTime.Now;
                mod.UserName = "******";
                mod.ChangeNumber = Guid.NewGuid().ToString("N");
                mod.Comment = "Making a change";
                mod.Type = "modified";
                mods[0] = mod;
                return mods;
            }
            else
            {
                return new Modification[0];
            }
		}
        /// <summary>
        /// Parses the specified input.	
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <returns></returns>
        /// <remarks></remarks>
		public Modification[] Parse(TextReader input, DateTime from, DateTime to)
		{
            var mods = new List<Modification>();
            var filemods = new List<string>();

			string line;

			while( (line = input.ReadLine()) != null )
			{
				if( !line.StartsWith(PlasticSCM.DELIMITER.ToString(CultureInfo.CurrentCulture)))
					continue;
				// path date user changeset
				string[] data = line.Split(PlasticSCM.DELIMITER);
				Modification mod = new Modification();
				string path = data[1];
				mod.FileName = Path.GetFileName(path);
				mod.FolderName = Path.GetDirectoryName(path);
				mod.UserName = data[2];
				mod.ModifiedTime = DateTime.ParseExact (data[3], PlasticSCM.DATEFORMAT, CultureInfo.InvariantCulture);
				mod.ChangeNumber =  data[4];
				if (!filemods.Contains(path)) 
				{
					filemods.Add(path);
					mods.Add(mod);
				}
			}
			return mods.ToArray();
			
		}
 public void SetupModification(Modification[] modifications)
 {
     foreach( Modification mod in modifications )
     {
         mod.Url = String.Format( _url, mod.FolderName + "/" + mod.FileName, mod.ChangeNumber );
     }
 }
Example #8
0
 public void SetupModification(Modification[] modifications)
 {
     foreach (Modification mod in modifications)
     {
         mod.Url = String.Format(_url, mod.FolderName.Length == 0 ? mod.FileName : mod.FolderName + "/" + mod.FileName);
     }
 }
        /// <summary>
        /// Parse a commit for modifications and returns a list with every modification in the date/time limits.
        /// </summary>
        /// <param name="commitMatch"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        private static IList<Modification> GetCommitModifications(Match commitMatch, DateTime from, DateTime to)
        {
            IList<Modification> result = new List<Modification>();

            string hash = commitMatch.Groups["Hash"].Value;
            DateTime modifiedTime = DateTime.Parse(commitMatch.Groups["Time"].Value);
            string username = commitMatch.Groups["Author"].Value;
            string emailAddress = commitMatch.Groups["Mail"].Value;
            string comment = commitMatch.Groups["Message"].Value.TrimEnd('\r', '\n');
            string changes = commitMatch.Groups["Changes"].Value;

            if (modifiedTime < from || modifiedTime > to)
            {
                Log.Debug(string.Concat("[Git] Ignore commit '", hash, "' from '", modifiedTime.ToUniversalTime(),
                                        "' because it is older then '",
                                        from.ToUniversalTime(), "' or newer then '", to.ToUniversalTime(), "'."));
                return result;
            }

            MatchCollection file_matches = changeList.Matches(changes);
            if (file_matches.Count != 0)
            {
                foreach (Match change in file_matches)
                {
                    Modification mod = new Modification();
                    mod.ChangeNumber = hash;
                    mod.Comment = comment;
                    mod.EmailAddress = emailAddress;
                    mod.ModifiedTime = modifiedTime;
                    mod.UserName = username;

                    mod.Type = GetModificationType(change.Groups["Type"].Value);

                    string fullFilePath = change.Groups["FileName"].Value.TrimEnd('\r', '\n');
                    mod.FileName = GetFileFromPath(fullFilePath);
                    mod.FolderName = GetFolderFromPath(fullFilePath);

                    result.Add(mod);
                }
            }
            else
            {
                Modification mod = new Modification();
                mod.ChangeNumber = hash;
                mod.Comment = comment;
                mod.EmailAddress = emailAddress;
                mod.ModifiedTime = modifiedTime;
                mod.UserName = username;

                mod.Type = GetModificationType("m");

                mod.FileName = "Specific commit. No file changes.";
                mod.FolderName = "";

                result.Add(mod);
            }

            return result;
        }
 private DateTime firstModifiedTime(Modification[] modifications)
 {
     DateTime subResult = modifications[0].ModifiedTime;
     foreach (Modification modification in modifications)
         if (modification.ModifiedTime < subResult)
             subResult = modification.ModifiedTime;
     return subResult;
 }
Example #11
0
 public bool Accept(Modification modification)
 {
     if (modification.FolderName == null || modification.FileName == null)
     {
         return false;
     }
     string path = Path.Combine(modification.FolderName, modification.FileName);
     return PathUtils.MatchPath(Pattern, path, caseSensitive);
 }
Example #12
0
        /// <summary>
        /// Build the Modification list of what files will be built 
        /// with this Release
        /// </summary>
        /// <param name="mods"></param>
        /// <returns></returns>
        public static Modification[] AnalyzeModifications(IList mods)
        {
            // Hashtables are used so we can compare on the keys in search of duplicates
            Hashtable allFiles = new Hashtable();
            foreach (Modification mod in mods)
            {
                string key = mod.FolderName + mod.FileName;
                if (!allFiles.ContainsKey(key))
                    allFiles.Add(key, mod);
                else
                {
                    // If the revision number on the original is larger, then
                    // do the comparision against the original modification
                    // in search to see which revision is higher
                    // example: 1.64.1 < 1.65 but you need to compare against the
                    // larger string of 1.64.1 because we are splitting the numbers individually
                    // so 1 is compared to 1 and 64 is compared to 65.
                    Modification compareMod = allFiles[key] as Modification;
                    string[] originalVersion = compareMod.Version.Split(char.Parse("."));
                    string[] currentVersion = mod.Version.Split(char.Parse("."));
                    int len1 = originalVersion.Length;
                    int len2 = currentVersion.Length;
                    int usingLen = -1;
                    int otherLen = -1;
                    if (len1 >= len2)
                    {
                        usingLen = len1;
                        otherLen = len2;
                    }
                    else
                    {
                        usingLen = len2;
                        otherLen = len1;
                    }

                    for (int i = 0; i < usingLen; i++)
                    {
                        if (i > otherLen)
                            continue;
                        if (Convert.ToInt32(currentVersion[i]) > Convert.ToInt32(originalVersion[i]))
                        {
                            allFiles[compareMod.FolderName + compareMod.FileName] = mod;
                            break;
                        }
                    }
                }
            }
            // Convert the Hashtables to Modification arrays
            Modification[] validMods = new Modification[allFiles.Count];
            int count = 0;
            foreach (string key in allFiles.Keys)
            {
                validMods[count++] = allFiles[key] as Modification;
            }
            return validMods;
        }
Example #13
0
 public void SendMessageToModifiersWhoCheckedInTheFiles(Modification[] modifications, String Message)
 {
     foreach (Modification modification in modifications)
     {
         YahooUser yuser = GetYahooUser(modification.UserName);
         if (yuser!=null)
         {
             YahooWrap.SendYahooMessage(yuser.ID, Message);
         }
     }
 }
        public void LastModificationDate()
        {
            Modification earlierModification = new Modification();
            earlierModification.ModifiedTime = new DateTime(0);

            Modification laterModification = new Modification();
            laterModification.ModifiedTime = new DateTime(1);

            result.Modifications = new Modification[] { earlierModification, laterModification };
            Assert.AreEqual(laterModification.ModifiedTime, result.LastModificationDate);
        }
 public void AssignModificationTime( Modification modification, string time )
 {
     try
     {
         modification.ModifiedTime = DateTime.Parse( time );
     }
     catch ( FormatException )
     {
         modification.ModifiedTime = DateTime.MinValue;
     }
 }
		private static Modification ParseModification(Match revision, string path, DateTime createdDate)
		{
			Modification mod = new Modification();
			mod.Comment = revision.Groups["Comment"].Value.Trim();
			mod.FileName = Path.GetFileName(path);
			mod.FolderName = Path.GetDirectoryName(path).Trim();
			mod.ModifiedTime = Pvcs.GetDate(revision.Groups["CheckIn"].Value.Trim());
			mod.UserName = revision.Groups["Author"].Value.Trim();
			mod.Version = revision.Groups["Version"].Value.Trim();
			mod.Type = (mod.ModifiedTime == createdDate) ? "New" : "Checked in";
			return mod;
		}
 public ModificationPhaseFactory(IPofSerializer pofSerializer, IFileSystemProxy fileSystemProxy, TemporaryFileService temporaryFileService, ExeggutorService exeggutorService, ModificationPhaseManager phaseManager, ModificationLoader modificationLoader, ModificationViewModel viewModel, LeagueBuildUtilities leagueBuildUtilities, Modification modification)
 {
     this.pofSerializer = pofSerializer;
      this.fileSystemProxy = fileSystemProxy;
      this.temporaryFileService = temporaryFileService;
      this.exeggutorService = exeggutorService;
      this.phaseManager = phaseManager;
      this.modificationLoader = modificationLoader;
      this.viewModel = viewModel;
      this.leagueBuildUtilities = leagueBuildUtilities;
      this.modification = modification;
 }
Example #18
0
 private string GetModificationsDetectedMessage(Modification[] modifications)
 {
     switch (modifications.Length)
     {
         case 0:
             return "No modifications detected.";
         case 1:
             return "1 modification detected.";
         default:
             return string.Format("{0} modifications detected.", modifications.Length);
     }
 }
Example #19
0
        public ModificationForm(Modification modification)
        {
            InitializeComponent();

            RevivalMod = modification;

            // Set tab size
            int EM_SETTABSTOPS = 0x00CB;
            Graphics graphics = releaseNotesTextBox.CreateGraphics();
            int characterWidth = (int)graphics.MeasureString("M", releaseNotesTextBox.Font).Width;
            int tabWidth = 1;
            SendMessage(releaseNotesTextBox.Handle, EM_SETTABSTOPS, 1, new int[] { tabWidth * characterWidth });
        }
 private Modification GenerateModification(string name, string type)
 {
     Modification modification = new Modification();
     modification.ChangeNumber = "1";
     modification.Comment = "A comment";
     modification.EmailAddress = "*****@*****.**";
     modification.FileName = name;
     modification.ModifiedTime = new DateTime(2009, 1, 1);
     modification.Type = type;
     modification.UserName = "******";
     modification.Version = "1.1.1.1";
     return modification;
 }
 public void WriteModifications(Modification[] mods)
 {
     writer.WriteStartElement(Elements.MODIFICATIONS);
     if (mods == null)
     {
         return;
     }
     foreach (Modification mod in mods)
     {
         mod.ToXml(writer);
     }
     writer.WriteEndElement();
 }
		/// <summary>
		/// Parses output from p4.exe obtained using arguments <code>p4 -s describe -s 123</code>
		/// where 123 (etc...) are changelist numbers.  This output looks like this:
		/// <p>
		/// <code>
		/// text: Change 123 by user@hostname on 2002/08/21 14:39:52
		/// text:
		/// text:   The checkin comment
		/// text:
		/// text: Affected files ...
		/// text:
		/// info1: //view/path/filename.java#1 add
		/// text:
		/// exit: 0
		/// </code>
		/// </p>
		/// the type appears at the end of the info1 line, and may be add, edit, delete etc...
		/// Two regex strings are used to match the first line, and the 'info1:' line.
		/// NOTE there's a tab character before comment text.
		/// </summary>
		/// <param name="reader"></param>
        /// <param name="from"></param>
        /// <param name="to"></param>
		/// <returns></returns>
		public Modification[] Parse(TextReader reader, DateTime from, DateTime to)
		{
            var mods = new List<Modification>();
			string line;
			string change = null, email = null, user = null, comment = string.Empty;
			DateTime date = DateTime.Now;
			while((line = reader.ReadLine()) != null)
			{
				Match modificationMatch = modRegex.Match(line);
				if (modificationMatch.Success)
				{
					// when this line is matched, we're finished with this mod, so add it
					Modification mod = new Modification();
					mod.ChangeNumber = change;
					mod.Version = modificationMatch.Groups["revision"].Value;
					mod.FolderName = modificationMatch.Groups["folder"].Value;
					mod.FileName = modificationMatch.Groups["file"].Value;
					mod.Type = modificationMatch.Groups["type"].Value;
					mod.EmailAddress = email;
					mod.UserName = user;
					mod.ModifiedTime = date;
					mod.Comment = comment.Trim();
					mods.Add(mod);
				}
				else 
				{
					Match changeMatch = changeRegex.Match(line);
					if (changeMatch.Success)
					{
						// set these values while they're available
						change = changeMatch.Groups["change"].Value;
						email = changeMatch.Groups["email"].Value;
						user = changeMatch.Groups["user"].Value;
						date = DateTime.Parse(changeMatch.Groups["date"].Value, CultureInfo.CurrentCulture);
						// TODO this is necessary, could someone explain why?
						comment =string.Empty;
					}
					else 
					{
						string checkinCommentPrefix = "text: \t";
						if (line.StartsWith(checkinCommentPrefix))
						{
							comment += line.Substring(checkinCommentPrefix.Length) + "\r\n";
						}
					}
				}
			}
			
			return mods.ToArray();
		}
        // #CheckInComment#|#Name#|#DbPath#|#SCIT#|#Mime Type#|#LocalPath#|#Changed By#|#NxN_VersionNumber#
        public Modification ParseModification(string[] modificationParams)
        {
            Modification modification = new Modification();
            modification.Comment = modificationParams[0];
            modification.FileName = modificationParams[1];
            modification.FolderName = "ab:/" + modificationParams[2].Replace("/" + modificationParams[1],string.Empty);
            modification.ModifiedTime = DateTime.FromFileTime(long.Parse(modificationParams[3]));
            modification.Type = modificationParams[4];
            modification.Url = modificationParams[5];
            modification.UserName = modificationParams[6];
            modification.Version = modificationParams[7];

            return modification;
        }
 public void AssignFileInfo( Modification modification, string file )
 {
     int separatorLocation = file.LastIndexOf( Path.DirectorySeparatorChar.ToString() );
     if ( separatorLocation > - 1 )
     {
         modification.FolderName = file.Substring( 0, separatorLocation );
         modification.FileName = file.Substring( separatorLocation + 1 );
     }
     else
     {
         modification.FolderName = string.Empty;
         modification.FileName = file;
     }
 }
        /// <summary>
        /// Setups the modification.	
        /// </summary>
        /// <param name="modifications">The modifications.</param>
        /// <remarks></remarks>
        public void SetupModification(Modification[] modifications)
        {
            foreach (Modification mod in modifications)
            {
                if ((mod != null) && !string.IsNullOrEmpty(mod.Comment) && mod.Comment.Length > 0)
                {
                    if (Regex.IsMatch(mod.Comment, _find))
                    {
                        mod.IssueUrl = Regex.Replace(mod.Comment, _find, _replace);
                    }
                }

            }
        }
Example #26
0
 private Modification ParseModification(string[] modificationParams)
 {
     Modification modification = new Modification();
     int lastIndexOfBackslash = modificationParams[1].LastIndexOf("\\");
     modification.FileName = modificationParams[1].Substring(modificationParams[1].LastIndexOf("\\") + 1);
     if (lastIndexOfBackslash > 0)
     {
         modification.FolderName = modificationParams[1].Substring(0, (modificationParams[1].LastIndexOf("\\")));
     }
     modification.ChangeNumber = int.Parse(modificationParams[2]);
     modification.ModifiedTime = DateTime.Parse(modificationParams[3]);
     modification.UserName = modificationParams[4];
     modification.Comment = modificationParams[5];
     return modification;
 }
		/// <summary>
		/// Construct and return an array of Modifications describing the changes in
		/// the AccuRev workspace, based on the output of the "accurev hist" command.
		/// </summary>
		/// <param name="history">the stream of "accurev hist" command output</param>
		/// <param name="from">the starting date and time for the range of modifications we want.</param>
		/// <param name="to">the ending date and time for the range of modifications we want.</param>
		/// <returns>the changes in the specified time range.</returns>
		public Modification[] Parse(TextReader history, DateTime from, DateTime to)
		{
			string line;
			fromDateTime = from;
			toDateTime = to;
            modificationList = new List<Modification>();
			modificationTemplate = null;
			Regex firstTokenPattern = new Regex(@"^\s*(\S+)");
            Regex absolutePathPrefixPattern = new Regex(@"(\\|/)\.(\\|/)");
            Regex commentTextPattern = new Regex(@"^\s*# (.*)$");
			
			while ((line = history.ReadLine()) != null)
			{
				// Get the first non-whitespace token in the line and decide how to parse based on it:
				Match parsed = firstTokenPattern.Match(line);
				string firstToken =string.Empty;
                if (parsed.Success)
                    firstToken = parsed.Groups[1].ToString();
                switch (firstToken)
                {
                    case "transaction":
                        ParseTransaction(line);
                        break;
                    case "#":
                        // String together the lines of the comment, with a newline sequence between 
                        // adjacent lines.
                        if (modificationTemplate.Comment != null)
                            modificationTemplate.Comment += Environment.NewLine;
                        Match commentText = commentTextPattern.Match(line);
                        if (commentText.Groups.Count != 0)
                            modificationTemplate.Comment += commentText.Groups[1].ToString();
                        break;
                    case "ancestor:":
                    case "type:":
                    case "":
                        // Ignore uninteresting lines.
                        break;
                    default:
                        if (absolutePathPrefixPattern.IsMatch(firstToken))
                            ParseFileLine(line);
                        else
                            Log.Error(string.Format(System.Globalization.CultureInfo.CurrentCulture,"Unrecognized line in AccuRev \"accurev hist\" output: {0}", line));
                        break;
                }
            }
			Log.Debug(string.Format(System.Globalization.CultureInfo.CurrentCulture,"AccuRev reported {0} modifications", modificationList.Count));
			return modificationList.ToArray();
		}
        /// <summary>
        /// Accepts the specified m.	
        /// </summary>
        /// <param name="m">The m.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public bool Accept(Modification m)
        {
            if (this.Filters.Length == 0)
            {
                return false;
            }

            foreach (IModificationFilter mf in Filters)
            {
                if (!mf.Accept(m))
                {
                    return false;
                }
            }
            return true;
        }
        public Modification CreateNewModification(
			string userName,
			string time,
			string elementName,
			string modificationType,
			string comment,
			string change )
        {
            Modification modification = new Modification();
            modification.ChangeNumber = change;
            modification.UserName = userName;
            modification.Type = modificationType;
            modification.Comment = ( comment == string.Empty ? null : comment );
            AssignFileInfo( modification, elementName );
            AssignModificationTime( modification, time );
            return modification;
        }
        /// <summary>
        /// Setups the modification.	
        /// </summary>
        /// <param name="modifications">The modifications.</param>
        /// <remarks></remarks>
        public void SetupModification(Modification[] modifications)
        {
            if (modifications == null) throw new ArgumentNullException("modifications");

            foreach (Modification mod in modifications)
            {
                //split the comment on a space, take the first part
                //this must be the issue ID
                //from the last position of this part, go back while the characters are numeric                

                if ((mod != null) && !string.IsNullOrEmpty(mod.Comment) && mod.Comment.Length > 0)
                {
                    if (mod.Comment.IndexOf(' ') != 0)
                    {
                        string searchingComment = mod.Comment.Split(' ')[0];
                        int endPosition = searchingComment.Length - 1;
                        char currentChar = searchingComment[endPosition];
                        string result = string.Empty;
                        bool numericPartFound = false;

                        //eliminate non numeric characters at the end (ex type  [ccnet-1500])
                        while (endPosition > 0 && !char.IsNumber(currentChar))
                        {
                            endPosition--;
                            currentChar = searchingComment[endPosition];
                        }


                        //while last position is numeric add to result
                        while (endPosition >= 0 && char.IsNumber(currentChar))
                        {
                            result = result.Insert(0, currentChar.ToString(CultureInfo.CurrentCulture));
                            endPosition--;
                            if (endPosition >= 0) currentChar = searchingComment[endPosition];

                            numericPartFound = true;
                        }

                        if (numericPartFound)
                        {
                            mod.IssueUrl = string.Format(CultureInfo.CurrentCulture, _url, result);
                        }
                    }
                }
            }
        }
        public void TestFullProteinReadWrite()
        {
            Modification mod = new Modification("mod1", "modType1");

            ModificationMotif.TryGetMotif("E", out ModificationMotif motif);
            ModificationWithLocation mod2 = new ModificationWithLocation("mod2", "modType1", motif, TerminusLocalization.Any, null);

            ModificationMotif.TryGetMotif("N", out ModificationMotif motif3);
            ModificationWithMass mod3 = new ModificationWithMass("mod3", "modType1", motif3, TerminusLocalization.Any, 10, null, null, null);

            List <Tuple <string, string> > gene_names = new List <Tuple <string, string> > {
                new Tuple <string, string>("a", "b")
            };
            IDictionary <int, List <Modification> > oneBasedModifications = new Dictionary <int, List <Modification> >
            {
                { 3, new List <Modification> {
                      mod
                  } },
                { 4, new List <Modification> {
                      mod2
                  } },
                { 5, new List <Modification> {
                      mod3
                  } }
            };
            List <ProteolysisProduct> proteolysisProducts = new List <ProteolysisProduct> {
                new ProteolysisProduct(1, 2, "propeptide")
            };

            string name = "testName";

            string full_name = "testFullName";

            List <DatabaseReference> databaseReferences = new List <DatabaseReference> {
                new DatabaseReference("type1", "id1", new List <Tuple <string, string> > {
                    new Tuple <string, string>("e1", "e2")
                })
            };

            List <SequenceVariation> sequenceVariations = new List <SequenceVariation> {
                new SequenceVariation(3, "Q", "N", "replace Q by N"),
                new SequenceVariation(3, 4, "QE", "NN", "replace QE by NN")
            };

            List <DisulfideBond> disulfideBonds = new List <DisulfideBond> {
                new DisulfideBond(1, "ds1"), new DisulfideBond(2, 3, "ds2")
            };

            Protein p1 = new Protein("SEQENCE",
                                     "a1",
                                     gene_names: gene_names,
                                     oneBasedModifications: oneBasedModifications,
                                     proteolysisProducts: proteolysisProducts,
                                     name: name,
                                     full_name: full_name,
                                     isDecoy: false,
                                     isContaminant: true,
                                     databaseReferences: databaseReferences,
                                     sequenceVariations: sequenceVariations,
                                     disulfideBonds: disulfideBonds,
                                     databaseFilePath: Path.Combine(TestContext.CurrentContext.TestDirectory, @"bnueiwhf.xml"));

            // Generate data for files
            ProteinDbWriter.WriteXmlDatabase(new Dictionary <string, HashSet <Tuple <int, Modification> > >(), new List <Protein> {
                p1
            }, Path.Combine(TestContext.CurrentContext.TestDirectory, @"bnueiwhf.xml"));

            IEnumerable <string>       modTypesToExclude     = new List <string>();
            IEnumerable <Modification> allKnownModifications = new List <Modification>();
            List <Protein>             ok = ProteinDbLoader.LoadProteinXML(Path.Combine(TestContext.CurrentContext.TestDirectory, @"bnueiwhf.xml"), true, DecoyType.None, allKnownModifications, true, modTypesToExclude, out Dictionary <string, Modification> unknownModifications);

            Assert.AreEqual(p1.Accession, ok[0].Accession);
            Assert.AreEqual(p1.BaseSequence, ok[0].BaseSequence);
            Assert.AreEqual(p1.DatabaseReferences.First().Id, ok[0].DatabaseReferences.First().Id);
            Assert.AreEqual(p1.DatabaseReferences.First().Properties.First().Item1, ok[0].DatabaseReferences.First().Properties.First().Item1);
            Assert.AreEqual(p1.DatabaseReferences.First().Properties.First().Item2, ok[0].DatabaseReferences.First().Properties.First().Item2);
            Assert.AreEqual(p1.DatabaseReferences.First().Type, ok[0].DatabaseReferences.First().Type);

            Assert.AreEqual(p1.DisulfideBonds.First().Description, ok[0].DisulfideBonds.First().Description);
            Assert.AreEqual(p1.DisulfideBonds.First().OneBasedBeginPosition, ok[0].DisulfideBonds.First().OneBasedBeginPosition);
            Assert.AreEqual(p1.DisulfideBonds.First().OneBasedEndPosition, ok[0].DisulfideBonds.First().OneBasedEndPosition);
            Assert.AreEqual(p1.DisulfideBonds.Last().Description, ok[0].DisulfideBonds.Last().Description);
            Assert.AreEqual(p1.DisulfideBonds.Last().OneBasedBeginPosition, ok[0].DisulfideBonds.Last().OneBasedBeginPosition);
            Assert.AreEqual(p1.DisulfideBonds.Last().OneBasedEndPosition, ok[0].DisulfideBonds.Last().OneBasedEndPosition);

            Assert.AreEqual(p1.FullDescription, ok[0].FullDescription);
            Assert.AreEqual(p1.FullName, ok[0].FullName);
            Assert.AreEqual(p1.GeneNames, ok[0].GeneNames);
            Assert.AreEqual(p1.IsContaminant, ok[0].IsContaminant);
            Assert.AreEqual(p1.IsDecoy, ok[0].IsDecoy);
            Assert.AreEqual(p1.Length, ok[0].Length);
            Assert.AreEqual(p1.Name, ok[0].Name);
            Assert.AreEqual(p1.Organism, ok[0].Organism);
            Assert.AreEqual(p1.DatabaseFilePath, ok[0].DatabaseFilePath);
            Assert.AreEqual(p1.OneBasedPossibleLocalizedModifications[3][0], ok[0].OneBasedPossibleLocalizedModifications[3][0]);
            Assert.AreEqual(p1.OneBasedPossibleLocalizedModifications[3][0].id, ok[0].OneBasedPossibleLocalizedModifications[3][0].id);
            Assert.AreEqual(p1.OneBasedPossibleLocalizedModifications[3][0].modificationType, ok[0].OneBasedPossibleLocalizedModifications[3][0].modificationType);

            Assert.AreEqual(p1.OneBasedPossibleLocalizedModifications[4][0].id, ok[0].OneBasedPossibleLocalizedModifications[4][0].id);
            Assert.AreEqual(p1.OneBasedPossibleLocalizedModifications[4][0].modificationType, ok[0].OneBasedPossibleLocalizedModifications[4][0].modificationType);
            Assert.AreEqual((p1.OneBasedPossibleLocalizedModifications[4][0] as ModificationWithLocation).linksToOtherDbs, (ok[0].OneBasedPossibleLocalizedModifications[4][0] as ModificationWithLocation).linksToOtherDbs);
            Assert.AreEqual((p1.OneBasedPossibleLocalizedModifications[4][0] as ModificationWithLocation).motif, (ok[0].OneBasedPossibleLocalizedModifications[4][0] as ModificationWithLocation).motif);
            Assert.AreEqual((p1.OneBasedPossibleLocalizedModifications[4][0] as ModificationWithLocation).terminusLocalization, (ok[0].OneBasedPossibleLocalizedModifications[4][0] as ModificationWithLocation).terminusLocalization);

            Assert.AreEqual((p1.OneBasedPossibleLocalizedModifications[5][0] as ModificationWithMass).diagnosticIons, (ok[0].OneBasedPossibleLocalizedModifications[5][0] as ModificationWithMass).diagnosticIons);
            Assert.AreEqual((p1.OneBasedPossibleLocalizedModifications[5][0] as ModificationWithMass).neutralLosses, (ok[0].OneBasedPossibleLocalizedModifications[5][0] as ModificationWithMass).neutralLosses);
            Assert.AreEqual((p1.OneBasedPossibleLocalizedModifications[5][0] as ModificationWithMass).monoisotopicMass, (ok[0].OneBasedPossibleLocalizedModifications[5][0] as ModificationWithMass).monoisotopicMass);

            Assert.AreEqual(p1.ProteolysisProducts.First().OneBasedBeginPosition, ok[0].ProteolysisProducts.First().OneBasedBeginPosition);
            Assert.AreEqual(p1.ProteolysisProducts.First().OneBasedEndPosition, ok[0].ProteolysisProducts.First().OneBasedEndPosition);
            Assert.AreEqual(p1.ProteolysisProducts.First().Type, ok[0].ProteolysisProducts.First().Type);

            Assert.AreEqual(p1.SequenceVariations.First().Description, ok[0].SequenceVariations.First().Description);
            Assert.AreEqual(p1.SequenceVariations.First().OneBasedBeginPosition, ok[0].SequenceVariations.First().OneBasedBeginPosition);
            Assert.AreEqual(p1.SequenceVariations.First().OneBasedEndPosition, ok[0].SequenceVariations.First().OneBasedEndPosition);
            Assert.AreEqual(p1.SequenceVariations.First().OriginalSequence, ok[0].SequenceVariations.First().OriginalSequence);
            Assert.AreEqual(p1.SequenceVariations.First().VariantSequence, ok[0].SequenceVariations.First().VariantSequence);
            Assert.AreEqual(p1.SequenceVariations.Last().Description, ok[0].SequenceVariations.Last().Description);
            Assert.AreEqual(p1.SequenceVariations.Last().OneBasedBeginPosition, ok[0].SequenceVariations.Last().OneBasedBeginPosition);
            Assert.AreEqual(p1.SequenceVariations.Last().OneBasedEndPosition, ok[0].SequenceVariations.Last().OneBasedEndPosition);
            Assert.AreEqual(p1.SequenceVariations.Last().OriginalSequence, ok[0].SequenceVariations.Last().OriginalSequence);
            Assert.AreEqual(p1.SequenceVariations.Last().VariantSequence, ok[0].SequenceVariations.Last().VariantSequence);
        }
Example #32
0
 /// <summary>
 /// Creates the individual label string.
 /// </summary>
 /// <param name="mod">The mod.</param>
 /// <param name="label">The label.</param>
 /// <returns></returns>
 /// <remarks></remarks>
 public string CreateIndividualLabelString(Modification mod, string label)
 {
     return(string.Format(CultureInfo.CurrentCulture, INDIVIDUAL_LABEL_REVISION_TEMPLATE, GetVersion(mod, label), GetUncPathPrefix(mod), mod.FolderName, mod.FileName));
 }
Example #33
0
        /// <summary>
        /// Gets the modifications.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public override Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
        {
            List <NameValuePair> originalSourceControlData = new List <NameValuePair>();
            List <NameValuePair> finalSourceControlData    = new List <NameValuePair>();

            var sourceControlDataType = from.SourceControlData.GetType();

            // check that the source control data given to us is in the list of list format
            // if not, then convert it now
            var fromSourceControlDataCount = from.SourceControlData.Count;

            if (fromSourceControlDataCount > 0 &&
                (fromSourceControlDataCount != SourceControls.Length ||
                 !XmlConversionUtil.CanConvertXmlToObject(sourceControlDataType, from.SourceControlData[0].Value)
                )
                )
            {
                var conversionList = new List <NameValuePair>();

                for (int i = 0; i < SourceControls.Length; i++)
                {
                    originalSourceControlData.Add(new NameValuePair(string.Format("sc{0:d}", i), ""));
                }

                int scdIndex = fromSourceControlDataCount - 1;
                for (int i = originalSourceControlData.Count - 1; i >= 0; i--)
                {
                    conversionList.Clear();

                    if (scdIndex >= 0)
                    {
                        if (!XmlConversionUtil.CanConvertXmlToObject(sourceControlDataType, from.SourceControlData[scdIndex].Value))
                        {
                            conversionList.Add(from.SourceControlData[scdIndex]);
                        }
                    }

                    originalSourceControlData[i].Value = XmlConversionUtil.ConvertObjectToXml(conversionList);

                    scdIndex--;
                }
            }
            else
            {
                originalSourceControlData.AddRange(from.SourceControlData);
            }

            var originalSourceControlDataCount = originalSourceControlData.Count;
            var modificationSet    = new Dictionary <Modification, bool>();
            int sourceControlIndex = 0;

            foreach (ISourceControl sourceControl in SourceControls)
            {
                from.SourceControlData.Clear();
                if (sourceControlIndex < originalSourceControlDataCount)
                {
                    from.SourceControlData.AddRange((List <NameValuePair>)(XmlConversionUtil.ConvertXmlToObject(sourceControlDataType, originalSourceControlData[sourceControlIndex].Value)));
                }

                to.SourceControlData.Clear();

                Modification[] mods = sourceControl.GetModifications(from, to);

                finalSourceControlData.Add(new NameValuePair(string.Format("sc{0:d}", sourceControlIndex), XmlConversionUtil.ConvertObjectToXml(to.SourceControlData)));

                if (mods != null && mods.Length > 0)
                {
                    foreach (var mod in mods)
                    {
                        modificationSet[mod] = true;
                    }
                }
                else if (RequireChangesFromAll)
                {
                    modificationSet.Clear();
                    break;
                }

                sourceControlIndex++;
            }

            to.SourceControlData.Clear();
            to.SourceControlData.AddRange(finalSourceControlData);

            // reset the from.SourceControlData to its original contents
            from.SourceControlData.Clear();
            from.SourceControlData.AddRange(originalSourceControlData);

            var modArray = new Modification[modificationSet.Count];

            modificationSet.Keys.CopyTo(modArray, 0);
            return(modArray);
        }
        public static void TestModificationAnalysis()
        {
            Ms2ScanWithSpecificMass scan = new Ms2ScanWithSpecificMass(new MsDataScan(new MzSpectrum(new double[, ] {
            }), 0, 0, true, Polarity.Positive,
                                                                                      0, new MzLibUtil.MzRange(0, 0), "", MZAnalyzerType.FTICR, 0, null, null, ""), 0, 0, "", new CommonParameters());

            ModificationMotif.TryGetMotif("N", out ModificationMotif motif1);
            Modification mod1 = new Modification(_originalId: "mod1", _modificationType: "myModType", _target: motif1, _locationRestriction: "Anywhere.", _monoisotopicMass: 10);

            ModificationMotif.TryGetMotif("L", out ModificationMotif motif2);
            Modification mod2 = new Modification(_originalId: "mod2", _modificationType: "myModType", _target: motif2, _locationRestriction: "Anywhere.", _monoisotopicMass: 10);

            IDictionary <int, List <Modification> > oneBasedModifications = new Dictionary <int, List <Modification> >
            {
                { 2, new List <Modification> {
                      mod1
                  } },
                { 5, new List <Modification> {
                      mod2
                  } },
                { 7, new List <Modification> {
                      mod1
                  } },
            };
            Protein protein1 = new Protein("MNLDLDNDL", "prot1", oneBasedModifications: oneBasedModifications);

            Dictionary <int, Modification> allModsOneIsNterminus1 = new Dictionary <int, Modification>
            {
                { 2, mod1 },
            };
            PeptideWithSetModifications pwsm1 = new PeptideWithSetModifications(protein1, new DigestionParams(), 2, 9, CleavageSpecificity.Unknown, null, 0, allModsOneIsNterminus1, 0);

            Dictionary <int, Modification> allModsOneIsNterminus2 = new Dictionary <int, Modification>
            {
                { 2, mod1 },
                { 7, mod1 },
            };
            PeptideWithSetModifications pwsm2 = new PeptideWithSetModifications(protein1, new DigestionParams(), 2, 9, CleavageSpecificity.Unknown, null, 0, allModsOneIsNterminus2, 0);

            Dictionary <int, Modification> allModsOneIsNterminus3 = new Dictionary <int, Modification>
            {
                { 7, mod1 },
            };
            PeptideWithSetModifications pwsm3 = new PeptideWithSetModifications(protein1, new DigestionParams(), 2, 9, CleavageSpecificity.Unknown, null, 0, allModsOneIsNterminus3, 0);

            Dictionary <int, Modification> allModsOneIsNterminus4 = new Dictionary <int, Modification>
            {
                { 8, mod1 },
            };
            PeptideWithSetModifications pwsm4 = new PeptideWithSetModifications(protein1, new DigestionParams(), 1, 9, CleavageSpecificity.Unknown, null, 0, allModsOneIsNterminus4, 0);

            CommonParameters CommonParameters = new CommonParameters(
                digestionParams: new DigestionParams(
                    maxMissedCleavages: 0,
                    minPeptideLength: 1,
                    maxModificationIsoforms: int.MaxValue),
                scoreCutoff: 1);

            var fsp = new List <(string fileName, CommonParameters fileSpecificParameters)>();

            fsp.Add(("", CommonParameters));

            var newPsms = new List <PeptideSpectralMatch>
            {
                new PeptideSpectralMatch(pwsm1, 0, 10, 0, scan, CommonParameters, new List <MatchedFragmentIon>()),
                new PeptideSpectralMatch(pwsm1, 0, 10, 0, scan, CommonParameters, new List <MatchedFragmentIon>()),
                new PeptideSpectralMatch(pwsm2, 0, 10, 0, scan, CommonParameters, new List <MatchedFragmentIon>()),
                new PeptideSpectralMatch(pwsm3, 0, 10, 0, scan, CommonParameters, new List <MatchedFragmentIon>()),
                new PeptideSpectralMatch(pwsm4, 0, 10, 0, scan, CommonParameters, new List <MatchedFragmentIon>()),
            };

            foreach (var psm in newPsms)
            {
                psm.ResolveAllAmbiguities();
            }

            MassDiffAcceptor searchMode  = new SinglePpmAroundZeroSearchMode(5);
            List <Protein>   proteinList = new List <Protein> {
                protein1
            };

            FdrAnalysisEngine fdrAnalysisEngine = new FdrAnalysisEngine(newPsms, searchMode.NumNotches, CommonParameters, fsp, new List <string>());

            fdrAnalysisEngine.Run();
            ModificationAnalysisEngine modificationAnalysisEngine = new ModificationAnalysisEngine(newPsms, new CommonParameters(), fsp, new List <string>());
            var res = (ModificationAnalysisResults)modificationAnalysisEngine.Run();

            Assert.AreEqual(2, res.CountOfEachModSeenOnProteins.Count());
            Assert.AreEqual(2, res.CountOfEachModSeenOnProteins[mod1.IdWithMotif]);
            Assert.AreEqual(1, res.CountOfEachModSeenOnProteins[mod2.IdWithMotif]);

            Assert.AreEqual(1, res.CountOfModsSeenAndLocalized.Count());
            Assert.AreEqual(2, res.CountOfModsSeenAndLocalized[mod1.IdWithMotif]);

            Assert.AreEqual(0, res.CountOfAmbiguousButLocalizedModsSeen.Count());

            Assert.AreEqual(0, res.CountOfUnlocalizedMods.Count());

            Assert.AreEqual(0, res.CountOfUnlocalizedFormulas.Count());
        }
Example #35
0
        protected override void ModifyValue(PropertyReferenceProperty property, object valueToSet, Modification modification, int index)
        {
            if (this.objects.Length == 0)
            {
                using (this.ViewModel.ForceDefaultSetValue())
                    this.parent.SetValue((PropertyReferenceProperty)this.parentProperty, this.parent.GetValue(this.baseReference, PropertyReference.GetValueFlags.Computed));
                this.RebuildObjects();
            }
            bool treeModified = false;
            SceneEditTransaction sceneEditTransaction = (SceneEditTransaction)null;

            try
            {
                sceneEditTransaction = this.parent.PrepareTreeForModifyValue(this.parentProperty.Reference.Append(property.Reference), valueToSet, modification, out treeModified);
                if (treeModified)
                {
                    this.RebuildObjects();
                }
                base.ModifyValue(property, valueToSet, modification, index);
            }
            finally
            {
                if (sceneEditTransaction != null)
                {
                    sceneEditTransaction.Commit();
                    sceneEditTransaction.Dispose();
                }
            }
        }
Example #36
0
        /// <summary>
        /// Read results from tsv file into group of objects from PSI_Interface
        /// </summary>
        /// <param name="idFilePath"></param>
        /// <returns></returns>
        public static SimpleMZIdentMLReader.SimpleMZIdentMLData ReadResultsFromFileToMzIdData(string idFilePath)
        {
            var databaseSearchResultData = ReadResultsFromFile(idFilePath);

            var simpleMzIdentMLData = new SimpleMZIdentMLReader.SimpleMZIdentMLData(idFilePath);

            foreach (var databaseSearchResult in databaseSearchResultData)
            {
                var peptide = new SimpleMZIdentMLReader.PeptideRef
                {
                    Sequence = databaseSearchResult.Sequence
                };

                var identification = new SimpleMZIdentMLReader.SpectrumIdItem
                {
                    Peptide = peptide,
                    Charge  = databaseSearchResult.Charge,
                    ScanNum = databaseSearchResult.ScanNum,
                    SpecEv  = databaseSearchResult.SpecEValue,
                };

                // Parse modification
                var modParts = databaseSearchResult.Modifications.Split(',');
                if (modParts.Length > 0)
                {
                    foreach (var part in modParts)
                    {
                        var mod = part.Split(' ');
                        if (mod.Length < 2)
                        {
                            continue;
                        }

                        var modName  = mod[0];
                        var modIndex = Convert.ToInt32(mod[1]);
                        var ipMod    = Modification.Get(modName);

                        var modification = new SimpleMZIdentMLReader.Modification
                        {
                            Mass = ipMod.Mass,
                            Tag  = modName,
                        };

                        peptide.ModsAdd(modIndex, modification);
                    }
                }

                var proteinAccessions = databaseSearchResult.ProteinName.Split(',');
                foreach (var accession in proteinAccessions)
                {
                    var dbSequence = new SimpleMZIdentMLReader.DatabaseSequence
                    {
                        Accession          = accession.Trim(),
                        ProteinDescription = databaseSearchResult.ProteinDescription
                    };
                    var peptideEvidence = new SimpleMZIdentMLReader.PeptideEvidence
                    {
                        DbSeq      = dbSequence,
                        Pre        = databaseSearchResult.Pre,
                        Post       = databaseSearchResult.Post,
                        PeptideRef = identification.Peptide,
                        Start      = databaseSearchResult.Start,
                        End        = databaseSearchResult.End,
                    };

                    identification.PepEvidence.Add(peptideEvidence);
                }

                simpleMzIdentMLData.Identifications.Add(identification);
            }

            return(simpleMzIdentMLData);
        }
    /*============*\
    |*   Setter   *|
    \*============*/

    public void AddModification(Modification modification)
    {
        modification.SetModificationTarget(m_modificationObject);
        m_modifications.Add(modification);
        modAdded?.Invoke(modification);
    }
Example #38
0
        public static Dictionary <Tuple <int, int>, List <Product> > XlLoopGetTheoreticalFragments(DissociationType dissociationType, Modification loopMass,
                                                                                                   List <int> modPos, PeptideWithSetModifications peptide)
        {
            Dictionary <Tuple <int, int>, List <Product> > AllTheoreticalFragmentsLists = new Dictionary <Tuple <int, int>, List <Product> >();
            var originalFragments = peptide.Fragment(dissociationType, FragmentationTerminus.Both).ToList();

            foreach (int position1 in modPos)
            {
                foreach (int position2 in modPos)
                {
                    if (position2 <= position1)
                    {
                        continue;
                    }

                    // add N and C terminal fragments that do not contain the loop
                    Tuple <int, int> loopPositions = new Tuple <int, int>(position1, position2);
                    List <Product>   loopFragments = originalFragments
                                                     .Where(p => p.TerminusFragment.Terminus == FragmentationTerminus.N && p.TerminusFragment.AminoAcidPosition <position1 ||
                                                                                                                                                                 p.TerminusFragment.Terminus == FragmentationTerminus.C && p.TerminusFragment.AminoAcidPosition> position2).ToList();

                    // add N-terminal fragments containing the loop
                    Dictionary <int, Modification> modDict = new Dictionary <int, Modification>();
                    if (peptide.AllModsOneIsNterminus.Any())
                    {
                        double       combinedModMass = loopMass.MonoisotopicMass.Value + peptide.AllModsOneIsNterminus.Where(v => v.Key <= position2 + 1).Sum(p => p.Value.MonoisotopicMass.Value);
                        Modification combined        = new Modification(_monoisotopicMass: combinedModMass);
                        modDict.Add(position1 + 1, combined);

                        foreach (var mod in peptide.AllModsOneIsNterminus.Where(m => m.Key > position2 + 1))
                        {
                            modDict.Add(mod.Key, mod.Value);
                        }
                    }
                    else
                    {
                        modDict.Add(position1 + 1, loopMass);
                    }
                    PeptideWithSetModifications peptideWithLoop = new PeptideWithSetModifications(peptide.Protein, peptide.DigestionParams,
                                                                                                  peptide.OneBasedStartResidueInProtein, peptide.OneBasedEndResidueInProtein, peptide.CleavageSpecificityForFdrCategory,
                                                                                                  peptide.PeptideDescription, peptide.MissedCleavages, modDict, peptide.NumFixedMods);
                    loopFragments.AddRange(peptideWithLoop.Fragment(dissociationType, FragmentationTerminus.Both)
                                           .Where(p => p.TerminusFragment.Terminus == FragmentationTerminus.N && p.TerminusFragment.AminoAcidPosition >= position2));

                    // add C-terminal fragments containing the loop
                    modDict.Clear();
                    if (peptide.AllModsOneIsNterminus.Any())
                    {
                        double       combinedModMass = loopMass.MonoisotopicMass.Value + peptide.AllModsOneIsNterminus.Where(v => v.Key >= position1 + 1).Sum(p => p.Value.MonoisotopicMass.Value);
                        Modification combined        = new Modification(_monoisotopicMass: combinedModMass);
                        modDict.Add(position2 + 1, combined);

                        foreach (var mod in peptide.AllModsOneIsNterminus.Where(m => m.Key < position1 + 1))
                        {
                            modDict.Add(mod.Key, mod.Value);
                        }
                    }
                    else
                    {
                        modDict.Add(position2 + 1, loopMass);
                    }
                    peptideWithLoop = new PeptideWithSetModifications(peptide.Protein, peptide.DigestionParams,
                                                                      peptide.OneBasedStartResidueInProtein, peptide.OneBasedEndResidueInProtein, peptide.CleavageSpecificityForFdrCategory,
                                                                      peptide.PeptideDescription, peptide.MissedCleavages, modDict, peptide.NumFixedMods);
                    loopFragments.AddRange(peptideWithLoop.Fragment(dissociationType, FragmentationTerminus.Both)
                                           .Where(p => p.TerminusFragment.Terminus == FragmentationTerminus.C && p.TerminusFragment.AminoAcidPosition <= position1));

                    AllTheoreticalFragmentsLists.Add(loopPositions, loopFragments);
                }
            }

            return(AllTheoreticalFragmentsLists);
        }
Example #39
0
        public void FilesLoading()
        {
            Loaders.LoadElements(Path.Combine(TestContext.CurrentContext.TestDirectory, "elements2.dat"));

            var unimodMods = Loaders.LoadUnimod(Path.Combine(TestContext.CurrentContext.TestDirectory, "unimod_tables2.xml")).ToList();

            Assert.AreEqual(2639, unimodMods.Count); // UniMod PTM list may be updated at some point, causing the unit test to fail

            List <Modification> myList = unimodMods.Where(m => m.OriginalId.Equals("HexNAc(2)")).ToList();

            Modification testMod          = myList.First();
            int          neutralLossCount = 0;

            if (testMod.NeutralLosses.Count != 0)
            {
                foreach (KeyValuePair <MassSpectrometry.DissociationType, List <double> > item in testMod.NeutralLosses)
                {
                    foreach (double loss in item.Value)
                    {
                        neutralLossCount++;
                    }
                }
            }

            Assert.AreEqual(2, neutralLossCount);
            var psiModDeserialized = Loaders.LoadPsiMod(Path.Combine(TestContext.CurrentContext.TestDirectory, "PSI-MOD.obo2.xml"));

            // N6,N6,N6-trimethyllysine
            var trimethylLysine = psiModDeserialized.Items.OfType <UsefulProteomicsDatabases.Generated.oboTerm>().First(b => b.id.Equals("MOD:00083"));

            Assert.AreEqual("1+", trimethylLysine.xref_analog.First(b => b.dbname.Equals("FormalCharge")).name);

            // Phosphoserine
            Assert.IsFalse(psiModDeserialized.Items.OfType <UsefulProteomicsDatabases.Generated.oboTerm>().First(b => b.id.Equals("MOD:00046")).xref_analog.Any(b => b.dbname.Equals("FormalCharge")));

            Dictionary <string, int> formalChargesDictionary = Loaders.GetFormalChargesDictionary(psiModDeserialized);

            var uniprotPtms = Loaders.LoadUniprot(Path.Combine(TestContext.CurrentContext.TestDirectory, "ptmlist2.txt"), formalChargesDictionary).ToList();

            Assert.AreEqual(334, uniprotPtms.Count()); // UniProt PTM list may be updated at some point, causing the unit test to fail

            using (StreamWriter w = new StreamWriter(Path.Combine(TestContext.CurrentContext.TestDirectory, "test.txt")))
            {
                foreach (var nice in uniprotPtms)
                {
                    w.WriteLine(nice.ToString());
                    w.WriteLine("//");
                }
                foreach (var nice in unimodMods)
                {
                    w.WriteLine(nice.ToString());
                    w.WriteLine("//");
                }
            }

            var sampleModList = PtmListLoader.ReadModsFromFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "test.txt"), out var errors).ToList();

            Assert.AreEqual(2973, sampleModList.Count());
            string s = "";

            List <Modification> myOtherList = new List <Modification>();

            foreach (Modification mod in sampleModList)
            {
                if (mod.IdWithMotif != null && mod.IdWithMotif.Contains("Acetyl"))
                {
                    myOtherList.Add(mod);
                }
            }

            var thisMod = myOtherList.First();

            Assert.IsTrue(thisMod.MonoisotopicMass > 42);
            Assert.IsTrue(thisMod.MonoisotopicMass < 43);
        }
 public void ShouldReturnNullAsLastChangeNumberIfNoModifications()
 {
     Modification[] modifications = new Modification[0];
     Assert.AreEqual(null, Modification.GetLastChangeNumber(modifications), "LastChangeNumer({})");
 }
Example #41
0
        public bool AddModification(Modification modification)
        {
            var result = ModificationRepository.AddModification(modification);

            return(result);
        }
Example #42
0
        public bool UpdateModification(Modification modification)
        {
            var result = ModificationRepository.UpdateModification(modification);

            return(result);
        }
        private void OptimizationLoop()
        {
            population = new List <OptimizableStructure>();
            scoreList  = new List <double>();

            if (optimizationMethod == OptimizationMethod.GA)
            {
                stopWatch.Start();
                running = true;
                double elapsedOptimizationTime;
                SetUpGeneticAlgorithm();
                creepMutationRate = 0;

                bestScore      = double.MinValue;
                iterationIndex = 0;
                numberOfEvaluatedIndividuals = 0;

                double minimumParameterValue = optimizationSettings.MinimumSpeedValue;
                double maximumParameterValue = optimizationSettings.MaximumSpeedValue;
                double desiredAverageSpeed   = optimizationSettings.DesiredAverageSpeed;

                while (running)
                {
                    for (int ii = 0; ii < populationSize; ii++)
                    {
                        OptimizableStructure individual = population[ii].Copy();
                        speedProfileEvaluator = new PiecewiseLinearSpeedProfileEvaluator();
                        speedProfileEvaluator.AssignMetricMap(metricMap);
                        speedProfileEvaluator.AssignMetricPath(metricPath);
                        speedProfileEvaluator.MaximumAllowedSpeed = maximumParameterValue;
                        speedProfileEvaluator.MinimumAllowedSpeed = minimumParameterValue;
                        speedProfileEvaluator.DesiredAverageSpeed = desiredAverageSpeed;
                        speedProfileEvaluator.AssignPossibleSpeedList(possibleSpeedList);

                        double score = speedProfileEvaluator.EvaluateGA(individual);
                        scoreList[ii]    = score;
                        cumulativeScore += score;

                        List <int> individualSpeedIndexList = new List <int>();
                        for (int kk = 0; kk < individual.ParameterList.Count; kk++)
                        {
                            individualSpeedIndexList.Add(((IntParameter)individual.ParameterList[kk]).ParameterValue);
                        }
                        long speedProfileIndex = ConvertToBase10(individualSpeedIndexList);

                        OnIndividualEvaluated(individualSpeedIndexList, speedProfileIndex, 0, score, individual.Copy(), ii, iterationIndex, true);

                        if (score >= bestScore)
                        {
                            // MW 20180206
                            if (score > bestScore)
                            {
                                OnNewBestIndividualFound(individualSpeedIndexList, speedProfileIndex, 0, score, individual.Copy(), ii, iterationIndex, true);
                            }


                            bestScore           = score;
                            bestIndividualIndex = ii;
                            // Copy the best individual here, in case the algorithm exits due to maximum time reached.
                            optimizedSpeedProfile = individual.Copy();
                        }
                        numberOfEvaluatedIndividuals++;
                        elapsedOptimizationTime = stopWatch.ElapsedTicks / (double)Stopwatch.Frequency;
                        if (elapsedOptimizationTime >= optimizationTime | numberOfEvaluatedIndividuals >= optimizationSettings.NumberOfGenerations * optimizationSettings.PopulationSize)
                        {
                            running = false;
                            OnStopped();
                            break;
                        }
                        if (!running)
                        {
                            break;
                        }
                    }

                    // Make new generation:
                    OptimizableStructure        bestIndividual = population[bestIndividualIndex].Copy();
                    List <OptimizableStructure> oldPopulation  = new List <OptimizableStructure>();
                    foreach (OptimizableStructure individual in population)
                    {
                        OptimizableStructure copiedIndividual = individual.Copy();
                        oldPopulation.Add(copiedIndividual);
                    }
                    population = new List <OptimizableStructure>();
                    int counter = 0;
                    while (counter < oldPopulation.Count)
                    {
                        int firstIndex = TournamentSelection.Select(randomNumberGenerator, scoreList, OptimizationObjective.Maximization,
                                                                    tournamentSize, tournamentSelectionParameter);
                        int secondIndex = TournamentSelection.Select(randomNumberGenerator, scoreList, OptimizationObjective.Maximization,
                                                                     tournamentSize, tournamentSelectionParameter);
                        double r = randomNumberGenerator.NextDouble();
                        OptimizableStructure parent1 = oldPopulation[firstIndex];
                        OptimizableStructure parent2 = oldPopulation[secondIndex];
                        if (r < crossoverProbability)
                        {
                            List <OptimizableStructure> newIndividualsList = null;
                            newIndividualsList = Crossover.ExecuteSinglePoint(parent1, parent2, unitLength, randomNumberGenerator);
                            population.Add(newIndividualsList[0]);
                            population.Add(newIndividualsList[1]);
                        }
                        else
                        {
                            population.Add(parent1);
                            population.Add(parent2);
                        }
                        counter += 2;
                    }
                    if (population.Count > oldPopulation.Count)
                    {
                        population.RemoveAt(population.Count - 1);
                    }                                                                                          // If the population size is odd..

                    for (int jj = 0; jj < population.Count; jj++)
                    {
                        OptimizableStructure individual        = population[jj];
                        OptimizableStructure mutatedIndividual = (OptimizableStructure)Modification.Execute(individual,
                                                                                                            mutationRate, creepMutationRate, randomNumberGenerator);
                        population[jj] = mutatedIndividual;
                    }
                    if (useElitism)
                    {
                        population[0] = bestIndividual;
                    }

                    double     bestFitness    = bestScore;
                    double     averageFitness = scoreList.Average();
                    List <int> bestIndividualSpeedIndexList = new List <int>();
                    for (int kk = 0; kk < bestIndividual.ParameterList.Count; kk++)
                    {
                        bestIndividualSpeedIndexList.Add(((IntParameter)bestIndividual.ParameterList[kk]).ParameterValue);
                    }

                    long bestSpeedProfileIndex = ConvertToBase10(bestIndividualSpeedIndexList);

                    List <int> populationAverageIndividual = new List <int>();

                    OnGenerationEvaluated(bestFitness, averageFitness, iterationIndex, bestIndividualIndex,
                                          numberOfEvaluatedIndividuals, bestIndividualSpeedIndexList, bestSpeedProfileIndex);
                    iterationIndex++;
                    if (numberOfEvaluatedIndividuals >= optimizationSettings.NumberOfGenerations * optimizationSettings.PopulationSize)
                    {
                        running = false;
                        OnStopped();
                        break;
                    }
                }
                OnStopped();
            }
            OnStopped();
        }
Example #44
0
        public void TestParsePtms(double qValueThreshold, int expectedPTMListCount)
        {
            var methodName = MethodBase.GetCurrentMethod().Name;

            Utils.ShowStarting(methodName);

            var resultFilePath = Path.Combine(Utils.DEFAULT_SPEC_FILES_FOLDER, "QC_Shew_Intact_26Sep14_Bane_C2Column3_Excerpt_IcTda.tsv");
            var resultFile     = Utils.GetTestFile(methodName, resultFilePath);

            var parser        = new TsvFileParser(resultFile.FullName);
            var sequences     = parser.GetData("Sequence");
            var modifications = parser.GetData("Modifications");
            var compositions  = parser.GetData("Composition");
            var scanNums      = parser.GetData("Scan").Select(s => Convert.ToInt32(s)).ToArray();
            var qValues       = parser.GetData("QValue").Select(s => Convert.ToDouble(s)).ToArray();
            var nMacthed      = parser.GetData("#MatchedFragments");
            var aaSet         = new AminoAcidSet();
            var ptmList       = new List <Tuple <int, double, double> >();

            var trimChars            = new[] { '"', ' ' };
            var filterPassingResults = 0;

            for (var i = 0; i < parser.NumData; i++)
            {
                if (qValues[i] > qValueThreshold)
                {
                    continue;
                }

                filterPassingResults++;

                var seq          = new Sequence(sequences[i], aaSet);
                var sequenceComp = seq.Composition + Composition.H2O;

                var modComposition = Composition.Zero;
                var modsStr        = modifications[i].Trim(trimChars);
                if (modsStr.Length == 0)
                {
                    continue;
                }

                var mods = modsStr.Split(',');
                foreach (var modStr in mods.Where(str => str.Length > 0))
                {
                    var modName = modStr.Split()[0];
                    var mod     = Modification.Get(modName);
                    modComposition += mod.Composition;
                }

                if (ptmList.Count < 5)
                {
                    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}", scanNums[i], sequenceComp.Mass, modComposition.Mass, nMacthed[i], sequences[i], modsStr);
                }

                var compFromSeqAndMods = sequenceComp + modComposition;

                var expectedComposition = compositions[i];
                Assert.AreEqual(expectedComposition, compFromSeqAndMods.ToString(), "Composition Mismatch");

                ptmList.Add(new Tuple <int, double, double>(scanNums[i], sequenceComp.Mass, modComposition.Mass));
            }

            Console.WriteLine();
            Console.WriteLine("{0} results with PTMs / {1} total results passing threshold qValue < {2}", ptmList.Count, filterPassingResults, qValueThreshold);
            Assert.AreEqual(expectedPTMListCount, ptmList.Count, "Unexpected number of identifications with at least one PTM at qValue < {0}", qValueThreshold);
        }
 public void RemoveModiciation(Modification modification)
 {
     m_modifications.Remove(modification);
     modRemoved?.Invoke(modification);
 }
 override public void ApplyModification(Modification mod, Sheet sheet)
 {
     StaticErrorLogger.AddGenericError("trying to modify a modification component: " + name);
 }
Example #47
0
        public override IEnumerable <ICodeBlockMappingExpression> Map(IModificationMappingExpression expression)
        {
            Modification modification = expression.CurrentEntity <Modification>();

            if (modification.Action == TouchedFileAction.REMOVED)
            {
                return(SingleExpression(expression
                                        .RemoveCode()));
            }

            List <CodeBlockMappingExpression> codeBlockExpressions = new List <CodeBlockMappingExpression>();
            string   revision = expression.CurrentEntity <Commit>().Revision;
            CodeFile file     = expression.CurrentEntity <CodeFile>();
            var      blame    = vcsData.Blame(revision, file.Path);

            if (blame != null)
            {
                var linesByRevision = blame.Select(x => new
                {
                    Revision = x.Key,
                    CodeSize = x.Value
                }).ToList();

                void CopyCode()
                {
                    foreach (var linesForRevision in linesByRevision)
                    {
                        var newExp = expression.Code(linesForRevision.CodeSize);
                        if (linesForRevision.Revision != revision)
                        {
                            newExp.CopiedFrom(linesForRevision.Revision);
                        }
                        codeBlockExpressions.Add(newExp);
                    }
                };

                if ((modification.Action == TouchedFileAction.ADDED) &&
                    (modification.SourceFile != null))
                {
                    CopyCode();
                }
                else
                {
                    var addedCode = linesByRevision.SingleOrDefault(x => x.Revision == revision);
                    if (addedCode != null)
                    {
                        linesByRevision.Remove(addedCode);
                        codeBlockExpressions.Add(
                            expression.Code(addedCode.CodeSize)
                            );
                    }

                    var isMerge        = vcsData.Log(revision).IsMerge;
                    var updatedCodeExp = expression.UpdateCode((exp, rev, size) =>
                    {
                        var linesForRevision = linesByRevision.SingleOrDefault(x => x.Revision == rev);
                        if (linesForRevision != null)
                        {
                            linesByRevision.Remove(linesForRevision);
                        }
                        double realCodeSize = linesForRevision == null ? 0 : linesForRevision.CodeSize;
                        if ((size > realCodeSize) ||
                            (size < realCodeSize && isMerge))
                        {
                            var newExp = expression.Code(realCodeSize - size);
                            newExp.ForCodeAddedInitiallyInRevision(rev);
                            return(newExp);
                        }

                        return(null);
                    });
                    if (isMerge && linesByRevision.Count > 0)
                    {
                        CopyCode();
                    }
                    if (updatedCodeExp != null)
                    {
                        codeBlockExpressions.Add(updatedCodeExp);
                    }
                }
            }

            if (codeBlockExpressions.Count == 0 && modification.Action == TouchedFileAction.MODIFIED)
            {
                expression.Revert();
            }
            return(codeBlockExpressions);
        }
Example #48
0
 protected bool Equals(Modification other)
 {
     return(ExplicitMod.Equals(other.ExplicitMod) && MonoisotopicMass.Equals(other.MonoisotopicMass) &&
            AverageMass.Equals(other.AverageMass));
 }
        /// <summary>
        ///     Synergy specific implemtation of <see cref="IHistoryParser.Parse"/>
        /// </summary>
        /// <remarks>
        ///     Processes both the task query and the object query to fully populate each
        ///     <see cref="Modification"/> object in the returned array.
        /// </remarks>
        /// <param name="newTasks">
        ///     Standard output stream from the Synergy query command.
        /// </param>
        /// <param name="newObjects">
        ///     Standard output stream from the Synergy finduse command.
        /// </param>
        /// <param name="from">
        ///     The date since the last successful integration run.  Not used, since the finduse
        ///     query includes this parameter.
        /// </param>
        /// <returns>
        ///     <c>null</c> by default.
        ///     If changes have occurred since the last integration attempt, an array containing
        ///     each new modification is returned.
        /// </returns>
        public virtual Modification[] Parse(string newTasks, string newObjects, DateTime from)
        {
            var       modifications = new List <Modification>();
            Hashtable tasks         = new Hashtable();

            // don't bother doing anything if no modified objects were found
            if (string.IsNullOrEmpty(newObjects))
            {
                return(new Modification[0]);
            }

            // optionally, parse the comments from each associated task
            if (!string.IsNullOrEmpty(newTasks))
            {
                tasks = ParseTasks(newTasks);
            }

            // look for modifications in the output from the finduse command
            Regex           grep    = new Regex(ObjectFormat, RegexOptions.CultureInvariant);
            MatchCollection matches = grep.Matches(newObjects);

            // each match is a detected modification
            foreach (Match match in matches)
            {
                Modification modification = new Modification();
                modification.FolderName   = match.Groups["folder"].Value;
                modification.FileName     = match.Groups["displayname"].Value;
                modification.Type         = match.Groups["cvtype"].Value;
                modification.EmailAddress = match.Groups["resolver"].Value;
                modification.UserName     = match.Groups["resolver"].Value;

                /* normalize the folder path to resemble other SCM systems
                 * vis a vis the "$/project/folder/file" format */
                if (modification.FolderName.Length > 0)
                {
                    modification.FolderName = String.Concat("$/", modification.FolderName.Replace('\\', '/'));
                }

                // Retrieve the comment, if available
                CaptureCollection captures = match.Groups["task"].Captures;
                if (null != captures)
                {
                    foreach (Capture capture in captures)
                    {
                        SynergyTaskInfo info = (SynergyTaskInfo)tasks[capture.Value];
                        if (info == null)
                        {
                            modification.ChangeNumber = Regex.Match(capture.Value, @"\d+").Value;
                        }
                        else
                        {
                            modification.ChangeNumber = info.TaskNumber.ToString(CultureInfo.CurrentCulture);
                            modification.ModifiedTime = info.CompletionDate;
                            if (null != info.TaskSynopsis)
                            {
                                modification.Comment = info.TaskSynopsis;
                            }
                        }
                    }
                }
                modifications.Add(modification);
            }
            return(modifications.ToArray());
        }
        public static void TestModificationAnalysisWithNonLocalizedPtms()
        {
            Ms2ScanWithSpecificMass scan = new Ms2ScanWithSpecificMass(new MsDataScan(new MzSpectrum(new double[, ] {
            }), 0, 0, true, Polarity.Positive,
                                                                                      0, new MzLibUtil.MzRange(0, 0), "", MZAnalyzerType.FTICR, 0, null, null, ""), 0, 0, "", new CommonParameters());

            ModificationMotif.TryGetMotif("N", out ModificationMotif motif1);
            Modification mod1 = new Modification(_originalId: "mod1", _modificationType: "mt", _target: motif1, _locationRestriction: "Anywhere.", _monoisotopicMass: 10, _neutralLosses: new Dictionary <DissociationType, List <double> > {
                { MassSpectrometry.DissociationType.AnyActivationType, new List <double> {
                      10
                  } }
            });

            IDictionary <int, List <Modification> > oneBasedModifications = new Dictionary <int, List <Modification> >
            {
                { 2, new List <Modification> {
                      mod1
                  } },
                { 7, new List <Modification> {
                      mod1
                  } },
            };
            Protein protein1 = new Protein("MNLDLDNDL", "prot1", oneBasedModifications: oneBasedModifications);

            Dictionary <int, Modification> allModsOneIsNterminus1 = new Dictionary <int, Modification>
            {
                { 2, mod1 },
            };
            PeptideWithSetModifications pwsm1 = new PeptideWithSetModifications(protein1, new DigestionParams(), 2, 9, CleavageSpecificity.Unknown, null, 0, allModsOneIsNterminus1, 0);

            Dictionary <int, Modification> allModsOneIsNterminus3 = new Dictionary <int, Modification>
            {
                { 7, mod1 },
            };
            PeptideWithSetModifications pwsm2 = new PeptideWithSetModifications(protein1, new DigestionParams(), 2, 9, CleavageSpecificity.Unknown, null, 0, allModsOneIsNterminus3, 0);

            CommonParameters CommonParameters = new CommonParameters(digestionParams: new DigestionParams(maxMissedCleavages: 0, minPeptideLength: 1), scoreCutoff: 1);
            var fsp = new List <(string fileName, CommonParameters fileSpecificParameters)>();

            fsp.Add(("", CommonParameters));

            PeptideSpectralMatch myPsm = new PeptideSpectralMatch(pwsm1, 0, 10, 0, scan, new CommonParameters(), new List <MatchedFragmentIon>());

            myPsm.AddOrReplace(pwsm2, 10, 0, true, new List <MatchedFragmentIon>(), 0);

            myPsm.ResolveAllAmbiguities();

            MassDiffAcceptor searchMode  = new SinglePpmAroundZeroSearchMode(5);
            List <Protein>   proteinList = new List <Protein> {
                protein1
            };

            FdrAnalysisEngine fdrAnalysisEngine = new FdrAnalysisEngine(new List <PeptideSpectralMatch> {
                myPsm
            }, searchMode.NumNotches, CommonParameters, fsp, new List <string>());

            fdrAnalysisEngine.Run();
            ModificationAnalysisEngine modificationAnalysisEngine = new ModificationAnalysisEngine(new List <PeptideSpectralMatch> {
                myPsm
            }, new CommonParameters(), fsp, new List <string>());
            var res = (ModificationAnalysisResults)modificationAnalysisEngine.Run();

            Assert.AreEqual(1, res.CountOfEachModSeenOnProteins.Count());
            Assert.AreEqual(2, res.CountOfEachModSeenOnProteins[mod1.IdWithMotif]);
            Assert.AreEqual(0, res.CountOfModsSeenAndLocalized.Count());
            Assert.AreEqual(0, res.CountOfAmbiguousButLocalizedModsSeen.Count);
            Assert.AreEqual(1, res.CountOfUnlocalizedMods[mod1.IdWithMotif]); // Saw it, but not sure where!
            Assert.AreEqual(0, res.CountOfUnlocalizedFormulas.Count());
        }
        //Reading in metamopheus excel
        public List <TopDownHit> ReadMetamopheusFile(InputFile file)
        {
            //if neucode labeled, calculate neucode light theoretical AND observed mass! --> better for matching up
            //if carbamidomethylated, add 57 to theoretical mass (already in observed mass...)
            aaIsotopeMassList = new AminoAcidMasses(Sweet.lollipop.carbamidomethylation, Sweet.lollipop.neucode_labeled).AA_Masses;
            List <TopDownHit> td_hits = new List <TopDownHit>();//for one line in excel file

            //creates dictionary to find mods
            Dictionary <string, Modification> mods = Sweet.lollipop.theoretical_database.all_mods_with_mass.ToDictionary(kv => kv.IdWithMotif, kv => kv);


            List <List <string> > cells = ExcelReader.get_cell_strings(file, true);//This returns the entire sheet except for the header. Each row of cells is one List<string>

            //get ptms on proteoform -- check for mods. IF not in database, make new topdown mod, show Warning message.
            Parallel.ForEach(cells, cellStrings =>
            {
                bool add_topdown_hit = true; //if PTM or accession not found, will not add (show warning)
                if (cellStrings.Count == 55)
                {
                    List <Ptm> new_ptm_list = new List <Ptm>();
                    //if bad mod itll catch it to add to bad_topdown_ptms
                    try
                    {
                        PeptideWithSetModifications modsIdentifier = new PeptideWithSetModifications(cellStrings[14].Split('|')[0], mods);

                        var ptm_list = modsIdentifier.AllModsOneIsNterminus;

                        //for each  entry in ptm_list make a new Ptm and add it to the new_ptm_list
                        foreach (KeyValuePair <int, Proteomics.Modification> entry in ptm_list)
                        {
                            Modification mod = Sweet.lollipop.theoretical_database.uniprotModifications.Values.SelectMany(m => m).Where(m => m.IdWithMotif == entry.Value.IdWithMotif).FirstOrDefault();
                            var Ptm          = new Ptm();

                            if (mod != null)
                            {
                                new_ptm_list.Add(new Ptm(entry.Key, entry.Value));
                            }
                            else
                            {
                                lock (bad_topdown_ptms)
                                {
                                    //error is somewahre in sequece
                                    bad_topdown_ptms.Add("Mod Name:" + entry.Value.IdWithMotif + " at " + entry.Key);
                                    add_topdown_hit = false;
                                }
                            }
                        }
                    }
                    catch (MzLibUtil.MzLibException)
                    {
                        lock (bad_topdown_ptms)
                        {
                            //error is somewahre in sequece
                            bad_topdown_ptms.Add("Bad mod at " + cellStrings[0] + " scan " + cellStrings[1]);
                            add_topdown_hit = false;
                        }
                    }

                    //This is the excel file header:
                    //cellStrings[0]=File Name
                    //cellStrings[1]=Scan Number
                    //cellStrings[2]=Scan Retention Time
                    //cellStrings[3]=Num Experimental Peaks
                    //cellStrings[4]=Total Ion Current
                    //cellStrings[5]=Precursor Scan Number
                    //cellStrings[6]=Precursor Charge
                    //cellStrings[7]=Precursor MZ
                    //cellStrings[8]=Precursor Mass
                    //cellStrings[9]=Score
                    //cellStrings[10]=Delta Score
                    //cellStrings[11]=Notch
                    //cellStrings[12]=Different Peak Matches
                    //cellStrings[13]=Base Sequence
                    //cellStrings[14]=Full Sequence
                    //cellStrings[15]=Essential Sequence
                    //cellStrings[16]=PSM Count
                    //cellStrings[17]=Mods
                    //cellStrings[18]=Mods Chemical Formulas
                    //cellStrings[19]=Mods Combined Chemical Formula
                    //cellStrings[20]=Num Variable Mods
                    //cellStrings[21]=Missed Cleavages
                    //cellStrings[22]=Peptide Monoisotopic Mass
                    //cellStrings[23]=Mass Diff (Da)
                    //cellStrings[24]=Mass Diff (ppm)
                    //cellStrings[25]=Protein Accession
                    //cellStrings[26]=Protein Name
                    //cellStrings[27]=Gene Name
                    //cellStrings[28]=Organism Name
                    //cellStrings[29]=Intersecting Sequence Variations
                    //cellStrings[30]=Identified Sequence Variations
                    //cellStrings[31]=Splice Sites
                    //cellStrings[32]=Contaminant
                    //cellStrings[33]=Decoy
                    //cellStrings[34]=Peptide Description
                    //cellStrings[35]=Start and End Residues In Protein
                    //cellStrings[36]=Previous Amino Acid
                    //cellStrings[37]=Next Amino Acid
                    //cellStrings[38]=All Scores
                    //cellStrings[39]=Theoreticals Searched
                    //cellStrings[40]=Decoy/Contaminant/Target
                    //cellStrings[41]=Matched Ion Series
                    //cellStrings[42]=Matched Ion Mass-To-Charge Ratios
                    //cellStrings[43]=Matched Ion Mass Diff (Da)
                    //cellStrings[44]=Matched Ion Mass Diff (Ppm)
                    //cellStrings[45]=Matched Ion Intensities
                    //cellStrings[46]=Matched Ion Counts
                    //cellStrings[47]=Localized Scores
                    //cellStrings[48]=Improvement Possible
                    //cellStrings[49]=Cumulative Target
                    //cellStrings[50]=Cumulative Decoy
                    //cellStrings[51]=QValue
                    //cellStrings[52]=Cumulative Target Notch
                    //cellStrings[53]=Cumulative Decoy Notch
                    //cellStrings[54]=QValue Notch
                    //cellStrings[55]=eValue
                    //cellStrings[56]=eScore



                    if (cellStrings[35].Length > 0)
                    {
                        string[] ids = cellStrings[35].Split('|');
                        //splits the string to get the value of starting index
                        string[] index = ids[0].Split(' ');

                        string[] startIndexValue = index[0].Split('[');
                        string startResidues     = startIndexValue[1];

                        //splits string to get value of ending index
                        string[] endIndexValue = index[2].Split(']');
                        string endResidues     = endIndexValue[0];


                        if (add_topdown_hit)
                        {
                            //if bad mod u want td hit to be false
                            TopDownHit td_hit = new TopDownHit(aaIsotopeMassList, file, TopDownResultType.TightAbsoluteMass, cellStrings[25], cellStrings[14], cellStrings[25], cellStrings[26], cellStrings[13],
                                                               Int32.TryParse(startResidues, out int j) ? j : 0, Int32.TryParse(endResidues, out int i) ? i : 0, new_ptm_list, Double.TryParse(cellStrings[8], out double d) ? d : 0, Double.TryParse(cellStrings[22], out d) ? d : 0,
                                                               Int32.TryParse(cellStrings[1], out i) ? i : 0, Double.TryParse(cellStrings[2], out d) ? d : 0, cellStrings[0].Split('.')[0], Double.TryParse(cellStrings[8], out d) ? d : 0, Sweet.lollipop.min_score_td + 1);


                            if (td_hit.begin > 0 && td_hit.end > 0 && td_hit.theoretical_mass > 0 && td_hit.pscore > 0 && td_hit.reported_mass > 0 && td_hit.score > 0 &&
                                td_hit.ms2ScanNumber > 0 && td_hit.ms2_retention_time > 0)
                            {
                                lock (td_hits) td_hits.Add(td_hit);
                            }
                        }
                    }
                }
            });
            return(td_hits);
        }
Example #52
0
        /// <summary>
        /// Parses the parameter file for ascore
        /// </summary>
        /// <param name="inputFile">name of the xml file</param>
        /// <returns>ascore parameters object</returns>
        public static AScoreParameters ParseXml(string inputFile)
        {
            XmlDocument parameterFile = new XmlDocument();

            parameterFile.Load(new XmlTextReader(inputFile));

            XmlNodeList staticMod  = parameterFile.SelectNodes("/Run/Modifications/StaticSeqModifications");
            XmlNodeList terminiMod = parameterFile.SelectNodes("/Run/Modifications/TerminiModifications");
            XmlNodeList dynamicMod = parameterFile.SelectNodes("/Run/Modifications/DynamicModifications");

            XmlNode massTolerance = parameterFile.SelectSingleNode("/Run/MassTolerance");

            XmlNode fragmentType = parameterFile.SelectSingleNode("/Run/FragmentType");



            FragmentType f       = GetFragmentType(fragmentType);
            double       massTol = double.Parse(massTolerance.InnerText);

            List <Modification>        stat    = new List <Modification>();
            List <TerminiModification> termMod = new List <TerminiModification>();
            List <DynamicModification> dynam   = new List <DynamicModification>();


            foreach (XmlNode mod in staticMod)
            {
                foreach (XmlNode mod2 in mod.ChildNodes)
                {
                    double      massMonoIsotopic = 0.0;
                    char        modSymbol        = ' ';
                    List <char> possibleModSites = new List <char>();
                    int         uniqueID         = 0;
                    foreach (XmlNode item in mod2.ChildNodes)
                    {
                        if (item.Name == "MassMonoIsotopic")
                        {
                            massMonoIsotopic = double.Parse(item.InnerText);
                        }
                        else if (item.Name == "PossibleModSites")
                        {
                            foreach (XmlNode item2 in item.ChildNodes)
                            {
                                possibleModSites.Add(item2.InnerText[0]);
                            }
                        }
                        else if (item.Name == "UniqueID")
                        {
                            uniqueID = int.Parse(item.InnerText);
                        }
                    }
                    Modification m = new Modification();
                    m.MassMonoisotopic = massMonoIsotopic;
                    m.ModSymbol        = modSymbol;
                    m.PossibleModSites = possibleModSites;
                    m.UniqueID         = uniqueID;
                    stat.Add(m);
                }
            }


            foreach (XmlNode mod in terminiMod)
            {
                foreach (XmlNode mod2 in mod.ChildNodes)
                {
                    double      massMonoIsotopic = 0.0;
                    char        modSymbol        = ' ';
                    List <char> possibleModSites = new List <char>();
                    int         uniqueID         = 0;
                    bool        nTerm            = false;
                    bool        cTerm            = false;
                    foreach (XmlNode item in mod2.ChildNodes)
                    {
                        if (item.Name == "MassMonoIsotopic")
                        {
                            massMonoIsotopic = double.Parse(item.InnerText);
                        }
                        else if (item.Name == "UniqueID")
                        {
                            uniqueID = int.Parse(item.InnerText);
                        }

                        else if (item.Name == "Nterm")
                        {
                            nTerm = bool.Parse(item.InnerText);
                        }
                        else if (item.Name == "Cterm")
                        {
                            cTerm = bool.Parse(item.InnerText);
                        }
                    }

                    TerminiModification m = new TerminiModification();
                    m.MassMonoisotopic = massMonoIsotopic;
                    m.ModSymbol        = modSymbol;
                    m.PossibleModSites = possibleModSites;
                    m.UniqueID         = uniqueID;
                    m.nTerminus        = nTerm;
                    m.cTerminus        = cTerm;
                    termMod.Add(m);
                }
            }


            foreach (XmlNode mod in dynamicMod)
            {
                foreach (XmlNode mod2 in mod.ChildNodes)
                {
                    double      massMonoIsotopic = 0.0;
                    char        modSymbol        = ' ';
                    List <char> possibleModSites = new List <char>();
                    int         uniqueID         = 0;
                    foreach (XmlNode item in mod2.ChildNodes)
                    {
                        if (item.Name == "MassMonoIsotopic")
                        {
                            massMonoIsotopic = double.Parse(item.InnerText);
                        }
                        else if (item.Name == "ModificationSymbol")
                        {
                            modSymbol = item.InnerText[0];
                        }
                        else if (item.Name == "PossibleModSites")
                        {
                            foreach (XmlNode item2 in item.ChildNodes)
                            {
                                possibleModSites.Add(item2.InnerText[0]);
                            }
                        }
                        else if (item.Name == "UniqueID")
                        {
                            uniqueID = int.Parse(item.InnerText);
                        }
                        else if (item.Name == "MaxPerSite")
                        {
                        }
                    }
                    DynamicModification m = new DynamicModification();
                    m.MassMonoisotopic = massMonoIsotopic;
                    m.ModSymbol        = modSymbol;
                    m.PossibleModSites = possibleModSites;
                    m.UniqueID         = uniqueID;
                    dynam.Add(m);
                }
            }



            AScoreParameters aParams = new AScoreParameters(stat, termMod, dynam, f, massTol);

            return(aParams);
        }
 /// <summary>
 /// Accepts the specified m.
 /// </summary>
 /// <param name="m">The m.</param>
 /// <returns></returns>
 /// <remarks></remarks>
 public bool Accept(Modification m)
 {
     return(Array.IndexOf(UserNames, m.UserName) >= 0);
 }
Example #54
0
 /// <summary>
 /// Creates the individual get string.
 /// </summary>
 /// <param name="mod">The mod.</param>
 /// <param name="fileLocation">The file location.</param>
 /// <returns></returns>
 /// <remarks></remarks>
 public string CreateIndividualGetString(Modification mod, string fileLocation)
 {
     return(string.Format(CultureInfo.CurrentCulture, INDIVIDUAL_GET_REVISION_TEMPLATE, GetVersion(mod, string.Empty), GetUncPathPrefix(mod), mod.FolderName, mod.FileName, fileLocation));
 }
Example #55
0
 /// <summary>
 /// Method calls listeners of the change event
 /// </summary>
 /// <param name="message">Some sembols that brings info about event</param>
 protected void Modified(string message)
 {
     Modification?.Invoke(message);
 }
Example #56
0
 public ModificationController(Modification modification, ModificationViewModel viewModel)
 {
     this.modification = modification;
     this.viewModel    = viewModel;
 }
Example #57
0
 private string GetUncPathPrefix(Modification mod)
 {
     //Add extract \ for UNC paths
     return(mod.FolderName.StartsWith("\\") ? @"\" :string.Empty);
 }
Example #58
0
 /// <summary>
 /// Determines whether given modification can be a C-terminal modification
 /// </summary>
 /// <param name="variableModification"></param>
 /// <param name="peptideLength"></param>
 /// <returns></returns>
 private bool CanBeCTerminalMod(Modification variableModification, int peptideLength)
 {
     return(ModificationLocalization.ModFits(variableModification, Protein.BaseSequence, peptideLength, peptideLength, OneBasedStartResidueInProtein + peptideLength - 1) &&
            (variableModification.LocationRestriction == "C-terminal." || variableModification.LocationRestriction == "Peptide C-terminal."));
 }
Example #59
0
 private string GetVersion(Modification mod, string label)
 {
     return((label == null || label.Length == 0) ? (mod.Version == null ? "1.0" : mod.Version) : (LabelOrPromotionInput(label)));
 }
        private void SetUpGeneticAlgorithm()
        {
            populationSize = optimizationSettings.PopulationSize;

            tournamentSelectionParameter = optimizationSettings.TournamentSelectionParameter;
            tournamentSize = optimizationSettings.TournamentSize;
            // Note: The mutation rate is set below, after the individuals have been generated
            crossoverProbability = optimizationSettings.CrossoverProbability;
            creepMutationRate    = optimizationSettings.CreepMutationRate;

            int numberOfLineSegments = optimizationSettings.NumberOfSpeedPoints;

            double minimumParameterValue = optimizationSettings.MinimumSpeedValue;
            double maximumParameterValue = optimizationSettings.MaximumSpeedValue;
            double discretizationStep    = optimizationSettings.SpeedIncrement;
            double desiredAverageSpeed   = optimizationSettings.DesiredAverageSpeed;

            possibleSpeedList = new List <double>();
            double initialSpeed = minimumParameterValue;

            possibleSpeedList.Add(initialSpeed);

            while (initialSpeed < maximumParameterValue)
            {
                initialSpeed += discretizationStep;
                initialSpeed  = Math.Min(initialSpeed, maximumParameterValue);
                possibleSpeedList.Add(initialSpeed);
            }

            //returns the index of desired average speed from the possible speed list (generated above). Required for optimizaiton.
            int desiredAverageSpeedIndex = possibleSpeedList.FindIndex(s => s == desiredAverageSpeed);

            OptimizableStructure cruiseControlSpeedProfile = new OptimizableStructure();

            IntParameter p0ParameterFirstIndividual = new IntParameter();

            p0ParameterFirstIndividual.MaximumValue   = possibleSpeedList.Count - 1;
            p0ParameterFirstIndividual.MinimumValue   = 0;
            p0ParameterFirstIndividual.ParameterValue = desiredAverageSpeedIndex;
            cruiseControlSpeedProfile.ParameterList.Add(p0ParameterFirstIndividual);

            for (int jj = 0; jj < numberOfLineSegments; jj++)
            {
                IntParameter p0Parameter = new IntParameter();
                p0Parameter.MaximumValue   = possibleSpeedList.Count - 1;
                p0Parameter.MinimumValue   = 0;
                p0Parameter.ParameterValue = desiredAverageSpeedIndex;
                cruiseControlSpeedProfile.ParameterList.Add(p0Parameter);
            }
            population.Add(cruiseControlSpeedProfile.Copy());
            scoreList.Add(double.MinValue);

            for (int ii = 1; ii < populationSize; ii++)
            {
                OptimizableStructure individual = new OptimizableStructure();

                IntParameter p0ParameterFirst = new IntParameter();
                p0ParameterFirst.MaximumValue   = possibleSpeedList.Count - 1;
                p0ParameterFirst.MinimumValue   = 0;
                p0ParameterFirst.ParameterValue = desiredAverageSpeedIndex;
                individual.ParameterList.Add(p0ParameterFirst);

                for (int jj = 0; jj < numberOfLineSegments; jj++)
                {
                    IntParameter p0Parameter = new IntParameter();
                    p0Parameter.MaximumValue   = possibleSpeedList.Count - 1;
                    p0Parameter.MinimumValue   = 0;
                    p0Parameter.ParameterValue = desiredAverageSpeedIndex;
                    individual.ParameterList.Add(p0Parameter);
                }

                // Randomize all individuals except the first one:
                OptimizableStructure mutatedIndividual = (OptimizableStructure)Modification.Execute(individual,
                                                                                                    1.0, 1.0, randomNumberGenerator);

                population.Add(mutatedIndividual.Copy());
                scoreList.Add(double.MinValue);
            }

            mutationRate = optimizationSettings.RelativeMutationProbability /
                           (double)population[0].ParameterList.Count;
        }