25 February 2022

Enumerating Gene Orders - https://rosalind.info/problems/perm/

 from itertools import permutations  
 import math  
 f = open("out.txt", "w")  
 num=5  
 s=1   
 e=s+num  
 p=math.factorial(num)  
 print(p)  
 f.write(str(p) + '\n')  
 l = list(permutations(range(s, e)))  
 for i in range(p):  
   for j in range(num):  
     print(l[i][j], end=' ')  
     f.write(str(l[i][j]) + ' ')  
   print('')    
   f.write('\n')  
 f.close()    

Calculating Protein Mass - https://rosalind.info/problems/prtm/

 mmt = {  
 "A":71.03711,  
 "C":103.00919,  
 "D":115.02694,  
 "E":129.04259,  
 "F":147.06841,  
 "G":57.02146,  
 "H":137.05891,  
 "I":113.08406,  
 "K":128.09496,  
 "L":113.08406,  
 "M":131.04049,  
 "N":114.04293,  
 "P":97.05276,  
 "Q":128.05858,  
 "R":156.10111,  
 "S":87.03203,  
 "T":101.04768,  
 "V":99.06841,  
 "W":186.07931,  
 "Y":163.06333 }  
 input_file = open("rosalind_prtm.txt", "r")  
 AA = input_file.read().replace('\n','')  
 print(sum([mmt[x] for x in AA]))  

Answer for ROSALIND Open Reading Frames https://rosalind.info/problems/orf/

 import re  
 condon_len = 3  
 c_map = {  
   "A":"T",  
   "G":"C",  
   "C":"G",  
   "T":"A"  
 }  
 dna_map = {  
   "TTT":"F", "TCT":"S", "TAT":"Y", "TGT":"C",   
 "TTC":"F", "TCC":"S", "TAC":"Y", "TGC":"C",   
 "TTA":"L", "TCA":"S", "TAA":"STOP", "TGA":"STOP",   
 "TTG":"L", "TCG":"S", "TAG":"STOP", "TGG":"W",   
 "CTT":"L", "CCT":"P", "CAT":"H", "CGT":"R",   
 "CTC":"L", "CCC":"P", "CAC":"H", "CGC":"R",   
 "CTA":"L", "CCA":"P", "CAA":"Q", "CGA":"R",   
 "CTG":"L", "CCG":"P", "CAG":"Q", "CGG":"R",   
 "ATT":"I", "ACT":"T", "AAT":"N", "AGT":"S",   
 "ATC":"I", "ACC":"T", "AAC":"N", "AGC":"S",   
 "ATA":"I", "ACA":"T", "AAA":"K", "AGA":"R",   
 "ATG":"M", "ACG":"T", "AAG":"K", "AGG":"R",   
 "GTT":"V", "GCT":"A", "GAT":"D", "GGT":"G",   
 "GTC":"V", "GCC":"A", "GAC":"D", "GGC":"G",   
 "GTA":"V", "GCA":"A", "GAA":"E", "GGA":"G",   
 "GTG":"V", "GCG":"A", "GAG":"E", "GGG":"G"  
 }  
 found = []  
 input_file = open("rosalind_orf.txt", "r")  
 def GetComplement(seq):  
   r = ''.join([c_map[x] for x in seq])  
   return r  
 def GetAA(condon):  
   return dna_map[condon]  
 def GetAASeq(dna_seq, pos):  
   dna_seq_len = len(dna_seq)  
   seq=""  
   start_pos = pos  
   end_pos = pos + condon_len  
   condon = dna_seq[start_pos:end_pos]  
   AA = GetAA(condon)  
   while AA != "STOP":  
     seq = seq + AA  
     start_pos = start_pos + condon_len  
     end_pos = end_pos + condon_len  
     if (end_pos> (dna_seq_len-1)):  
       return "" #end of seq reached without finding stop condon  
     condon = dna_seq[start_pos:end_pos]  
     AA = GetAA(condon)  
   found.append(seq)    
   return seq    
 dna_seq = ""  
 lines = input_file.readlines()  
 for l in lines:  
   if (l[0]!=">"):  
     dna_seq = dna_seq + l.replace("\n", "").replace("\r","")  
 r_dna_seq = GetComplement(dna_seq[::-1])  
 seq_regex="ATG"  
 p = re.compile(seq_regex)  
 for m in p.finditer(dna_seq):  
   GetAASeq(dna_seq, m.start())  
 for m in p.finditer(r_dna_seq):  
   GetAASeq(r_dna_seq, m.start())    
 for s in list(set(found)):  
   print(s)     

17 February 2022

ROSALIND - Inferring mRNA from Protein

