Monday, February 9, 2009

Network Layout using NetworkX

Below is the Python code that uses the Networkx module to layout the network. Hopefully the code is self-explanatory. The code is saved in "c/nxAutoLayout.py"

import pytc
import networkx as nx

nodes = pytc.itemsOfFamily("node");

connections = pytc.itemsOfFamily("connection");

numNodes = len(nodes);

numConnections = len(connections);

M = [];

for i in range(0,numConnections):

   pytc.setStraight(connections[i]);

   connected_nodes = pytc.getConnectedParts( connections[i] );

   for j in connected_nodes:

       n = 0;

       for k in range(0,numNodes):

           if nodes[k] == j:

           n = k;

           break;

       n += numConnections;

       M.append( (i,n) ); #connection i and node k are connected


G = nx.Graph();

G.add_nodes_from( range( 0, numConnections + numNodes ) );

G.add_edges_from(M);


Pos = nx.spring_layout(G);


minx = 0;

maxx = 0;

miny = 0;

maxy = 0;


for i in range(0,len(Pos)):

    if minx == 0 or minx > Pos[i][0]:

        minx = Pos[i][0];

    if miny == 0 or miny > Pos[i][1]:

        miny = Pos[i][1];

    if maxx == 0 or maxx <>

        maxx = Pos[i][0];

    if maxy == 0 or maxy <>

        maxy = Pos[i][0];


for i in range(0,len(Pos)):

   Pos[i][0] += - minx;

   Pos[i][0] *= 500.0/(maxx - minx);

   Pos[i][1] += - miny;

   Pos[i][1] *= 500.0/(maxy - miny);


for i in range(0,numConnections):

   pytc.setCenterPoint(connections[i],Pos[i][0],Pos[i][1]);


for i in range(numConnections,numConnections+numNodes):

   pytc.setPos(nodes[i-numConnections],Pos[i][0],Pos[i][1]);


print "layout finished";

Sunday, February 8, 2009

Changing the Parts Tree

Since the Parts Tree and Connection Tree are loaded from an XML file, it was long anticipated that a feature would be added which allows users to replace the default tree. Now, that feature is available. 

Right-click on the parts or connections tree allows replacement of the XML file for the tree. The new tree will not take effect until the next time TinkerCell starts. 

The natural problems with this is that the heirarchy or parts depends on the tree structure, which can be problematic for some plugins that use the isA("...") to determine whether a part belongs to a particular family. 

  

Measurement Units

The ItemFamily in TinkerCell has now been modified to include a Pair called measurementUnit.

This pair indicates the unit by which a part is measured. The measurement unit for Species family, for example, would be ("concentration", "mM")

This means that values such as "concentration" that were once places under "Attributes" are no longer attributes. The "Initial Value" data stores these values. The name "concentration" can be obtained by looking at the measurementUnit of the Species family. The same applies to all other families. Connection families do not have any measurement units at the moments (should they?). 

Important implications:
  1. units are not determined by the model, but by the family tree
  2. users cannot change the units while constructing models
  3. changing units means changing the parts/connections tree
  4. units are part of the "standards" defined by the parts and connections tree

Sunday, February 1, 2009

Python Modules inside TinkerCell






Since Python is embedded inside TinkerCell, a user does not need Python installed on his/her computer in order to use Python in TinkerCell. Of course, this is not an issue for Linux users, because it is very easy to install Python modules. 

Various useful Python modules will be included in TinkerCell. 

NumPy and SciPy are Python modules with functions ranging from numerical integration to statistics. Get more information at  numpy.scipy.org and www.scipy.org

PySCeS builds on SciPy and provides various useful functionalities for analysis of dynamical systems, particularly biological systems. Get more information at pysces.sourceforge.net

Networkx is a module with a few useful graph algorithms, particularly graph layout algorithms. Get more information at networkx.lanl.gov

Rpy is a Python version of the popular R statistical language. Get more information at rpy.sourceforge.net/


Python Interpreter inside TinkerCell

Problem:
It is not a good idea to load and unload the Python interpreter. It can cause Python to crash if external modules are loaded. 

The DynamicCodePlugin has been modified to alleviate this issue. 

The solution:  
The PythinInterpreterThread class runs as a separate thread. It initializes the Python interpreter when TinkerCell is loaded, and it finalizes (i.e. quits) the interpreter when TinkerCell exists. 

Now, it is very easy to call Python code inside a C program. The hillEquations.c function that generates the automatic Hill equation calls a Python code like this:

#include "TC_api.h"

int main()
{
    tc_runPythonFile("c/hillEquations.py");
    return 0;
}

Simple!

What happens here is that the DynamicCodePlugin accepts the string and sends it to the already loaded Python interpreter. This makes the process fast because the interpreter is already loaded. 

Drawback:

The Python interpreter runs as a single separate thread. This means that only one Python program can run at a time. In other words, Python programs are not as multi-threaded as C programs. But it is probably rare that someone would need to run multiple Python programs at once. 



Friday, January 16, 2009

Genetic Networks and Hill Equations

The new AutoRegulatoryNetwork plugin keeps track of how the genetic parts, such as promoters, coding sequence, etc. are moved. Whenever coding parts are placed downstream of a promoter, the coding parts will receive an Assignment rule that sets the coding part's value equal to the promoter part's value. Remember that value refers to the the activity numerical attribute for genetic parts such as promoter, rbs, coding, etc.

