Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

avoid sympy bug in ast_parser #20

Closed
wants to merge 4 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 46 additions & 8 deletions src/driven/data_sets/expression_profile.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# -*- coding: utf8 -*-
# -*- coding: utf-8 -*-

# Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU.

Expand All @@ -19,16 +19,53 @@
from __future__ import absolute_import

from itertools import combinations
from ast import And, Or, NodeTransformer

import altair as alt
import numpy as np
import pandas as pd
from sympy import Min, Max, Add, Mul, Symbol
from sympy.parsing.ast_parser import parse_expr

from cobra.core.gene import parse_gpr
from driven.utils import get_common_start


class Transform(NodeTransformer):
"""
Transform a python ast syntax tree to a sympy one.

The output of `cobra.core.gene.parse_gpr` is an extremely limited
syntax tree so we don't need to do much.
"""

def visit_Name(self, node):
return Symbol(node.id)
def visit_BoolOp(self, node):
values = [self.visit(v) for v in node.values]
if isinstance(node.op, And):
return Mul(*values)
if isinstance(node.op, Or):
return Add(*values)
return node

def parse_expr(gene_reaction_rule):
"""
Takes a gene_reaction_rule and converts it to a sympy expression.

Parameters
----------
gene_reaction_rule: string
model reaction rule

Returns
-------
Tuple[sympy.Expr, Set[str]]:
sympy expression, set of gene identifiers found
"""
a, genes = parse_gpr(gene_reaction_rule.strip())
a = Transform().visit(a)
return a.body, genes


class ExpressionProfile(object):
"""
Representation of an expression profile.
Expand Down Expand Up @@ -329,15 +366,16 @@ def _map_gene_to_rxn(self, reaction, gene_values, by):
float

"""
local_dict = {gene.id: Symbol(gene.id) for gene in reaction.genes}
rule = reaction.gene_reaction_rule.replace("and", "*").replace("or",
"+")
expression = parse_expr(rule, local_dict)
rule = reaction.gene_reaction_rule
expression, genes = parse_expr(rule)
missing = genes - set(gene_values)
if missing:
raise ValueError("missing values for genes {}".format(missing))
if by == "or2max_and2min":
expression = expression.replace(Mul, Min).replace(Add, Max)
elif by == "or2sum_and2min":
expression = expression.replace(Mul, Min)
return expression.subs(gene_values).evalf()
return float(expression.subs(gene_values).evalf())

def to_dict(self, condition):
"""
Expand Down