Answer to https://rosalind.info/problems/mrna/
 def GetMRna(AA):  
   l_aa = {key for key, value in aa_map.items() if value == AA}  
   return l_aa  
 input_file = open("rosalind_mrna.txt", "r")  
 aa_seq = input_file.read().replace("\n", "")  
 print(aa_seq)  
 aa_map = {  
   "UUU":"F", "UCU":"S", "UAU":"Y", "UGU":"C",   
 "UUC":"F", "UCC":"S", "UAC":"Y", "UGC":"C",   
 "UUA":"L", "UCA":"S", "UAA":"STOP", "UGA":"STOP",   
 "UUG":"L", "UCG":"S", "UAG":"STOP", "UGG":"W",   
 "CUU":"L", "CCU":"P", "CAU":"H", "CGU":"R",   
 "CUC":"L", "CCC":"P", "CAC":"H", "CGC":"R",   
 "CUA":"L", "CCA":"P", "CAA":"Q", "CGA":"R",   
 "CUG":"L", "CCG":"P", "CAG":"Q", "CGG":"R",   
 "AUU":"I", "ACU":"T", "AAU":"N", "AGU":"S",   
 "AUC":"I", "ACC":"T", "AAC":"N", "AGC":"S",   
 "AUA":"I", "ACA":"T", "AAA":"K", "AGA":"R",   
 "AUG":"M", "ACG":"T", "AAG":"K", "AGG":"R",   
 "GUU":"V", "GCU":"A", "GAU":"D", "GGU":"G",   
 "GUC":"V", "GCC":"A", "GAC":"D", "GGC":"G",   
 "GUA":"V", "GCA":"A", "GAA":"E", "GGA":"G",   
 "GUG":"V", "GCG":"A", "GAG":"E", "GGG":"G",   
 }  
 condon_len = []  
 stop_condons_len = 3  
 aa_seq_len = len(aa_seq)  
 for i in range(aa_seq_len):  
   condons = GetMRna(aa_seq[i])  
   condons_len = len(condons)  
   stop_condons_len = stop_condons_len * condons_len  
 print("Answer:" + str(stop_condons_len % 1000000) )      

06 February 2022

Rosalind - Answer to Finding a Protein Motif

Answer to Finding a Protein Motif https://rosalind.info/problems/mprt/
 import urllib.request  
 import re  
 from numpy import mat  
 #N-glycosylation motif  
 MotifRegex = "N[^P][ST][^P]"  
 file_out = open("output.txt", "w")  
 #Class to process protein sequence  
 class Sequence:  
   def __init__(self, name, seq):  
     self.name = name  
     self.seq = seq  
   def FindReg(self, reg):  
     match_string = ""  
     for match in re.finditer('(?={0})'.format(MotifRegex), self.seq):  
       index = match.start()+1  
       if len(match_string) == 0:  
         match_string = str(index)  
       else:  
         match_string = match_string + " " + str(index)  
     return match_string   
   def PrintOutcome(self):  
     match_string = self.FindReg(MotifRegex)  
     if len(match_string)>0:  
       print(self.name)   
       print(match_string)  
       file_out.write(self.name + '\n')  
       file_out.write(match_string + '\n')  
 #Get protein sequence from https://www.uniprot.org/uniprot/  
 def GetProtein(name):  
   url_base = "https://www.uniprot.org/uniprot/"  
   url_prefix = ".fasta"  
   url = url_base + name + url_prefix  
   with urllib.request.urlopen(url) as response:  
     html = response.read()  
     lines = html.decode().split("\n")    
     for line in lines:  
       if len(line)>1 and line[0] == ">":  
         protein = Sequence(name, "")  
       else:  
         protein.seq = protein.seq+line  
   return protein        
 ProteinList = []  
 input_file = open("rosalind_mprt.txt", "r")  
 #input_file = open("input.txt", "r")  
 lines = input_file.readlines()  
 for line in lines:  
   Protein = GetProtein(line.replace("\n", ""))  
   ProteinList.append(Protein)  
 for Protein in ProteinList:  
   Protein.PrintOutcome()    
 file_out.close()  

04 January 2022

