예제 #1
0
def FrF2(genenames, runs):
    """
    Genotypes: Fractional factorial design for two levels of a variable.
    
    @todo: There is a conflict between pylab plotting and the use of tcltk in R.
    Try to avoid plotting after running genotypes(). Plotting in an existing 
    figure window seems to work, though.
    """
    from rnumpy import r, rcopy
    r["genenames"] = rcopy(genenames)
    r("""
    library(FrF2)
    factor.names <- rep(list(c(0,2)), length(genenames))
    names(factor.names) <- genenames
    des <- FrF2(%s, factor.names=factor.names, randomize=FALSE)
    mat <- data.matrix(des)
    """ % runs)
    # r.mat has values 1 and 2 as seen from Python, even though we defined 
    # them as factor levels 0 and 2 in R.
    genotype = np.rec.fromarrays((r.mat.T - 1) * 2, names=genenames)
    return genotype
예제 #2
0
def markovplot(t, y, a=None, names=None, model=None, comp=None, col="bgrcmyk", 
    plotpy=False, plotr=True, newfig=True, **legend_kwargs):
    """
    Plot markov state distribution for ion channel.
    
    :param array_like t: time
    :param recarray y: state
    :param recarray a: algebraics
    :param names: sequence of variable names to include
    :param Cellmlmodel model: Cellmlmodel object
    :param str comp: (partial) name of component
    :param col: sequence of fill colours for stacked area chart
    :param bool plotpy: plot using Python (matplotlib)?
    :param bool plotr: plot using R (ggplot2)?
    :param bool newfig: create a new figure? (if using matplotlib)
    :param ``**legend_kwargs``: passed to matplotlib legend()
    
    If a is None, it will be computed using 
    ``model.rates_and_algebraic(t, y)``.
    If names is ``None``, include all "dimensionless" variables whose 
    component name contains *comp*.
    
    .. ggplot::
       
       from cgp.virtexp.elphys.examples import Bond
       from cgp.virtexp.elphys.clampable import markovplot
       
       bond = Bond()
       t, y, stats = bond.ap()
       p = markovplot(t, y, model=bond, comp="fast_sodium")
    """
    t, i = np.unique(t, return_index=True)
    y = y[i]
    if a is None:
        _dy, a = model.rates_and_algebraic(t, y)
    else:
        a = a[i]
    if names is None:
        # Often a closed state is defined algebraically as 1 minus the others.
        # This puts it apart from other closed states in the list of names 
        # that we generate below. To remedy this, we sort it.
        names = sorted([n for i in "y", "a" 
                        for n, c, u in zip(*model.legend[i]) 
                        if comp in c and u == "dimensionless"])
        # Distribution only makes sense for at least two states
        if len(names) < 2:
            return None
        # Now put any open state(s) first.
        o = [i for i in names if i.startswith("O")]
        no = [i for i in names if not i.startswith("O")]
        names = o + no
    x = np.rec.fromarrays(
        [y[k] if k in y.dtype.names else a[k] for k in names], names=names)
    xc = x.view(float).cumsum(axis=1).view(x.dtype).squeeze()
    if plotr:
        from ...utils.rec2dict import rec2dict
        r["df"] = r.cbind({"t": t}, r.as_data_frame(rec2dict(x)))
        # r["df"] = r.data_frame(t=t, **rec2dict(xc))
        # r["df"] = r("df[c('" + "','".join(["t"] + names) + "')]")
        r.library("ggplot2")
        r.library("jov")
        # r.plot(r.df)
        r["xm"] = r.melt(r.df, id_var="t")
        cmd = ("qplot(t, value, fill=variable, geom='area', position='stack', "
            "data=xm) + scale_fill_brewer('State', palette='Set3') + "
            "theme_bw() + blankopt")
        if comp:
            cmd += "+ opts(title='%s')" % comp
        return r(cmd)
    if plotpy:
        from pylab import figure, fill_between, legend, axis, Rectangle
        if newfig:
            figure()
        prev = 0
        col = [col[i % len(col)] for i in range(len(names))]
        # Workaround for fill_between not being compatible with legend():
        # http://matplotlib.sourceforge.net/users/legend_guide.html
        # #plotting-guide-legend
        symbols = []
        labels = []
        for i, k in enumerate(x.dtype.names):
            kwargs = dict(label=k, facecolor=col[i], edgecolor="none")
            fill_between(t, xc[k], prev, **kwargs)
            prev = xc[k]
            symbols.append(Rectangle((0, 0), 1, 1, **kwargs))
            labels.append(k)
        axis("tight")
        # Reverse to match vertical order
        legend(reversed(symbols), reversed(labels), labelspacing=0, 
               handlelength=1, handletextpad=0.5, borderaxespad=0, 
               **legend_kwargs)

def markovplots(t, y, a=None, model=None):
    """
    Markov plots for all components.
    
    >>> from cgp.virtexp.elphys.examples import Bond
    >>> bond = Bond()
    >>> t, y, stats = bond.ap()
    >>> from cgp.utils.thinrange import thin
    >>> i = thin(len(t), 100)
    
    (Below, the ... ellipsis makes doctest ignore messages that R may print 
    about packages getting loaded. However, doctest output cannot start with 
    ellipsis, so we need to print something else first. Sigh.)
    
    >>> print "Text output ignored:"; L = markovplots(t[i], y[i], model=bond)
    Text output ignored:...
    >>> from rnumpy import r
    >>> r.windows(record=True) # doctest: +SKIP
    >>> print L # doctest: +SKIP    
    """
    comps = np.unique([c for v in model.legend.values() 
                       for _n, c, _u in zip(*v) if c])
    plots = [markovplot(t, y, model=model, comp=comp) for comp in comps]
    return [(c, p) for c, p in zip(comps, plots) if p]

if __name__ == "__main__":
    import doctest
    doctest.testmod(optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE)
예제 #3
0
파일: splom.py 프로젝트: mirams/cgptoolbox
        return OrderedDict((k, rlist2pydict(r.dollar(x, k))) for k in xnames)

def r2rec(x):
    """
    Convert R list to Numpy record array.
    
    >>> r2rec(r.iris)[0:1] # doctest: +NORMALIZE_WHITESPACE
    rec.array([(5.1, 3.5, 1.4, 0.2, 'setosa')], 
    dtype=[('Sepal.Length', '<f8'), ('Sepal.Width', '<f8'), 
    ('Petal.Length', '<f8'), ('Petal.Width', '<f8'), ('Species', '|S10')])
    """
    k, v = zip(*rlist2pydict(x).items())
    return np.rec.fromarrays(v, names=k).view(np.recarray)

try:
    iris = r2rec(r("within(iris, Species <- as.numeric(Species))"))
except NameError:
    iris = None

def spij(m, n, i, j, *args, **kwargs):
    """Subplot specified by nrows, ncols, row, col; row, col start from zero."""
    return subplot(m, n, 1 + i * n + j, *args, **kwargs)

def thinp(h, k, n):
    """Thin property 'k' of handle 'h' to 'n' elements."""
    hk = getp(h, k)[1:-1]
    if len(hk) > 0:
        setp(h, k, thin(hk, n))

# pylint: disable=W0401
def splom(a=None, fun=plot, ntick=3, trim=(0, 0), hkw={}, skw={},