The AutoRegulatoryNetwork also provides actions in the context menu (mouse right click) that allow users to automatically place degradation reactions on species or transcription factor binding connections on regulatory parts.

The AutoRegulatoryNetwork is a nice combination with the Hill Equations python function, which automatically generates the Assignment rule for promoters. Select a promoter with one or more transcription factors bound to it, and click the Hill equation button.

The Hill Equations function is written in Python. Below is the code:

import pytc
items = pytc.selectedItems();
promoters = [];
pytc.errorReport("",0);
for i in items:
   if pytc.isA(i,"Regulatory"):
      promoters.append(i);

if (len(promoters) > 0):
k = pytc.getFromList("Select the logical function to approximate:",["AND","OR","NOT","XOR"]);
for i in promoters:
fracs = [];
indiv = [];
connectors = pytc.getConnectionsIn(i);
for c in connectors:
if pytc.isA(c,"Transcription Regulation"):
cname = pytc.getName(c);
parts = pytc.getConnectedPartsIn(c);
pnames = pytc.getNames(parts);
for n in pnames:
s = "(" + n + "/" + cname + ".kd)";
indiv.append(s);
s = "(1+pow(" + s + "," + cname + ".h))";
fracs.append(s);

rate = "";
if k == 0:
rate = " * ".join(indiv) + "/(1.0 + " + "*".join(fracs) + ")";
elif k == 1:
rate = "(" + " * ".join(fracs) + ")/(1.0 + " + "*".join(fracs) + ")";
elif k == 2:
rate = " 1.0 /(1.0 + " + "*".join(fracs) + ")";
elif k == 3:
rate = "(" + " + ".join(indiv) + ")/(1 + " + "*".join(fracs) + ")";
pytc.write(rate+"\n");
if (len(rate) > 0):
pytc.setTextData(i,"Assignments",pytc.getName(i),"function",rate);
else:
pytc.errorReport("no regulatory elements selected\n",0);

Events and Assignment Functions

Events allow you to define a condition and an event that will occur under those conditions. For example, IF B <= 1 THEN a =10 will set the value of A to 10 whenever B's value becomes less that 1. 

An assignment rule lets you define a function, such as a A.f = 1 + sin(time) * B, or something else like that. You can then use the name A.f in other parts of the model. 
Important: you can specify that A = 1 + sim(time).  This will make A itself into a boundary variable rather than a regular variable. 

Tuesday, December 30, 2008

Modules

Modules have interfaces (small pins on the edges) that can be used to connect one module to another. This connection merges the items (handles) that are connected. When the connection is deleted, then the handles are separated. In other words, the module connection performs the same function as grouping, but the interface is different -- that is all. Saving is a problem, because if the merged handles are saved, then the saved file will not have information about the original handles. So, before saving, the handles are separated, and after saving, the handles are merged again. When saving a model with modules, you will notice these commands being executed in the history window.

The ModuleTool uses a new class of connector called ModuleConnectionGraphicsItem. This connection always uses straight line and contains a merge-handle commmand inside. It does not have a handle. 

The ModuleTool also uses a new PatGraphicsItem called ModuleLinkerItem. This item always belongs on the edge of its parentModule; this adjustment is made in the paint method. It is always an alias, so it hides itself when the original item is not present. 

Wednesday, November 26, 2008

Python and R


Since TinkerCell has a C API and Python provides a recipe for embedding and extending (using python26.dll) , the natural extension is to provide a Python API on top of C API.

 
R, like Python, can be embedded inside C programs (using R.dll). Adding R is an efficient way to add a great number of functionality to TinkerCell. However, it seems that the easier way is to use Rpy


Saturday, November 15, 2008

Current C functions

-----------------------------------------------------

ODE simulation:

works on: selected items (all items if no items are selected)

writes the model in temp.c, performs the simulation using CVode and outputs the results to the output window and the plot window.  

-----------------------------------------------------

Stochastic simulation:  

works on: selected items (all items if no items are selected)

writes the model in temp.c, performs the naive Gillespie algorithm and outputs the results to the output window and the plot window

-----------------------------------------------------

Load Fill Binding Kinetics:  

works on: selected nodes with "Binding" connections

Generates the full binding/unbinding mass-action model for the Binding interactions that the selected node(s) is involved in.

-----------------------------------------------------

Multi-step Process:  

works on: selected 1-to-1 connections

Converts each reaction into a multi-step reaction with intermediates. Asks the user for the number of intermediate steps.

-----------------------------------------------------

Steady State Plot:  

works on: selected items (or all items if none are selected)

Asks the user for a variable, and performs repeated simulations (ODE) by incrementing that variable each time. Plots all the steady state values (0 if no steady state) as a function of the user selected variable.

-----------------------------------------------------

Values At Time T  :

works on: selected items (or all items if none are selected)

Asks the user for a variable, and performs repeated simulations (ODE or Stochastic) by incrementing that variable each time. Plots all the values at time T (user defined) as a function of the user selected variable. 

-----------------------------------------------------

Find Bistability:  

works on: selected items (or all items if none are selected)

Performs a complicated optimization in order to find the set of parameters that will convert the system into a bistable system (if such parameters exist). 

-----------------------------------------------------