Found a really useful rapidxml example

 #include <string.h>  
 #include <stdio.h>  
 #include <iostream>  
 #include <fstream>  
 #include <vector>  
 #include "rapidxml.hpp"  
 using namespace rapidxml;  
 using namespace std;  
 int main()  
 {  
           cout << "Parsing my beer journal..." << endl;  
           xml_document<> doc;  
           xml_node<>* root_node;  
           // Read the xml file into a vector  
           ifstream theFile("C:\\Work3\\ReadXml\\beerJournal.xml");  
           vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());  
           buffer.push_back('\0');  
           // Parse the buffer using the xml file parsing library into doc   
           doc.parse<0>(&buffer[0]);  
           // Find our root node  
           root_node = doc.first_node("MyBeerJournal");  
           // Iterate over the brewerys  
           for (xml_node<>* brewery_node = root_node->first_node("Brewery"); brewery_node; brewery_node = brewery_node->next_sibling())  
           {  
                     printf("I have visited %s in %s. ",  
                               brewery_node->first_attribute("name")->value(),  
                               brewery_node->first_attribute("location")->value());  
                     // Interate over the beers  
                     for (xml_node<>* beer_node = brewery_node->first_node("Beer"); beer_node; beer_node = beer_node->next_sibling())  
                     {  
                               printf("On %s, I tried their %s which is a %s. ",  
                                         beer_node->first_attribute("dateSampled")->value(),  
                                         beer_node->first_attribute("name")->value(),  
                                         beer_node->first_attribute("description")->value());  
                               printf("I gave it the following review: %s", beer_node->value());  
                     }  
                     cout << endl;  
           }  
 }  
 <?xml version="1.0" encoding="utf-8"?>  
 <MyBeerJournal>  
   <Brewery name="Founders Brewing Company" location="Grand Rapids, MI">  
     <Beer name="Centennial" description="IPA" rating="A+" dateSampled="01/02/2011">  
       "What an excellent IPA. This is the most delicious beer I have ever tasted!"  
     </Beer>  
   </Brewery>  
   <Brewery name="Brewery Vivant" location="Grand Rapids, MI">  
     <Beer name="Farmhouse Ale" description="Belgian Ale" rating="B" dateSampled="02/07/2015">  
       This beer is not so good... but I am not that big of a fan of english style ales.  
     </Beer>  
   </Brewery>  
   <Brewery name="Bells Brewery" location="Kalamazoo, MI">  
     <Beer name="Two Hearted Ale" description="IPA" rating="A" dateSampled="03/15/2012">  
       Another execllent brew. Two Hearted gives Founders Centennial a run for it's money.  
     </Beer>  
   </Brewery>  
 </MyBeerJournal>  

26 December 2021

