<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Beginning Python for Bioinformatics &#187; wxPython</title>
	<atom:link href="http://python.genedrift.org/category/wxpython/feed/" rel="self" type="application/rss+xml" />
	<link>http://python.genedrift.org</link>
	<description>a step-by-step guide to create Python applications in bioinformatics</description>
	<lastBuildDate>Thu, 20 May 2010 21:34:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1-alpha</generator>
		<item>
		<title>Managing a simple database with Python, SQLite and wxPython, 8</title>
		<link>http://python.genedrift.org/2009/04/22/managing-a-simple-database-with-python-sqlite-and-wxpython-8/</link>
		<comments>http://python.genedrift.org/2009/04/22/managing-a-simple-database-with-python-sqlite-and-wxpython-8/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 15:04:17 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[Phase 2]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=282</guid>
		<description><![CDATA[Image via Wikipedia Thanks to the comments and suggestions to the last post, it&#8217;s possible to make now a more pythonic and clearly generic database update class. Let&#8217;s check how the &#8220;generic&#8221; update/edit entry function is currently: def update_data(self, values_list): &#039;&#039;&#039;edits and updates fields&#039;&#039;&#039; if sys.platform == &#039;darwin&#039;: (cursor, database) = link_db(self.db_path) else: (cursor, database) [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl style="width: 210px;" class="wp-caption alignright">
<dt class="wp-caption-dt"><a href="http://commons.wikipedia.org/wiki/Image:Gene.png"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Gene.png/200px-Gene.png" alt="Diagram of the location of introns and exons w..." title="Diagram of the location of introns and exons w..." height="160" width="200"></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image via <a href="http://commons.wikipedia.org/wiki/Image:Gene.png">Wikipedia</a></dd>
</dl>
</div>
</div>
<p>Thanks to the comments and suggestions to the last post, it&#8217;s possible to make now a more pythonic and clearly generic database update class. Let&#8217;s check how the &#8220;generic&#8221; update/edit entry function is currently:</p>
<pre name="code" class="python">
def update_data(self, values_list):
    &#039;&#039;&#039;edits and updates fields&#039;&#039;&#039;

    if sys.platform == &#039;darwin&#039;:
        (cursor, database) = link_db(self.db_path)
    else:
        (cursor, database) = link_db()

    cursor.execute(&quot;UPDATE bac SET  projects = ?, comments = ?, temperature = ?, cell = ?, box = ?, tubes = ?, chromosome = ?, sdate = ?, clone = ?, source
	= ?, location1 = ?, startpos = ?, endpos = ?,
	gene = ?, genelink = ?, dnaex = ?, validation = ?, pcr = ?, refs = ?, antibiotic = ? WHERE idbac = ?&quot;,
    values_list[&#039;projects&#039;], values_list[&#039;comments&#039;], values_list[&#039;temperature&#039;], values_list[&#039;cell&#039;], values_list[&#039;box&#039;], values_list[&#039;tubes&#039;],
    values_list[&#039;chromo&#039;], values_list[&#039;date&#039;], values_list[&#039;clone&#039;], values_list[&#039;source&#039;], values_list[&#039;location&#039;], values_list[&#039;start&#039;]
    values_list[&#039;end&#039;], values_list[&#039;gene&#039;], values_list[&#039;genelink&#039;], values_list[&#039;dna&#039;], values_list[&#039;validation&#039;], values_list[&#039;pcr&#039;],
    values_list[&#039;refs&#039;], values_list[&#039;antibiotic&#039;], values_list[&#039;idbac&#039;]))

    database.commit()
    database.close()
</pre>
<p>which is really ugly and, although it works, is not really useful outside this small project. Based on the comments the best option was to use placeholders and a dictionary, similar to the approach used on the insert data function. Pre-formatting a string to have both the field name to be updated and a placeholder (for instance <code>:idbac</code>) that will receive the values</p>
<pre name="code" class="python">
update = &#039;,&#039;.join([&#039;%s=:%s&#039; % (y, y) for y in values_list])
</pre>
<p>where update is the string we want and values_list is the dictionary with all the key-value pairs. I tried this approach, using this structure in the generic function, but then I decided that the best alternative was to put this <code>join</code> in the derived class function and pre-populate the string with the values and then send this string directly to the update function. In the end I opted to use this </p>
<pre name="code" class="python">
update = &#039;,&#039;.join([&#039;%s=\&quot;%s\&quot;&#039; % (y, values_list[y]) for y in values_list])
</pre>
<p>The latter is slightly different to what was suggested. The original one would create a tuple with the keys from the dictionary, making for instance <code>sdate:sdate</code>. With all these place holders just pass the dictionary and you have all the values inserted. This would be handy if the insert string was being created on the &#8220;generic&#8221; function. If we move this to the derived class, we can use the the alternative, keeping in mind that the values parsed should be surrounded by quotes, otherwise the SQL UPDATE statement will have problems with spaces and other foreign characters that should not be there. So instead of placeholders we will have <code>gene:"<a class="zem_slink" href="http://en.wikipedia.org/wiki/PTEN_%28gene%29" title="PTEN (gene)" rel="wikipedia">PTEN</a>"</code> and we can attache this joined string to the actual commands. We then can move all the machinery from the &#8220;generic&#8221; function that can be written as</p>
<pre name="code" class="python">
def update_data(self, update_string):
    &#039;&#039;&#039;edits and updates fields&#039;&#039;&#039;

    if sys.platform == &#039;darwin&#039;:
        (cursor, database) = link_db(self.db_path)
    else:
        (cursor, database) = link_db()
    cursor.execute(update_string)

    database.commit()
    database.close()
</pre>
<p>That&#8217;s it, very elegant (we will see the derived class in the next post). And finishing our generic class, we would need a delete function, so the user can eliminate entries that he/she doesn&#8217;t want anymore. It&#8217;s also a very simple function</p>
<pre name="code" class="python">
def delete_data(self, delete_string):
    &#039;&#039;&#039;deletes one field&#039;&#039;&#039;

    if sys.platform == &#039;darwin&#039;:
        (cursor, database) = link_db(self.db_path)
    else:
        (cursor, database) = link_db()
    cursor.execute(delete_string)

    database.commit()
    database.close()
</pre>
<p>We will check the delete string next time. Again, I would like to thank for all the comments, it has been really helpful for me.</p>
<p>Previously in the series:<br />
<a href="http://python.genedrift.org/2009/02/09/managing-a-simple-database-with-python-sqlite-and-wxpython-1/">Part 1</a><br />
<a href="http://python.genedrift.org/2009/02/17/managing-a-simple-database-with-python-sqlite-and-wxpython-2/">Part 2</a><br />
<a href="http://python.genedrift.org/2009/02/18/managing-a-simple-database-with-python-sqlite-and-wxpython-3/">Part 3</a><br />
<a href="http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-4/">Part 4</a><br />
<a href="http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-5/">Part 5</a><br />
<a href="http://python.genedrift.org/2009/03/31/managing-a-simple-database-with-python-sqlite-and-wxpython-6/">Part 6</a><br />
<a href="http://python.genedrift.org/2009/04/20/managing-a-simple-database-with-python-sqlite-and-wxpython-7-includes-a-question/">Part 7</a></p>
<div style="margin-top: 10px; height: 15px;" class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/e8dc77f5-e3de-4d4f-8ec1-8c0006225743/" title="Reblog this post [with Zemanta]"><img style="border: medium none ; float: right;" class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_a.png?x-id=e8dc77f5-e3de-4d4f-8ec1-8c0006225743" alt="Reblog this post [with Zemanta]"></a><span class="zem-script more-related pretty-attribution"><script type="text/javascript" src="http://static.zemanta.com/readside/loader.js" defer="defer"></script></span></div>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2009/04/22/managing-a-simple-database-with-python-sqlite-and-wxpython-8/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Managing a simple database with Python, SQLite and wxPython, 7 (includes a question)</title>
		<link>http://python.genedrift.org/2009/04/20/managing-a-simple-database-with-python-sqlite-and-wxpython-7-includes-a-question/</link>
		<comments>http://python.genedrift.org/2009/04/20/managing-a-simple-database-with-python-sqlite-and-wxpython-7-includes-a-question/#comments</comments>
		<pubDate>Mon, 20 Apr 2009 17:21:59 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[Phase 2]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/2009/04/20/managing-a-simple-database-with-python-sqlite-and-wxpython-7-includes-a-question/</guid>
		<description><![CDATA[And we&#8217;re back. After a couple of weeks of inactivity we will get back to our small soap-opera pf Python, wxPython and SQLite. Continuing in our database management code let&#8217;s check two other functions that changed since our first inception of the code. The first one is the insert_data function that looks like this now [...]]]></description>
			<content:encoded><![CDATA[<p>And we&#8217;re back. After a couple of weeks of inactivity we will get back to our small soap-opera pf Python, wxPython and SQLite. Continuing in our database management code let&#8217;s check two other functions that changed since our first inception of the code. The first one is the <code>insert_data</code> function that looks like this now</p>
<pre name="code" class="python">
def insert_data(self, values_list, insert_string):
    &#039;&#039;&#039;inserts data in the database&#039;&#039;&#039;

    if sys.platform == &#039;darwin&#039;:
        (cursor, database) = link_db(self.db_path)
    else:
        (cursor, database) = link_db()

    cursor.execute(insert_string % self.table_name, values_list)

    database.commit()
    database.close()
</pre>
<p>Basically no changes, apart from the obvious check for the current running operating system, which was explained in the last post. The other function to check is the <code>update_data</code>. This function is new and it wasn&#8217;t in the first version, but as it can be seen it has a problem being a &#8220;generic&#8221; function, because it contains information pertained to the table and database being used in the interface. This function basically received information that needs to be updated in the table&#8217;s fields and by using the SQL <code>UPDATE ... SET</code> edits and updates data in the changed fields. I have tried several different syntaxes to make the execute generic, mainly trying to pre-format the string without success. IF anyone reading this can help, I&#8217;d appreciate.</p>
<pre name="code" class="python">
def update_data(self, values_list):
    &#039;&#039;&#039;edits and updates fields&#039;&#039;&#039;

    if sys.platform == &#039;darwin&#039;:
        (cursor, database) = link_db(self.db_path)
    else:
        (cursor, database) = link_db()

    cursor.execute(&quot;UPDATE bac SET  projects = ?, comments = ?, temperature = ?, cell = ?, box = ?, tubes = ?, chromosome = ?, sdate = ?, clone = ?, source = ?, location1 = ?, startpos = ?, endpos = ?,
	gene = ?, genelink = ?, dnaex = ?, validation = ?, pcr = ?, refs = ?, antibiotic = ? WHERE idbac = ?&quot;,
    values_list[&#039;projects&#039;], values_list[&#039;comments&#039;], values_list[&#039;temperature&#039;], values_list[&#039;cell&#039;], values_list[&#039;box&#039;], values_list[&#039;tubes&#039;],
    values_list[&#039;chromo&#039;], values_list[&#039;date&#039;], values_list[&#039;clone&#039;], values_list[&#039;source&#039;], values_list[&#039;location&#039;], values_list[&#039;start&#039;],  values_list[&#039;end&#039;],
    values_list[&#039;gene&#039;], values_list[&#039;genelink&#039;], values_list[&#039;dna&#039;], values_list[&#039;validation&#039;], values_list[&#039;pcr&#039;],
    values_list[&#039;refs&#039;], values_list[&#039;antibiotic&#039;], values_list[&#039;idbac&#039;]))

    database.commit()
    database.close()
</pre>
<p>Anyway, I will explain the logic of the command (OK for a stop gap, but not as a definite solution). <code>values_list</code> is a dictionary that is passed to the function and contains the field names as keys and the new/changed information as values. The execute method simply parses the values from each key in the update string which is then sent to the database and table to be changed. Everything is committed and the database is closed.</p>
<p>As this is a &#8220;generic&#8221; function from a &#8220;generic&#8221; class the ideal scenario would be to the function to receive a pre-formatted string with all the information, as in the insert data function, and update the information in the database. </p>
<p>I would like to thank in advance anyone that can comment on this. Next time we will continue checking the generic class and finalize this part in order to start with the interface build process.</p>
<p>Previously in the series:<br />
<a href="http://python.genedrift.org/2009/02/09/managing-a-simple-database-with-python-sqlite-and-wxpython-1/">Part 1</a><br />
<a href="http://python.genedrift.org/2009/02/17/managing-a-simple-database-with-python-sqlite-and-wxpython-2/">Part 2</a><br />
<a href="http://python.genedrift.org/2009/02/18/managing-a-simple-database-with-python-sqlite-and-wxpython-3/">Part 3</a><br />
<a href="http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-4/">Part 4</a><br />
<a href="http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-5/">Part 5</a><br />
<a href="http://python.genedrift.org/2009/03/31/managing-a-simple-database-with-python-sqlite-and-wxpython-6/">Part 6</a></p>
<div style="margin-top: 10px; height: 15px;" class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/d0bb5d11-6f9d-8521-9a2f-6cd30868e375/" title="Reblog this post [with Zemanta]"><img style="border: medium none ; float: right;" class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_a.png?x-id=d0bb5d11-6f9d-8521-9a2f-6cd30868e375" alt="Reblog this post [with Zemanta]"></a><span class="zem-script more-related pretty-attribution"><script type="text/javascript" src="http://static.zemanta.com/readside/loader.js" defer="defer"></script></span></div>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2009/04/20/managing-a-simple-database-with-python-sqlite-and-wxpython-7-includes-a-question/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Managing a simple database with Python, SQLite and wxPython, 6</title>
		<link>http://python.genedrift.org/2009/03/31/managing-a-simple-database-with-python-sqlite-and-wxpython-6/</link>
		<comments>http://python.genedrift.org/2009/03/31/managing-a-simple-database-with-python-sqlite-and-wxpython-6/#comments</comments>
		<pubDate>Tue, 31 Mar 2009 17:06:08 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[Phase 2]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=276</guid>
		<description><![CDATA[Image via Wikipedia Let&#8217;s get back to our SQLite and wxPython project. We haven&#8217;t seen anything on wxPython yet, and we will check the interface only on the next post. For now, let&#8217;s see some extra code added to the SQLite access class. Remember that we have a generic class and one class derived from [...]]]></description>
			<content:encoded><![CDATA[<div class="zemanta-img" style="margin: 1em; display: block;">
<div>
<dl style="width: 212px;" class="wp-caption alignright">
<dt class="wp-caption-dt"><a href="http://commons.wikipedia.org/wiki/Image:SQLite_Logo_4.png"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/19/SQLite_Logo_4.png/202px-SQLite_Logo_4.png" alt="The :en:SQLite logo as of 2007-12-15" title="The :en:SQLite logo as of 2007-12-15" height="60" width="202"></a></dt>
<dd class="wp-caption-dd zemanta-img-attribution" style="font-size: 0.8em;">Image via <a href="http://commons.wikipedia.org/wiki/Image:SQLite_Logo_4.png">Wikipedia</a></dd>
</dl>
</div>
</div>
<p>Let&#8217;s get back to our SQLite and wxPython project. We haven&#8217;t seen anything on wxPython yet, and we will check the interface only on the next post. For now, let&#8217;s see some extra code added to the SQLite access class. Remember that we have a generic class and one class derived from it that would work on accessing specific tables in our database file.</p>
<p>When we last covered the db access routines, there was no search for an entry (the function returned everything in the table no matter what), there was no update function in case someone would want to modify an entry and there was no delete method if you wanted to delete something. In the meantime, I added all of this functionality (and some other) to the generic class and extended it to the class derived from it. Let&#8217;s check how the generic class is now (you will notice that there is an issue in one of the methods, if someone can help me I&#8217;d appreciate. More details later.)</p>
<pre name="code" class="python">
class DB_Generic():
    &#039;&#039;&#039;generic class to add DB functionality&#039;&#039;&#039;
    def __init__(self, table_name, db_path = &#039;&#039;):
        #par= name of the table to be used
        self.table_name = table_name
        if len(db_path) &amp;gt; 0:
            self.db_path = db_path
            print db_path

    def get_data_generic(self, range = 1, bac_to_get = 0):
        &#039;&#039;&#039;gets the data from the database&#039;&#039;&#039;       

        if sys.platform == &#039;darwin&#039;:
            (cursor, database) = link_db(self.db_path)
        else:
            (cursor, database) = link_db()

        if range == 1:
            cursor.execute(&quot;&quot;&quot;SELECT * FROM %s&quot;&quot;&quot; % self.table_name)
        elif range == 2:
            cursor.execute(&quot;&quot;&quot;SELECT * FROM %s where idbac = %d&quot;&quot;&quot; % (self.table_name, bac_to_get))

        table_data = cursor.fetchall()
        raw_data = []
        for i in table_data:
            raw_data.append(list(i))

        self.table_data = raw_data
        database.close()

    def insert_data(self, values_list, insert_string):
        &#039;&#039;&#039;inserts data in the database&#039;&#039;&#039;

        if sys.platform == &#039;darwin&#039;:
            (cursor, database) = link_db(self.db_path)
        else:
            (cursor, database) = link_db()

        cursor.execute(insert_string % self.table_name, values_list)

        database.commit()
        database.close()

    def update_data(self, values_list):
        &#039;&#039;&#039;edits and updates fields&#039;&#039;&#039;

        if sys.platform == &#039;darwin&#039;:
            (cursor, database) = link_db(self.db_path)
        else:
            (cursor, database) = link_db()

        #change this to generic!!!!!!!!!!!!
        cursor.execute(&quot;UPDATE bac SET  projects = ?, comments = ?, temperature = ?, cell = ?, box = ?, tubes = ?, chromosome = ?, sdate = ?, clone = ?, source = ?, location1 = ?, startpos = ?, endpos = ?,
		gene = ?, genelink = ?, dnaex = ?, validation = ?, pcr = ?, refs = ?, antibiotic = ? WHERE idbac = ?&quot;,
        (values_list[&#039;projects&#039;], values_list[&#039;comments&#039;], values_list[&#039;temperature&#039;], values_list[&#039;cell&#039;], values_list[&#039;box&#039;], values_list[&#039;tubes&#039;],
         values_list[&#039;chromo&#039;], values_list[&#039;date&#039;], values_list[&#039;clone&#039;], values_list[&#039;source&#039;], values_list[&#039;location&#039;], values_list[&#039;start&#039;], values_list[&#039;end&#039;],
         values_list[&#039;gene&#039;], values_list[&#039;genelink&#039;], values_list[&#039;dna&#039;], values_list[&#039;validation&#039;], values_list[&#039;pcr&#039;],
         values_list[&#039;refs&#039;], values_list[&#039;antibiotic&#039;], values_list[&#039;idbac&#039;]))

        database.commit()
        database.close()

    def delete_data(self, delete_string):
        &#039;&#039;&#039;deletes one field&#039;&#039;&#039;

        if sys.platform == &#039;darwin&#039;:
            (cursor, database) = link_db(self.db_path)
        else:
            (cursor, database) = link_db()
        cursor.execute(delete_string)

        database.commit()
        database.close()
</pre>
<p>In the next couple of posts we&#8217;ll dissect each function and see what&#8217;s going on. The class definition wasn&#8217;t changed, so we start with <code>get_data_generic</code></p>
<pre name="code" class="python">
def get_data_generic(self, range = 1, bac_to_get = 0):
	&#039;&#039;&#039;gets the data from the database&#039;&#039;&#039;       

	if sys.platform == &#039;darwin&#039;:
		(cursor, database) = link_db(self.db_path)
	else:
		(cursor, database) = link_db()

	if range == 1:
		cursor.execute(&quot;&quot;&quot;SELECT * FROM %s&quot;&quot;&quot; % self.table_name)
	elif range == 2:
		cursor.execute(&quot;&quot;&quot;SELECT * FROM %s where idbac = %d&quot;&quot;&quot; % (self.table_name, bac_to_get))

	table_data = cursor.fetchall()
	raw_data = []
	for i in table_data:
		raw_data.append(list(i))

	self.table_data = raw_data
	database.close()
</pre>
<p>The first difference we notice here is the <code>sys.platform</code> usage. This is required if we intend to package our application as an OS X app, using py2app. When a Python/wxPython application is packaged in OS X, the actual application executable is inside the a directory named after the application (or whatever you set up). In our case here we don&#8217;t provide a way for the Python script to receive the path and name for the database on a command line, as we expect it to be in the executable&#8217;s current directory. Because of that we need to provide a &#8220;config&#8221; file (in our case here a one-line text file with the database path) inside the application wrapper, something we will see in the end of the series.</p>
<p>Another modification here is the <code>range</code> parameter and the addition of the <code>bac_to_get</code> parameter. Notice that both parameters have a value assigned to it. This means that they are optional, the function&#8217;s call can pass them or not. If it doesn&#8217;t pass, their value will be the one assigned on the function declaration. So, here if we are interested in getting all bacs, <code>range</code> will have the value of 1 and we don&#8217;t need to worry about it. If we want an specific bac we will pass <code>range</code> as 2 and then pass the <code>bac_to_get</code> ID to be returned. </p>
<p>A final change/addition is that we added a new select statement for the cases when <code>range</code> equals 2. This time we are adding the bac ID to be returned.</p>
<p>Previously in the series:<br />
<a href="http://python.genedrift.org/2009/02/09/managing-a-simple-database-with-python-sqlite-and-wxpython-1/">Part 1</a><br />
<a href="http://python.genedrift.org/2009/02/17/managing-a-simple-database-with-python-sqlite-and-wxpython-2/">Part 2</a><br />
<a href="http://python.genedrift.org/2009/02/18/managing-a-simple-database-with-python-sqlite-and-wxpython-3/">Part 3</a><br />
<a href="http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-4/">Part 4</a><br />
<a href="http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-5/">Part 5</a></p>
<div style="margin-top: 10px; height: 15px;" class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/ea53b728-33c6-47db-aabf-0c695dcfabd8/" title="Zemified by Zemanta"><img style="border: medium none ; float: right;" class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_a.png?x-id=ea53b728-33c6-47db-aabf-0c695dcfabd8" alt="Reblog this post [with Zemanta]"></a><span class="zem-script more-related"><script type="text/javascript" src="http://static.zemanta.com/readside/loader.js" defer="defer"></script></span></div>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2009/03/31/managing-a-simple-database-with-python-sqlite-and-wxpython-6/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Managing a simple database with Python, SQLite and wxPython, 5</title>
		<link>http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-5/</link>
		<comments>http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-5/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 00:23:42 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[Phase 2]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[SQLite]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=253</guid>
		<description><![CDATA[We have seen how to connect, get and insert data (at least theoretically) in the database. Now, a little not about the SQL engine of choice here: SQLite. SQLite databases have the main characteristic that they are self-contained files. Also it does not require an installation, works without a server and works pretty well in [...]]]></description>
			<content:encoded><![CDATA[<p>We have seen how to connect, get and insert data (at least theoretically) in the database. Now, a little not about the SQL engine of choice here: SQLite. SQLite databases have the main characteristic that they are self-contained files. Also it does not require an installation, works without a server and works pretty well in most operating systems. </p>
<p>Basically for the type of application we&#8217;re developing here, SQLite seems ideal. It eliminates a lot of infrastructure that would be needed if we were working with MySQL or postgresql. We don&#8217;t need a server or know how to configure users or manage the databases and tables. All we need is contained in a single file that can be transported from system to system and can be accesed from the computers used in the lab, mainly XP and OS X. Also some web frameworks (Rails and <a class="zem_slink" href="http://www.djangoproject.com" title="Django (web framework)" rel="homepage">Django</a>, for instance) can use SQLite, so in the end we can have a desktop application and a web application accessing the same file without extra configuration.</p>
<p>Now the database created for this application has 8 tables and almost no relationships among them. SQLite allows the creation of relationships but in our case only a couple of cases were required. For the table we are using at the moment (bac) there is no need for relationships, although there are some fileds that can benefit from a more relational structure. Also SQLite don&#8217;t have the same data types that are found on the bigger SQL engines. All values can be stored as text, integer, real (floating point numbers), null and blob (verbose type, what you store is what you get). As actual types, you can set columns as Boolean and Data for instance and SQLite will understand them. If you have no experience in creating databases, let&#8217;s check again the table we are using in this small project. First, I would recommend the use of some SQLite database editor. You can find pretty good ones for any computer system and there is even a Firefox extension that allows you to edit some files. Editors make it easier to generate the SQL table creation scripts and make easier to visualize what we are doing.</p>
<p>So, the table bac looks like </p>
<pre name="code" class="sql">
CREATE TABLE bac
(idbac INTEGER PRIMARY KEY,
clone Text,
sdate Date,
source Text,
gene Text,
chromosome Text,
startpos Integer,
endpos Integer,
antibiotic Text,
location1 Text,
temperature Integer,
tubes Integer,
box Integer,
cell Integer,
dnaex Boolean,
validation Boolean,
pcr Boolean,
projects Text,
comments Text,
genelink Text,
refs Text);
</pre>
<p>If you go back to our last post, you will see that in the insert statement there is no mention of the <code>idbac</code> field. We don&#8217;t actually insert ay value there, the values that populate this field are created automatically. And <code>idbac</code> is our primary key, meaning it&#8217;s the unique identifier of each bac we insert in this table. And in SQLite a integer primary key is automatically incremented whenever values are inserted in the table. So our first insertion will create <code>idbac</code> 1, the second will create <code>idbac</code> 2 and so on. </p>
<p>I&#8217;m not going to enter in details about database development and administration, but it&#8217;s usual and safe to create tables with an auto-incremental integer primary keys. These fields, apart from make it easier t identify records, make access to such records faster and are great when relationships among tables are set. Let&#8217;s say that we had a column user in our bac table. And let&#8217;s say we had an user table with two columns: user_id and name, user_id being a auto-increment primary key. The user column in back could be linked with the user_id column in the user table, in what we call a one-to-many relationship (one user can insert as many bacs as he wants). One day we want to know who is actually working in the lab and we want to check how many bacs were catalogued by each user. We can easily search the user table and extract information from bacs at the same time thanks to the relationship between the tables. And the result should be returned quite quickly, as we are only searching integers.</p>
<p>All the other fields/columns in our table are straightforward to understand. They are basically related to the type of data they need to store. <code>validation</code> is a boolean because the bac might have been validated or not, just as <code>danex</code> (DNA extraction). At the same time, the number of tubes stored in the freezer will always be an integer. So, why does temperature is an integer? Because we can only store bacs in two type of freezers: -80 (ultra freezers) or -20 (regular freezer that we can have at home), and we don&#8217;t need to worry about fractional numbers. </p>
<p>Well, this is a very short and limited explanation of tables and SQLite. The web is full of resources about it, so next time we will get back to Python.</p>
<p>Previously in the series:<br />
<a href="http://python.genedrift.org/2009/02/09/managing-a-simple-database-with-python-sqlite-and-wxpython-1/">Part 1</a><br />
<a href="http://python.genedrift.org/2009/02/17/managing-a-simple-database-with-python-sqlite-and-wxpython-2/">Part 2</a><br />
<a href="http://python.genedrift.org/2009/02/18/managing-a-simple-database-with-python-sqlite-and-wxpython-3/">Part 3</a><br />
<a href="http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-4/">Part 4</a></p>
<div style="margin-top: 10px; height: 15px;" class="zemanta-pixie"><a class="zemanta-pixie-a" href="http://reblog.zemanta.com/zemified/4be1389f-5603-4b76-961b-b79d985066cc/" title="Zemified by Zemanta"><img style="border: medium none ; float: right;" class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_e.png?x-id=4be1389f-5603-4b76-961b-b79d985066cc" alt="Reblog this post [with Zemanta]"></a><span class="zem-script more-related"><script type="text/javascript" src="http://static.zemanta.com/readside/loader.js" defer="defer"></script></span></div>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2009/03/02/managing-a-simple-database-with-python-sqlite-and-wxpython-5/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, final</title>
		<link>http://python.genedrift.org/2008/11/19/creating-an-interface-for-the-motif-finding-script-final/</link>
		<comments>http://python.genedrift.org/2008/11/19/creating-an-interface-for-the-motif-finding-script-final/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 21:57:24 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/2008/11/19/creating-an-interface-for-the-motif-finding-script-final/</guid>
		<description><![CDATA[We can say that this would be our final version of the script. There are many nice wxPython programming resources, and one is a very good book called wxPython in Action, which is co-written by Robin Dunn, the wxPython maintainer. Go check it out. So for the last entry in this series, we just need [...]]]></description>
			<content:encoded><![CDATA[<p>We can say that this would be our final version of the script. There are many nice wxPython programming resources, and one is a very good book called <a href ="http://manning.com/rappin/">wxPython in Action</a>, which is co-written by Robin Dunn, the wxPython maintainer. Go check it out.</p>
<p>So for the last entry in this series, we just need to add a couple of changes to our interface and motif finding scripts. Basically on the interface script we need to add a line that gets the value entered (or the default one, if not changed) in the motif width input box. And we can do that by including the line below in the <code>run_finder</code> function.</p>
<pre name="code" class="python">
width = self.motif_width.GetValue()
</pre>
<p>This line tells the script to get the value of the box and assign to the variable width. This method will get whatever is inside the input box and save as a string to the variable assigned. Now, we need to create the structure to actually send this value to the motif finder functions. Last version of our function <code>calculate_motifs</code> received two parameters, we need to add an extra one, and also change the lines that call the function that get the quorums. Basically the first lines of the function will be</p>
<pre name="code" class="python">
def calculate_motifs(input_seqs, input_seqs2, width):

    print input_seqs, input_seqs2
    input_seqs = fasta.read_seqs(open(input_seqs).readlines())
    input_seqs2 = fasta.read_seqs(open(input_seqs2).readlines())

    foreground = get_quorums(input_seqs, width)
    background = get_quorums(input_seqs2, width)
</pre>
<p>And that&#8217;s it. Our simple interface is ready to primetime. OK, not prime primetime, we didn&#8217;t add a series of features that will make it useful by everyone. For instance, there is no error control, so someone could enter &#8216;ABC&#8217; in the width input box and that value would be sent and an error will occur. Also you can click the run button without any file selected. And we could go on and on. But this is just a primer, and we can build from it.</p>
<p>The code is on <a href="http://github.com/nuin/beginning-python-for-bioinformatics/tree/master/scripts%2Fmotifs">Github</a>, so get it there and have fun. Next time we will see &#8230; no plans yet. We&#8217;ll see &#8230; </p>
<p>Technorati Tags: <a class="performancingtags" href="http://technorati.com/tag/wxPython" rel="tag">wxPython</a>, <a class="performancingtags" href="http://technorati.com/tag/motifs" rel="tag">motifs</a>, <a class="performancingtags" href="http://technorati.com/tag/Python" rel="tag">Python</a>, <a class="performancingtags" href="http://technorati.com/tag/bioinformatics" rel="tag">bioinformatics</a></p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/11/19/creating-an-interface-for-the-motif-finding-script-final/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, some corrections</title>
		<link>http://python.genedrift.org/2008/11/18/creating-an-interface-for-the-motif-finding-script-some-corrections/</link>
		<comments>http://python.genedrift.org/2008/11/18/creating-an-interface-for-the-motif-finding-script-some-corrections/#comments</comments>
		<pubDate>Tue, 18 Nov 2008 19:45:31 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/2008/11/18/creating-an-interface-for-the-motif-finding-script-some-corrections/</guid>
		<description><![CDATA[We need to pause a bit and do some corrections on our code. First the code I posted on the last entry for the pymotif.py module is wrong. Ok, not wrong, but some of the code I use to test ended up on the blog. Ths first two lines of the calculate_motifs function contained a [...]]]></description>
			<content:encoded><![CDATA[<p>We need to pause a bit and do some corrections on our code. First the code I posted on the last entry for the pymotif.py module is wrong. Ok, not wrong, but some of the code I use to test ended up on the blog. Ths first two lines of the calculate_motifs function contained a link to the files I use for testing and should be replaced by</p>
<pre name="code" class="python">
input_seqs = fasta.read_seqs(open(input_seqs).readlines())
input_seqs2 = fasta.read_seqs(open(input_seqs2).readlines())
</pre>
<p>Also both variables that store the filenames and paths in pymoteGUI.py are declared in the wrong scope. The should have be declared at the pymotGUI class level, so it is accessible to all the functions in that class. This also means that every time we access the variable it should be preceded by the class name in order for the interpreter to know where the to get the value from. So both corrected files would be</p>
<pre name="code" class="python">
#!/usr/bin/env python

import wx
import pymot
import pymotif
import fasta
import os

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    fore_file = &#039;&#039;
    back_file = &#039;&#039;

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, &#039;Select foreground file&#039;)
        background_menu = filemenu.Append(-1, &#039;Select background file&#039;)
        sep = filemenu.AppendSeparator()
        quitmenu = filemenu.Append(-1, &#039;Quit&#039;)

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, &#039;File&#039;)
        self.SetMenuBar(menubar)

        #input box for motif width, and label
        self.one_label = wx.StaticText(panel, -1, &#039;Motif width&#039;, (10,50))
        self.motif_width = wx.TextCtrl(panel, -1, &#039;10&#039;, (95, 50), (40,18))
        #result textbox
        self.results = wx.TextCtrl(panel, -1, &#039;&#039;, (150, 50), (200, 100), wx.TE_MULTILINE | wx.TE_AUTO_SCROLL | wx.HSCROLL)

        #run bbutton
        self.run_button = wx.Button(panel, -1, &#039;Run&#039;, (10, 80))

        #labels
        self.fore_label = wx.StaticText(panel, -1, &#039;Select the foreground file&#039;, (10, 10))
        self.back_label = wx.StaticText(panel, -1, &#039;Select the background file&#039;, (10, 30))

        #binding the menus to functions
        self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
        self.Bind(wx.EVT_MENU, self.on_background, background_menu)
        self.Bind(wx.EVT_BUTTON, self.run_finder, self.run_button)

    def on_foreground(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            pymotGUI.fore_file = dialog.GetPath()
            self.fore_label.SetLabel(pymotGUI.fore_file)

    def on_background(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            pymotGUI.back_file = dialog.GetPath()
            self.back_label.SetLabel(pymotGUI.back_file)

    def run_finder(self, event):
        print pymotGUI.fore_file
        result = pymotif.calculate_motifs(pymotGUI.fore_file, pymotGUI.back_file)
        for motif in result:
            self.results.WriteText(motif + &#039;n&#039;)
        #wx.MessageBox(&#039;It should run, eh?&#039;)

#if __name__ == &#039;__main__&#039;:
app = pymot()
frame = pymotGUI(parent=None, id = -1)
#frame.CentreOnScreen()
frame.Show()
app.MainLoop()
</pre>
<p>and </p>
<pre name="code" class="python">
#!/usr/bin/env python

import fasta
import sys
from collections import defaultdict

def choose(n, k):
    if 0 &lt;= k &lt;= n:
        ntok = 1
        ktok = 1
        for t in xrange(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0

def get_quorums(seqs, mlen):
    &quot;&quot;&quot;
    add seq id_no to a set
    use explicit counter to create seq_no
    &quot;&quot;&quot;
    quorum = defaultdict(int)
    for seq in seqs:
        for n in range(len(seq) - mlen):
            quorum[seq[n:n + mlen]] += 1
    return quorum

def calculate_motifs(input_seqs, input_seqs2):

    print input_seqs, input_seqs2
    input_seqs = fasta.read_seqs(open(input_seqs).readlines())
    input_seqs2 = fasta.read_seqs(open(input_seqs2).readlines())

    foreground = get_quorums(input_seqs, 10)
    background = get_quorums(input_seqs2, 10)

    N = len(input_seqs) + len(input_seqs2)

    res_motifs = []
    for i in foreground:
        term1 = choose(background[i], foreground[i])
        term2 = choose((N - background[i]), len(input_seqs) - 1)
        term3 = choose(N, len(input_seqs))
        p = (float(term1) * float(term2)) / term3
        if 0 &lt; p &lt;= 0.0001:
            res_motifs.append(i + &#039;t&#039; + str(foreground[i]) + &#039;t&#039; + str(background[i]) + &#039;t&#039; + str(p))

    res_motifs.sort()
    return res_motifs
</pre>
<p>On the next post, the last in the series, we will just check how to get the value from the width input box and wrap-up everything.</p>
<p>Technorati Tags: <a class="performancingtags" href="http://technorati.com/tag/wxPython" rel="tag">wxPython</a>, <a class="performancingtags" href="http://technorati.com/tag/python" rel="tag">python</a>, <a class="performancingtags" href="http://technorati.com/tag/motifs" rel="tag">motifs</a>, <a class="performancingtags" href="http://technorati.com/tag/GUI" rel="tag">GUI</a></p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/11/18/creating-an-interface-for-the-motif-finding-script-some-corrections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 8</title>
		<link>http://python.genedrift.org/2008/11/13/creating-an-interface-for-the-motif-finding-script-part-8/</link>
		<comments>http://python.genedrift.org/2008/11/13/creating-an-interface-for-the-motif-finding-script-part-8/#comments</comments>
		<pubDate>Thu, 13 Nov 2008 22:28:35 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/2008/11/13/creating-an-interface-for-the-motif-finding-script-part-8/</guid>
		<description><![CDATA[Let&#8217;s see now how do we connect our GUI to the the pymotif file (I changed the name because of some conflicts with the app name [my bad!], the git repo was updated accordingly). And also how to display the results, in a simpler manner. Ok, first to connecting the script to the function file, [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s see now how do we connect our GUI to the the pymotif file (I changed the name because of some conflicts with the app name [my bad!], the git repo was updated accordingly). And also how to display the results, in a simpler manner. </p>
<p>Ok, first to connecting the script to the function file, pymotif.py. The file is already imported in our script and we have used it before. We need to find the exact point and which parameters to pass. pytmotif.py is a slightly modified version of your command line script, and the code is below.</p>
<pre name="code" class="python">
#!/usr/bin/env python

import fasta
import sys
from collections import defaultdict

def choose(n, k):
    if 0 &lt;= k &lt;= n:
        ntok = 1
        ktok = 1
        for t in xrange(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0

def get_quorums(seqs, mlen):
    &quot;&quot;&quot;
    add seq id_no to a set
    use explicit counter to create seq_no
    &quot;&quot;&quot;
    quorum = defaultdict(int)
    for seq in seqs:
        for n in range(len(seq) - mlen):
            quorum[seq[n:n + mlen]] += 1
    return quorum

def calculate_motifs(input_seqs, input_seqs2):

    input_seqs = fasta.read_seqs(open(&#039;celladhesion1000.fa&#039;).readlines())
    input_seqs2 = fasta.read_seqs(open(&#039;celladhesion1000C.fa&#039;).readlines())

    foreground = get_quorums(input_seqs, 10)
    background = get_quorums(input_seqs2, 10)

    N = len(input_seqs) + len(input_seqs2)

    res_motifs = []
    for i in foreground:
        term1 = choose(background[i], foreground[i])
        term2 = choose((N - background[i]), len(input_seqs) - 1)
        term3 = choose(N, len(input_seqs))
        p = (float(term1) * float(term2)) / term3
        if 0 &lt; p &lt;= 0.0001:
            res_motifs.append(i + &#039;t&#039; + str(foreground[i]) + &#039;t&#039; + str(background[i]) + &#039;t&#039; + str(p))

    res_motifs.sort()
    return res_motifs
</pre>
<p>So, basically the line we are interested is this one</p>
<pre name="code" class="python">
def calculate_motifs(input_seqs, input_seqs2):
</pre>
<p>We replace the wx.MessageBox line in our run_finder function and use the input files selected by the user as parameters for calculate_motifs, and we are done</p>
<pre name="code" class="python">
def run_finder(self, event):
	result = pymotif.calculate_motifs(self.fore_file, self.back_file)
</pre>
<p>Very simple and direct. This should take care of everything except the motif width, what we will see in the next post. We still need a place to write the overrepresented motifs. We can add a text box to the frame, and we do that by adding an extra declaration in our __do_layout function. This time we need to add some extra style to the box, so it can show multiple lines and has a scroll bar.</p>
<pre name="code" class="python">
self.results = wx.TextCtrl(panel, -1, &#039;&#039;, (150, 50), (200, 100), wx.TE_MULTILINE | wx.TE_AUTO_SCROLL | wx.HSCROLL)
</pre>
<p>Notice the wx. flags added. MULTILINE allows the box to have multiple lines and the other two turn on the auto scroll and horizontal scroll. Great. And how do we write the results. Notice above that the function that calculates the motifs, returns a list where each item has the motif sequence and the p value, sorted. So the only thing we need to do is to iterate over the list and print each line to the result box. That simple, and we accomplish it by using the WriteText method, that receives as a parameter a string, either literal or a string object. Our run_finder function will have a couple of extra lines</p>
<pre name="code" class="python">
def run_finder(self, event):
	result = pymotif.calculate_motifs(self.fore_file, self.back_file)
	for motif in result:
		self.results.WriteText(motif + &#039;n&#039;)
</pre>
<p>That will present in a very simplistic way the resulting overrepresented motifs, but it&#8217;s enough for now. Our GUI script will be</p>
<pre name="code" class="python">
#!/usr/bin/env python

import wx
import pymot
import pymotif
import fasta
import os

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()
        self.fore_file = &#039;&#039;
        self.back_file = &#039;&#039;

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, &#039;Select foreground file&#039;)
        background_menu = filemenu.Append(-1, &#039;Select background file&#039;)
        sep = filemenu.AppendSeparator()
        quitmenu = filemenu.Append(-1, &#039;Quit&#039;)

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, &#039;File&#039;)
        self.SetMenuBar(menubar)

        #input box for motif width, and label
        self.one_label = wx.StaticText(panel, -1, &#039;Motif width&#039;, (10,50))
        self.motif_width = wx.TextCtrl(panel, -1, &#039;10&#039;, (95, 50), (40,18))
        #result textbox
        self.results = wx.TextCtrl(panel, -1, &#039;&#039;, (150, 50), (200, 100), wx.TE_MULTILINE | wx.TE_AUTO_SCROLL | wx.HSCROLL)

        #run bbutton
        self.run_button = wx.Button(panel, -1, &#039;Run&#039;, (10, 80))

        #labels
        self.fore_label = wx.StaticText(panel, -1, &#039;Select the foreground file&#039;, (10, 10))
        self.back_label = wx.StaticText(panel, -1, &#039;Select the background file&#039;, (10, 30))

        #binding the menus to functions
        self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
        self.Bind(wx.EVT_MENU, self.on_background, background_menu)
        self.Bind(wx.EVT_BUTTON, self.run_finder, self.run_button)

    def on_foreground(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            fore_file = dialog.GetPath()
            self.fore_label.SetLabel(fore_file)

    def on_background(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            back_file = dialog.GetPath()
            self.back_label.SetLabel(back_file)

    def run_finder(self, event):
        result = pymotif.calculate_motifs(self.fore_file, self.back_file)
        for motif in result:
            self.results.WriteText(motif + &#039;n&#039;)
        #wx.MessageBox(&#039;It should run, eh?&#039;)

#if __name__ == &#039;__main__&#039;:
app = pymot()
frame = pymotGUI(parent=None, id = -1)
#frame.CentreOnScreen()
frame.Show()
app.MainLoop()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/11/13/creating-an-interface-for-the-motif-finding-script-part-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 7</title>
		<link>http://python.genedrift.org/2008/11/11/creating-an-interface-for-the-motif-finding-script-part-7/</link>
		<comments>http://python.genedrift.org/2008/11/11/creating-an-interface-for-the-motif-finding-script-part-7/#comments</comments>
		<pubDate>Tue, 11 Nov 2008 18:53:09 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[GUI]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/2008/11/11/creating-an-interface-for-the-motif-finding-script-part-7/</guid>
		<description><![CDATA[Let&#8217;s get back to the last post and check one line we entered self.motif_width = wx.TextCtrl(panel, -1, &#039;10&#039;, (95, 50), (40,18)) There is something in this line that I did not explain. The third parameter in the test box declaration is '10'. How does this affect our box? That&#8217;s the default text that will be [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s get back to the last post and check one line we entered</p>
<pre name="code" class="python">
self.motif_width = wx.TextCtrl(panel, -1, &#039;10&#039;, (95, 50), (40,18))
</pre>
<p>There is something in this line that I did not explain. The third parameter in the test box declaration is <code>'10'</code>. How does this affect our box? That&#8217;s the default text that will be displayed inside the box as soon as it is created. In our case, 10 is the motif width, and it&#8217;s the value we consider to be the most common search width.</p>
<p>Another aspect not explained is the <code>run_finder</code>. We added a line </p>
<pre name="code" class="python">
wx.MessageBox(&#039;It should run, eh?&#039;)
</pre>
<p>where we declare a wx.MessageBox. What is it? A message box is the usual error/information dialog that you see in most programs. In our case it is very simple, just a warning/reminder that we need to include some code there.</p>
<p>Next time we will connect some Python source files and make our script find some motifs.</p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/11/11/creating-an-interface-for-the-motif-finding-script-part-7/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 6</title>
		<link>http://python.genedrift.org/2008/11/04/creating-an-interface-for-the-motif-finding-script-part-6/</link>
		<comments>http://python.genedrift.org/2008/11/04/creating-an-interface-for-the-motif-finding-script-part-6/#comments</comments>
		<pubDate>Tue, 04 Nov 2008 22:39:01 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=193</guid>
		<description><![CDATA[Last entry we saw how to allow the user to open a file. Now we need to work on this file and store its path so the script can process it later on. After the file is selected on the file menu, the filename is printed on the label. Let&#8217;s think for a second &#8230; [...]]]></description>
			<content:encoded><![CDATA[<p>Last entry we saw how to allow the user to open a file. Now we need to work on this file and store its path so the script can process it later on. After the file is selected on the file menu, the filename is printed on the label. Let&#8217;s think for a second &#8230; If we get only the filename from the dialog, the program won&#8217;t work, because the file might be located in another directory, partition, you name it. So we need tp get the file&#8217;s full path. We need to change the lines</p>
<pre name="code" class="python">
back_file = dialog.GetFilename()
self.fore_label.SetLabel(dialog.GetFilename())
</pre>
<p>by </p>
<pre name="code" class="python">
back_file = dialog.GetPath()
self.fore_label.SetLabel(back_file)
</pre>
<p>(do not forget to do the same to the fore_file!).</p>
<p>Let&#8217;s run the script and check what happens. The frame should look like the one below (with a little stretching for me).<br />
<a href="http://python.genedrift.org/wordpress/wp-content/uploads/2008/11/gui4.png"><img src="http://python.genedrift.org/wordpress/wp-content/uploads/2008/11/gui4.png" alt="new gui" title="new gui" width="535" height="264" class="alignnone size-full wp-image-194" /></a></p>
<p>OK, so this is part is solved. As we haven&#8217;t planned our application from the start, we will spend sometime thinking of the basic functionality that we migth need. So far, we need one input box, where the user can enter the motif width to be searched, and a button to start the process. Fine, let&#8217;s add the input box. For this we also need an extra label to tell the user what the box is for. Always working on our __do_layout function we add two lines</p>
<pre name="code" class="python">
self.one_label = wx.StaticText(panel, -1, &#039;Motif width&#039;, (10,50))
self.motif_width = wx.TextCtrl(panel, -1, &#039;10&#039;, (95, 50), (40,18))
</pre>
<p>Simple as that we have a input box. For the button, one line will suffice</p>
<pre name="code" class="python">
self.run_button = wx.Button(panel, -1, &#039;Run&#039;, (10, 80))
</pre>
<p>As we can see there is not much difference in any of the declarations, they follow a similar process and the parameters are more or less identical in some of them. Now, we need to bind the button to a function, that we will call <code>run_finder</code>. Remember that binding needs an event type, a target function and an object. This time the event is a button event, but the other two parameters are similar.</p>
<pre name="code" class="python">
self.Bind(wx.EVT_BUTTON, self.run_finder, self.run_button)
</pre>
<p>and the function, for now will look like</p>
<pre name="code" class="python">
def run_finder(self, event):
    wx.MessageBox(&#039;It should run, eh?&#039;)
</pre>
<p>That&#8217;s all for today. Our script is growing and the full code is below</p>
<pre name="code" class="python">
#!/usr/bin/env python

import wx
import pymot
import fasta
import os

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()
        self.fore_file = &#039;&#039;
        self.back_file = &#039;&#039;

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, &#039;Select foreground file&#039;)
        background_menu = filemenu.Append(-1, &#039;Select background file&#039;)
        sep = filemenu.AppendSeparator()
        quitmenu = filemenu.Append(-1, &#039;Quit&#039;)

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, &#039;File&#039;)
        self.SetMenuBar(menubar)

        #input box for motif width, and label
        self.one_label = wx.StaticText(panel, -1, &#039;Motif width&#039;, (10,50))
        self.motif_width = wx.TextCtrl(panel, -1, &#039;10&#039;, (95, 50), (40,18))

        #run bbutton
        self.run_button = wx.Button(panel, -1, &#039;Run&#039;, (10, 80))

        #labels
        self.fore_label = wx.StaticText(panel, -1, &#039;Select the foreground file&#039;, (10, 10))
        self.back_label = wx.StaticText(panel, -1, &#039;Select the background file&#039;, (10, 30))

        #binding the menus to functions
        self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
        self.Bind(wx.EVT_MENU, self.on_background, background_menu)
        self.Bind(wx.EVT_BUTTON, self.run_finder, self.run_button)

    def on_foreground(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            fore_file = dialog.GetPath()
            self.fore_label.SetLabel(fore_file)

    def on_background(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            back_file = dialog.GetPath()
            self.back_label.SetLabel(back_file)

    def run_finder(self, event):
        wx.MessageBox(&#039;It should run, eh?&#039;)

#if __name__ == &#039;__main__&#039;:
app = pymot()
frame = pymotGUI(parent=None, id = -1)
#frame.CentreOnScreen()
frame.Show()
app.MainLoop()
</pre>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/11/04/creating-an-interface-for-the-motif-finding-script-part-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 5</title>
		<link>http://python.genedrift.org/2008/10/30/creating-an-interface-for-the-motif-finding-script-part-5/</link>
		<comments>http://python.genedrift.org/2008/10/30/creating-an-interface-for-the-motif-finding-script-part-5/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 19:45:19 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=186</guid>
		<description><![CDATA[Last time we saw how to bind an interface element to a function. Now we need to make good use of it, and make the script have some actual functionality. First thing we are going to do is to include a label (or static text) on the interface. Remember that initially we added a panel [...]]]></description>
			<content:encoded><![CDATA[<p>Last time we saw how to bind an interface element to a function. Now we need to make good use of it, and make the script have some actual functionality. First thing we are going to do is to include a label (or static text) on the interface. Remember that initially we added a panel to the frame, so the label should go on the panel. For a label we use a <a href="http://wxpython.org/docs/api/wx.StaticText-class.htm">wx.StaticText</a> and has these parameters</p>
<pre name="code" class="python">
(self, parent, id=-1, label=EmptyString, pos=DefaultPosition, size=DefaultSize, style=0, name=StaticTextNameStr)
</pre>
<p>We don&#8217;t need all of them, just a couple would be enough. Basically, parent, id, label and pos will do it, as the size would be default and based on the text length we input. We are going to work on our __do_layout function and add two labels to the panel on the frame, one for each the fore and background files</p>
<pre name="code" class="python">
self.fore_label = wx.StaticText(panel, -1, &#039;Select the foreground file&#039;, (10, 10))
self.back_label = wx.StaticText(panel, -1, &#039;Select the background file&#039;, (10, 30))
</pre>
<p>These two lines are very similar, only the label, position and name change. </code>panel</code> is the name of the panel we created previously, -1 is the ID, the string is the actual text that will appear on the label and the values between parentheses are the X, Y coordinates to display them on the frame. In the beginning (or when a size needs to be set) we can add <code>pos=</code> to the label declaration in order to make clearer what the values are setting</p>
<pre name="code" class="python">
self.fore_label = wx.StaticText(panel, -1, &#039;Select the foreground file&#039;, pos=(10, 10))
</pre>
<p>If we add these two lines and run our script, both labels will be there on the frame, as can be seen in the screencap below.</p>
<p><a href="http://python.genedrift.org/wordpress/wp-content/uploads/2008/10/gui3.png"><img src="http://python.genedrift.org/wordpress/wp-content/uploads/2008/10/gui3-300x187.png" alt="GUI with labels" title="GUI with labels" width="300" height="187" class="aligncenter size-medium wp-image-187" /></a></p>
<p>Now, we need to add some functionality to the menus. The menu items set previously, basically should work by presenting a file open dialog to the user, where he/she can select a file that will be processed later (or immediately). wxPython provides an option of automatically creating a file dialog, by using the <a href="http://wxpython.org/docs/api/wx.FileDialog-class.html">wx.FileDialog method</a>. This method requires only one parameter, which is the style of the dialog. The dialog can be of many types, i.e. for opening (single and multiple files) and saving. the dialog call would look like</p>
<pre name="code" class="python">
dialog = wx.FileDialog(self, style=wx.OPEN)
</pre>
<p>very simple and objective. But just declaring won't make it show up on the screen. We need to actually call the dialog's show method. Usually, most dialogs are <a href="http://en.wikipedia.org/wiki/Modal_window">modal</a>, requiring some kind of interaction between the user and the dialog before returning to the application that called the dialog. Because of this behaviour we need to use an if clause when showing the dialog, to check what type of result returns from the user/dialog interaction. </p>
<pre name="code" class="python">
if dialog.ShowModal() == wx.ID_OK:
</pre>
<p>wx.ID_OK is a internal method of wxPython that checks if the user pressed the OK button on the file open dialog. If so, the program will process the code, otherwise it will destroy the dialog and return to the main application (or do something else if we set an elif clause). So, all we need is set, we just need to put things together and add some code when the user selects a file</p>
<pre name="code" class="python">
def on_foreground(self, event):
    dialog = wx.FileDialog(self, style=wx.OPEN)
    if dialog.ShowModal() == wx.ID_OK:
        fore_file = dialog.GetFilename()
        self.fore_label.SetLabel(forefile)
</pre>
<p>After the if clause, the script will get the name of the selected file from the dialog and then set the label of our StaticText (label!) with it. Straightforward. We do the same thing for the background file and we have some code going. One last thing, the objects <code>fore_file</code> and <code>back_file</code> are declared on the __init__ function of the frame class, so they are available to the whole frame scope. Our script will look like</p>
<pre name="code" class="python">
#!/usr/bin/env python

import wx
import pymot
import fasta
import os

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()
        self.fore_file = &#039;&#039;
        self.back_file = &#039;&#039;

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, &#039;Select foreground file&#039;)
        background_menu = filemenu.Append(-1, &#039;Select background file&#039;)
        sep = filemenu.AppendSeparator()
        quitmenu = filemenu.Append(-1, &#039;Quit&#039;)

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, &#039;File&#039;)
        self.SetMenuBar(menubar)

        self.fore_label = wx.StaticText(panel, -1, &#039;Select the foreground file&#039;, (10, 10))
        self.back_label = wx.StaticText(panel, -1, &#039;Select the background file&#039;, (10, 30))

        self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
        self.Bind(wx.EVT_MENU, self.on_background, background_menu)

    def on_foreground(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            fore_file = dialog.GetFilename()
            self.fore_label.SetLabel(dialog.GetFilename())

    def on_background(self, event):
        dialog = wx.FileDialog(self, style=wx.OPEN)
        if dialog.ShowModal() == wx.ID_OK:
            back_file = dialog.GetFilename()
            self.back_label.SetLabel(dialog.GetFilename())

#if __name__ == &#039;__main__&#039;:
app = pymot()
frame = pymotGUI(parent=None, id = -1)
#frame.CentreOnScreen()
frame.Show()
app.MainLoop()
</pre>
<p>Next we will keep adding elements on the screen and functionality.</p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/10/30/creating-an-interface-for-the-motif-finding-script-part-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 4</title>
		<link>http://python.genedrift.org/2008/10/29/creating-an-interface-for-the-motif-finding-script-part-4/</link>
		<comments>http://python.genedrift.org/2008/10/29/creating-an-interface-for-the-motif-finding-script-part-4/#comments</comments>
		<pubDate>Wed, 29 Oct 2008 18:35:27 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=183</guid>
		<description><![CDATA[Last time we checked how to add a menu to our simple frame. Unfortunately, just adding it won&#8217;t make the menu useful. In order to do that we need to bind some events to it. As any interface framework, wxPython is governed by events generated by the user, being these events mouse clicks on buttons [...]]]></description>
			<content:encoded><![CDATA[<p>Last time we checked how to add a menu to our simple frame. Unfortunately, just adding it won&#8217;t make the menu useful. In order to do that we need to bind some events to it. As any interface framework, wxPython is governed by events generated by the user, being these events mouse clicks on buttons and menus, objects getting/losing focus, etc. In our case, so far, we evidently need a event called menu event, which will tell the code what path to use when a menu is clicked. </p>
<p>My personal preference for binding an event to menu is to create a separate function to store these procedures, <code>__do_binding</code>. But by using this route we would need to change some code in the menu declaration, and to simplify things we will add the menu binding at the end of the <code>__do_layout</code> function.</p>
<p>And how we create a binding? In order to bind an object/menu to a function that will contain the executed code after the event is fired up, we need the name of the object/menu, the target function and the menu type. We already know the first and the last, we just need the function name then. Remember that we created the menu last time by using (the menu name were changed in the previous entry &#8211; it was some old code that got in the way &#8211; my mistake)</p>
<pre name="code" class="python">
foreground_menu = filemenu.Append(-1, &#039;Select foreground file&#039;)
background_menu = filemenu.Append(-1, &#039;Select background file&#039;)
...
quitmenu = filemenu.Append(-1, &#039;Quit&#039;)
</pre>
<p>hence our menu names are <code>foreground_menu</code>, <code>background_menu</code> and <code>quit_menu</code>. Basically a wx.Bind method has this structure</p>
<pre name="code" class="python">
self.Bind(EVENT_TYPE, handler, source)
</pre>
<p>where the handler is the function and the source is the actual source of the event. Let&#8217;s say then we want to use function <code>on_foreground</code> everytime someone clicks on foreground menu, and <code>on_background</code> everytime someone clicks on the background menu. We add a couple of lines to our layout function</p>
<pre name="code" class="python">
self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
self.Bind(wx.EVT_MENU, self.on_background, background_menu)
</pre>
<p>This will tell the code where to go when these items are clicked. If you start the interface, and error will be generated because we still haven&#8217;t created the event handler functions. We should define them</p>
<pre name="code" class="python">
def on_foreground(self, event):
    pass

def on_background(self, event):
    pass
</pre>
<p>Note that these function receive an <code>event</code> parameter, which is the actual event itself. The <code>pass</code> line means that the function is defined but no actual code has been added, so execution can bypass it and do nothing when the function is called. Our complete code would look like </p>
<pre name="code" class="python">
#!/usr/bin/env python

import wx
import pymot
import fasta

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, &#039;Select foreground file&#039;)
        background_menu = filemenu.Append(-1, &#039;Select background file&#039;)
        sep = filemenu.AppendSeparator()
        quitmenu = filemenu.Append(-1, &#039;Quit&#039;)

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, &#039;File&#039;)
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.on_foreground, foreground_menu)
        self.Bind(wx.EVT_MENU, self.on_background, background_menu)

    def on_foreground(self, event):
        pass

    def on_background(self, event):
        pass

app = pymot()
frame = pymotGUI(parent=None, id = -1)
frame.Show()
app.MainLoop()
</pre>
<p>Next time we will make good use of the events.</p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/10/29/creating-an-interface-for-the-motif-finding-script-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 3</title>
		<link>http://python.genedrift.org/2008/10/22/creating-an-interface-for-the-motif-finding-script-part-3/</link>
		<comments>http://python.genedrift.org/2008/10/22/creating-an-interface-for-the-motif-finding-script-part-3/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 20:30:13 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[Section 2]]></category>
		<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=178</guid>
		<description><![CDATA[Today we will add some elements to our interface. Looking at the previous screencap it is easy to conclude that our interface needs a lot of work to be ready. First, it has a dark gray background that does not resemble the usual window background (it looks more like a MDI frame). We need to [...]]]></description>
			<content:encoded><![CDATA[<p>Today we will add some elements to our interface. Looking at the previous screencap it is easy to conclude that our interface needs a lot of work to be ready. First, it has a dark gray background that does not resemble the usual window background (it looks more like a MDI frame). We need to change that. Also, there are no menu bars or menus, or tool bars. It&#8217;s pretty bare bones, and not exactly good or useful.</p>
<p>There many ways of customizing the look of a window/frame in wxPython, and two of these methods are adding a panel to the frame or adding the so-called sizers. The latter is a difficult method to master, but powerful and very good to customize objects, look and feels of a window. Addin a panel and subsequently adding objects to it is a more laborious process, but easier to understand. We will start by adding the <a href="http://www.wxpython.org/docs/api/wx.Panel-class.html">panel</a> to you <code>__do_layout</code> function (where most of our changes will happen for now).</p>
<p>Basically, only one line is required:</p>
<pre name="code" class="python">
#adding the panel
panel = wx.Panel(self)
</pre>
<p>That&#8217;s it, the wx.Panel method only needs one parameter, where the panel is being added to. The name <code>panel</code> is the one that we will be using to access methods and properties associated with the wx.Panel derivation that we just created.</p>
<p>Adding the menu would require a little bit more code. As its predecessor wxWidgets, wxPython divides the menu in subcategories. The menubar is based on wx.Menubar method, the menu itself (File, Edit, etc) is a wx.Menu wehre each of the entries is added. At the end each menu derived from wx.Menu will be added to the menubar. In order case we have to initialize a menubar</p>
<pre name="code" class="python">
#defines the menubar
menubar = wx.MenuBar()
</pre>
<p>and then initialize a menu element, which we will call filemenu and will be labeled File</p>
<pre name="code" class="python">
#file menu
filemenu = wx.Menu()
</pre>
<p>This will only initialize a menu element with the name <code>filemenu</code>, it won&#8217;t add anything anywhere. In our case from the start, as we didn&#8217;t do any planning on how our interface would look like (no UML, no case studies, nothing!), we need at least three menu items: one to open/set the foreground sequence file, one to open/set the background sequence file and one to quit the application. So what we are going to do is append these items to the <code>filemenu</code></p>
<pre name="code" class="python">
convertmenu = filemenu.Append(-1, &#039;Select foreground file&#039;)
seqmenu = filemenu.Append(-1, &#039;Select background file&#039;)
sep = filemenu.AppendSeparator()
treenooutmenu = filemenu.Append(-1, &#039;Quit&#039;)
</pre>
<p>that simple. The first two lines and the last one append the items that open/set files. The -1 parameter is an ID, as we saw previously, when no ID is required for our code we use -1, and the second parameter is the label of that menu item. The menu item <code>sep</code> is a separator, keeping apart the file open/set items and the quit element. One final thing is append the derived wx.Menu to the menubar and set it. We accomplish that by </p>
<pre name="code" class="python">
#appends the menu to the menubar and creates it
menubar.Append(filemenu, &#039;File&#039;)
self.SetMenuBar(menubar)
</pre>
<p>Line 2 initializes menubar on self, also known as pymotGUI, our main window. Putting everything together our code would look like</p>
<pre name="code" class="python">
#!/usr/bin/env python

import wx
import pymot
import fasta

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):

        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()
#        self.__do_binding()

    def __do_layout(self):

        #adding the panel
        panel = wx.Panel(self)

        #defines the menubar
        menubar = wx.MenuBar()

        #file menu
        filemenu = wx.Menu()
        foreground_menu = filemenu.Append(-1, &#039;Select foreground file&#039;)
        background_menu = filemenu.Append(-1, &#039;Select background file&#039;)
        sep = filemenu.AppendSeparator()
        quit_menu = filemenu.Append(-1, &#039;Quit&#039;)

        #appends the menu to the menubar and creates it
        menubar.Append(filemenu, &#039;File&#039;)
        self.SetMenuBar(menubar)

#if __name__ == &#039;__main__&#039;:
app = pymot()
frame = pymotGUI(parent=None, id = -1)
#frame.CentreOnScreen()
frame.Show()
app.MainLoop()
</pre>
<p>and this would look like the screencap below (on Vista).</p>
<p><a href="http://python.genedrift.org/wordpress/wp-content/uploads/2008/10/gui2.png"><img src="http://python.genedrift.org/wordpress/wp-content/uploads/2008/10/gui2-150x150.png" alt="gui2" title="gui2" width="150" height="150" class="aligncenter size-thumbnail wp-image-179" /></a></p>
<p>Next time we will work on more elements and activate the menu items.</p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/10/22/creating-an-interface-for-the-motif-finding-script-part-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 2</title>
		<link>http://python.genedrift.org/2008/10/21/creating-an-interface-for-the-motif-finding-script-part-2/</link>
		<comments>http://python.genedrift.org/2008/10/21/creating-an-interface-for-the-motif-finding-script-part-2/#comments</comments>
		<pubDate>Tue, 21 Oct 2008 16:40:33 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[interface]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=176</guid>
		<description><![CDATA[Let&#8217;s take a deeper look on the code we started yesterday, piece by piece class pymot(wx.App): def __init__(self, redirect=False): wx.App.__init__(self, redirect, filename) This is the class pymot we derived from wx.App, and this will be the main class for your application. As any other class derived it needs a OnInit or a __init__ function that [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s take a deeper look on the code we started yesterday, piece by piece</p>
<pre name="code" class="python">
class pymot(wx.App):
    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect, filename)
</pre>
<p>This is the class <code>pymot</code> we derived from wx.App, and this will be the main class for your application. As any other class derived it needs a OnInit or a __init__ function that will take care of initializing things. As usual, we pass <code>self</code> and a <code>redirect</code> parameter, that will tell the application to redirect some output to the command line. We actually don&#8217;t need a <code>redirect</code>, but it can be useful in the future to track errors. It&#8217;s set to false as we don&#8217;t need it now.</p>
<pre name="code" class="python">
class pymotGUI(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()

    def __do_layout(self):
        pass
</pre>
<p>This is the pymotGUI class derived, in this case, from wx.Frame. a wx.Frame is the common window you see in most OS. As above, it needs a OnInit or __init__ function, and here it initializes the window (but does not show it). In the first line of __init__ we have a call to format the window we want to display. The frame method would need these <a href="http://www.wxpython.org/docs/api/wx.Frame-class.html">paramaters</a> to customize the window</p>
<pre name="code" class="python">
__init__(self, parent, id, title, pos, size, style, name)
</pre>
<p>Both title and style are set by default (not that they cannot be changed) in the frame definition, and whe this is called and properly initialized, other parameters can be passed and/or changed. There is a second defined function in the <code>pymotGUI</code> class, <code>__do_layout</code>. This is a personal preference of having all the layout methods for the window grouped in one function. It helps organizing a bit the code and easier to browse and correct it if needed.</p>
<p>Most of the main part of the script could be moved to the wx.App class derivation, but for now, we can keep it there.</p>
<pre name="code" class="python">
app = pymot()
frame = pymotGUI(parent=None, id = -1)
frame.Show()
app.MainLoop()
</pre>
<p>The first line initializes the application, the second calls and initializes the frame. The method Show makes the window to be displayed. MainLoop we saw last time. </p>
<p>The skeleton of a wxPython script and application is very simple. Now we need to populate our window, create menus, buttons, and specially events. Next time we will include a menu on the form and check how events are linked to elements.</p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/10/21/creating-an-interface-for-the-motif-finding-script-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating an interface for the motif finding script, part 1</title>
		<link>http://python.genedrift.org/2008/10/20/creating-an-interface-for-the-motif-finding-script/</link>
		<comments>http://python.genedrift.org/2008/10/20/creating-an-interface-for-the-motif-finding-script/#comments</comments>
		<pubDate>Mon, 20 Oct 2008 21:31:50 +0000</pubDate>
		<dc:creator>Paulo Nuin</dc:creator>
				<category><![CDATA[motifs]]></category>
		<category><![CDATA[wxPython]]></category>
		<category><![CDATA[bioinformatics]]></category>
		<category><![CDATA[interface]]></category>

		<guid isPermaLink="false">http://python.genedrift.org/?p=171</guid>
		<description><![CDATA[And we are back. After much ado about real life, I am able to &#8220;restart&#8221; this blog and probably with a good frequency of posts. Last time we saw the final product of our motif finding series. We ended up creating a very elegant script in Python that efficiently counts words in FASTA sequences and [...]]]></description>
			<content:encoded><![CDATA[<p>And we are back. After much ado about real life, I am able to &#8220;restart&#8221; this blog and probably with a good frequency of posts. Last time we saw the final product of our motif finding series. We ended up creating a very elegant script in Python that efficiently counts words in FASTA sequences and then using a basic statistical method, calculates the significance of each word and output the overrepresented ones.</p>
<p>Our script used a little bit less than 50 lines, and if you include the imported fasta module, it won&#8217;t top 100. But the number of lines is not important. The efficiency, clarity and speed are key here. At the same time, running a script from the command line is not something everyone is used to do. In order to add more visibility to our simple script, why not including a GUI? With a visual interface, more people can use our script, in different systems. Sounds great.</p>
<p>Python has many options of GUI frameworks, some more cross-platform that others. In the end finding the right framework is more a matter of taste, or availability. My personal experience with <a href="http://www.wxwidgets.org">wxWidgets</a> lead me to start developing in <a href="http://www.wxpython.org">wxPython</a>, and for me this was a natural choice. But there are many other GUI frameworks for Python, each one providing more or less integration and portability (you can &#8220;choose&#8221; you own <a href="http://www.awaretek.com/toolkits.html">here</a>).</p>
<p>So, let&#8217;s create a skeleton for our GUI. First step is to install wxPython. Packages for Windows are available from their website, RPMs for Linux and DMG for Macs (I&#8217;m quite sure OS X Leopard comes with wxPython by default, just test importing it). After installing it, start Python and check if everything is in place</p>
<pre name="code" class="python">
import wx
wx.__version__
</pre>
<p>On my machine, I get no errors and the version is 2.8.9.1 (you don&#8217;t need the latest version to create the GUI). Everything seems to be fine. A wxPython script has the same format as any Python script, the only difference is that its output is not directed to the prompt or a file. The script&#8217;s product will be the screen, so in most cases the output and program usage will depend on the user&#8217;s interaction with objects on the screen. Like any other graphical interface. A very simple script would look like</p>
<pre name="code" class="python">
#!/usr/bin/env python

import wx

class pymot(wx.App):

    def __init__(self, redirect=False):
        wx.App.__init__(self, redirect)

class pymotGUI(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id,  &#039;Python Motif Finder&#039;, style=wx.DEFAULT_FRAME_STYLE)
        self.__do_layout()

    def __do_layout(self):
        pass

app = pymot()
frame = pymotGUI(parent=None, id = -1)
frame.Show()
app.MainLoop()
</pre>
<p>Usually a wxPython interface has three parts in its script: a class for the window/frame/dialog, a class for the application and a initialization routine. All wxPython applications, and scripts, need to derive an wx.App class and initialize it (on OnInit or on __init__ functions), i.e. create the window, begin the program, etc. Another class, derived from wx.Frame in this case, will build the window/frame/dialog <i>per se</i> and will also contain initialization for the window, objects, events, etc. The last part is the main script where the application is started, by calling the derived class, the window is also called and shown. The last line is the <code>MainLoop</code>, present in every wxPython script, and it is the main line of the script, the heart of the application. MainLoop processes all the events and manages how the objects interact by receiving and dispatching such events. </p>
<p>The script above could have been created differently, some lines of it omitted and there is also no need to derive an specific class for the frame. But this way it is easier to  get a grasp of the script as it will need to be enlarged so accomodates the objects and maybe a couple of extra windows and dialogs. Running the above script will generate the window below</p>
<p><a href="http://python.genedrift.org/wordpress/wp-content/uploads/2008/10/gui1.png"><img src="http://python.genedrift.org/wordpress/wp-content/uploads/2008/10/gui1-150x150.png" alt="First screencap of our GUI" title="First screencap of our GUI" width="150" height="150" class="aligncenter size-thumbnail wp-image-172" /></a></p>
<p>very simple and barebones. Next will explore the script above, include some extra elements and learn a little bit more of wxPython.</p>
]]></content:encoded>
			<wfw:commentRss>http://python.genedrift.org/2008/10/20/creating-an-interface-for-the-motif-finding-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