Simple MFC UDP example

 // SimpleUDPDlg.cpp : implementation file  
 //  
 #include "stdafx.h"  
 #include "SimpleUDP.h"  
 #include "SimpleUDPDlg.h"  
 #include "afxsock.h"  
 #include "ClientSend.h"  
 #ifdef _DEBUG  
 #define new DEBUG_NEW  
 #undef THIS_FILE  
 static char THIS_FILE[] = __FILE__;  
 #endif  
 #define ECHOMAX 1024  
 /////////////////////////////////////////////////////////////////////////////  
 // CAboutDlg dialog used for App About  
      HANDLE thr;  
      unsigned long id1;  
 class CAboutDlg : public CDialog  
 {  
 public:  
      CAboutDlg();  
 // Dialog Data  
      //{{AFX_DATA(CAboutDlg)  
      enum { IDD = IDD_ABOUTBOX };  
      //}}AFX_DATA  
      // ClassWizard generated virtual function overrides  
      //{{AFX_VIRTUAL(CAboutDlg)  
      protected:  
      virtual void DoDataExchange(CDataExchange* pDX);  // DDX/DDV support  
      //}}AFX_VIRTUAL  
 // Implementation  
 protected:  
      //{{AFX_MSG(CAboutDlg)  
      //}}AFX_MSG  
      DECLARE_MESSAGE_MAP()  
 };  
 CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)  
 {  
      //{{AFX_DATA_INIT(CAboutDlg)  
      //}}AFX_DATA_INIT  
 }  
 void CAboutDlg::DoDataExchange(CDataExchange* pDX)  
 {  
      CDialog::DoDataExchange(pDX);  
      //{{AFX_DATA_MAP(CAboutDlg)  
      //}}AFX_DATA_MAP  
 }  
 BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)  
      //{{AFX_MSG_MAP(CAboutDlg)  
           // No message handlers  
      //}}AFX_MSG_MAP  
 END_MESSAGE_MAP()  
 /////////////////////////////////////////////////////////////////////////////  
 // CSimpleUDPDlg dialog  
 CSimpleUDPDlg::CSimpleUDPDlg(CWnd* pParent /*=NULL*/)  
      : CDialog(CSimpleUDPDlg::IDD, pParent)  
 {  
      //{{AFX_DATA_INIT(CSimpleUDPDlg)  
           // NOTE: the ClassWizard will add member initialization here  
      //}}AFX_DATA_INIT  
      // Note that LoadIcon does not require a subsequent DestroyIcon in Win32  
      m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);  
 }  
 void CSimpleUDPDlg::DoDataExchange(CDataExchange* pDX)  
 {  
      CDialog::DoDataExchange(pDX);  
      //{{AFX_DATA_MAP(CSimpleUDPDlg)  
      DDX_Control(pDX, IDC_EDIT1, m_edit);  
      //}}AFX_DATA_MAP  
 }  
 BEGIN_MESSAGE_MAP(CSimpleUDPDlg, CDialog)  
      //{{AFX_MSG_MAP(CSimpleUDPDlg)  
      ON_WM_SYSCOMMAND()  
      ON_WM_PAINT()  
      ON_WM_QUERYDRAGICON()  
      ON_BN_CLICKED(IDC_BUTTON1, OnStart)  
      //}}AFX_MSG_MAP  
 END_MESSAGE_MAP()  
 /////////////////////////////////////////////////////////////////////////////  
 // CSimpleUDPDlg message handlers  
 UINT ReceiveData(LPVOID pParam)  
 {  
      CSimpleUDPDlg *dlg=(CSimpleUDPDlg*)pParam;  
      AfxSocketInit(NULL);  
      CSocket echoServer;   
       // Create socket for sending/receiving datagrams  
       if (echoServer.Create(514, SOCK_DGRAM, NULL)== 0) {  
           AfxMessageBox("Create() failed");  
       }  
      for(;;) { // Run forever  
   // Client address  
   SOCKADDR_IN echoClntAddr;   
   // Set the size of the in-out parameter  
   int clntAddrLen = sizeof(echoClntAddr);  
   // Buffer for echo string  
   char echoBuffer[ECHOMAX];   
   // Block until receive message from a client  
   int recvMsgSize = echoServer.ReceiveFrom(echoBuffer,   
       ECHOMAX, (SOCKADDR*)&echoClntAddr, &clntAddrLen, 0);  
   if (recvMsgSize < 0) {  
    AfxMessageBox("RecvFrom() failed");  
   }  
      echoBuffer[recvMsgSize]='\0';  
   dlg->m_edit.ReplaceSel(echoBuffer);  
      dlg->m_edit.ReplaceSel("\r\n");  
  }  
 }  
 BOOL CSimpleUDPDlg::OnInitDialog()  
 {  
      CDialog::OnInitDialog();  
      // Add "About..." menu item to system menu.  
      // IDM_ABOUTBOX must be in the system command range.  
      ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);  
      ASSERT(IDM_ABOUTBOX < 0xF000);  
      CMenu* pSysMenu = GetSystemMenu(FALSE);  
      if (pSysMenu != NULL)  
      {  
           CString strAboutMenu;  
           strAboutMenu.LoadString(IDS_ABOUTBOX);  
           if (!strAboutMenu.IsEmpty())  
           {  
                pSysMenu->AppendMenu(MF_SEPARATOR);  
                pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);  
           }  
      }  
      // Set the icon for this dialog. The framework does this automatically  
      // when the application's main window is not a dialog  
      SetIcon(m_hIcon, TRUE);               // Set big icon  
      SetIcon(m_hIcon, FALSE);          // Set small icon  
      thr=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ReceiveData,this,NULL,&id1);  
      // TODO: Add extra initialization here  
      return TRUE; // return TRUE unless you set the focus to a control  
 }  
 void CSimpleUDPDlg::OnSysCommand(UINT nID, LPARAM lParam)  
 {  
      if ((nID & 0xFFF0) == IDM_ABOUTBOX)  
      {  
           CAboutDlg dlgAbout;  
           dlgAbout.DoModal();  
      }  
      else  
      {  
           CDialog::OnSysCommand(nID, lParam);  
      }  
 }  
 // If you add a minimize button to your dialog, you will need the code below  
 // to draw the icon. For MFC applications using the document/view model,  
 // this is automatically done for you by the framework.  
 void CSimpleUDPDlg::OnPaint()   
 {  
      if (IsIconic())  
      {  
           CPaintDC dc(this); // device context for painting  
           SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);  
           // Center icon in client rectangle  
           int cxIcon = GetSystemMetrics(SM_CXICON);  
           int cyIcon = GetSystemMetrics(SM_CYICON);  
           CRect rect;  
           GetClientRect(&rect);  
           int x = (rect.Width() - cxIcon + 1) / 2;  
           int y = (rect.Height() - cyIcon + 1) / 2;  
           // Draw the icon  
           dc.DrawIcon(x, y, m_hIcon);  
      }  
      else  
      {  
           CDialog::OnPaint();  
      }  
 }  
 // The system calls this to obtain the cursor to display while the user drags  
 // the minimized window.  
 HCURSOR CSimpleUDPDlg::OnQueryDragIcon()  
 {  
      return (HCURSOR) m_hIcon;  
 }  
 void CSimpleUDPDlg::OnStart()   
 {  
      // TODO: Add your control notification handler code here  
      CClientSend send;  
      send.DoModal();  
 }