Example #1
0
def enumerate_states(primes: dict, proposition: str):
    """
    Generates all states that are referenced by *proposition* in the context of the variables given by *primes*.
    The syntax of *proposition* should be as in bnet files and TRUE and FALSE in will be treated as 1 and 0.

    .. note::
        This function uses :ref:`bnet2primes <bnet2primes>` and :ref:`list_states_in_subspace <list_states_in_subspace>` to enumerate
        the states referenced by an expression. The efficiency of this approach can decreases a lot starting from around 15 variables
        that appear in *proposition*.

    **arguments**:
        * *primes*: prime implicants
        * *proposition*: a propositional formula

    **returns**:
        * *states*: the referenced states in str format

    **example**:

        >>> prop = "!Erk | (Raf & Mek)"
        >>> enumerate_states(primes,prop)[0]
        "010"
    """

    assert "?" not in primes

    proposition = proposition.replace("TRUE", "1")
    proposition = proposition.replace("FALSE", "0")
    new_primes = bnet_text2primes(text=f"?, {proposition}")

    states = set([])
    for p in new_primes["?"][1]:
        states.update(set(list_states_in_subspace(primes, p)))

    return list(states)
Example #2
0
def create_variables(primes: dict,
                     update_functions: Dict[str, Union[callable, str]],
                     copy: bool = False) -> Optional[dict]:
    """
    Creates the variables defined in *update_functions* and add them to *primes*.
    Variables that already exist in *primes* are overwritten.
    Raises an exception if the resulting primes contain undefined variables.
    The *update_functions* are given as a dictionary of names and functions that are either a bnet string or a Python callable.

    **arguments**:
        * *primes*: prime implicants
        * *update_functions*: a dictionary of names and update functions
        * *copy*: change *primes* in place or copy and return

    **returns**:
        * *new_primes* if *copy == True*

    **example**::

        >>> primes = bnet2primes("A, A")
        >>> create_variables(primes, {"B": "A"})
        >>> create_variables(primes, {"C": lambda A, B: A and not B})
        >>> primes2bnet(primes)
        A, A
        B, A
        C, A&!B
    """

    if copy:
        primes = copy_primes(primes)

    new_primes = {}
    dependencies = set([])
    names = set(primes)

    for name, function in update_functions.items():
        names.add(name)
        if type(function) is str:
            new_primes[name] = bnet_text2primes(
                text=f"{name}, {function}")[name]
        else:
            new_primes[name] = functions2primes({name: function})[name]

        for x in new_primes[name][1]:
            dependencies.update(set(x))

    undefined = dependencies - names
    if undefined:
        log.error(
            f"can not add variables that depend on undefined variables: undefined={undefined}"
        )
        raise Exception

    primes.update(new_primes)

    if copy:
        return primes
Example #3
0
def primify_rbn(rbn_ensemble_rules):
    prime_dict = {}
    for i, x in enumerate(rbn_ensemble_rules):
        rules = sm.format.booleannet2bnet(x)
        primes = bnet_text2primes(rules)
        pyboolnet.prime_implicants.percolate(primes,
                                             remove_constants=True,
                                             copy=False)
        primes, constants = sm.reduction.remove_outdag(primes)
        prime_dict[i] = primes
    return prime_dict
Example #4
0
def update_primes(primes: dict,
                  name: str,
                  constants: dict,
                  copy: bool = False) -> Optional[dict]:
    """
    Updates the primes of the component *name* given the *constants*.

    **arguments**:
        * *primes*: prime implicants
        * *name*: name of the component to update
        * *constants*: the assumed constants
        * *copy*: change *primes* in place or copy and return

    **returns**:
        * *new_primes* if *copy == True*

    **example**::

        >>> primes["ERK"] = update_primes(primes, name="ERK", subspace={"MEK": 1, "RAF": 0})
    """

    if copy:
        primes = copy_primes(primes=primes)

    items = set(constants.items())
    items_negated = set((k, 1 - v) for k, v in constants.items())
    implicants = [[], []]

    hit = False
    for value in [0, 1]:
        if hit:
            break

        for prime in primes[name][value]:
            prime_items = set(prime.items())
            if prime_items.intersection(items_negated):
                continue

            remainder = prime_items.difference(items)
            if not remainder:
                primes[name] = get_constant_primes(value=value)
                hit = True
                break

            implicants[value].append(dict(remainder))

    if not hit:
        dnf = get_dnf(one_implicants=implicants[1])
        unique_name = "kev034uf034hgu4hg9oef393"
        primes[name] = bnet_text2primes(
            text=f"{unique_name}, {dnf}")[unique_name]

    if copy:
        return primes
Example #5
0
def import_primes(fname, format='BooleanNet', remove_constants=False):
    """Import boolean rules from file and return pyboolnet formatted primes list.

    Parameters
    ----------
    fname : str
        Path to (plaintext) file containing Boolean rules in format specified
        by the 'format' option.
        Path to Boolean Expressions folder in case of CellCollective format.
    format : str
         Boolean rule format; options are 'BooleanNet' or 'BNet' or 'CellCollective'
         (the default is 'BooleanNet').
    remove_constants : bool
         If True, variables that are constant are removed and their influence is
         percolated. Otherwise, they remain and we consider initial conditions
         in opposition to their values (the default is False).

    Returns
    -------
    pyboolnet primes dictionary
        Update rules in pyboolnet format.

    """

    if format == 'CellCollective':
        rules1 = remove_comment_lines(open(fname + '/expr/expressions.ALL.txt'))
        external = remove_comment_lines(open(fname + '/expr/external_components.ALL.txt'))
        # In the case of CellCollective format, external components are given
        # rules of the form "A = A"
        lines = external.splitlines()
        for i in range(len(lines)):
            lines[i] = lines[i] + ' = ' + lines[i]
        rules2 = "\n".join(lines)
        rules = rules1 + "\n" + rules2
        rules = cellcollective2bnet(rules)

    else:
        rules = remove_comment_lines(open(fname))
        if format == 'BooleanNet':
            rules = booleannet2bnet(rules)
        elif format == 'BNet':
            rules = rules
        else:
            raise ValueError('Unrecognized format',format)

    primes = bnet_text2primes(rules)
    if remove_constants:
        pyboolnet.prime_implicants.percolate(primes,remove_constants=True,copy=False)
    return primes
def functions2primes(functions: Dict[str, callable]) -> dict:
    """
    Generates and returns the prime implicants of a Boolean network represented by *functions*.

    **arguments**:
        * *functions*: keys are component names and values are Boolean functions

    **returns**:
        * *primes*: primes implicants

    **example**:

        >>> funcs = {"v1": lambda v1, v2: v1 or not v2,
        ...          "v2": lambda v1, v2: v1 + v2 == 1}
        >>> primes = functions2primes(funcs)
    """

    mindnf = functions2mindnf(functions)
    text = "\n".join([f"{name},\t\t{dnf}" for name, dnf in mindnf.items()])

    return bnet_text2primes(text=text)
Example #7
0
def create_primes(rules,remove_constants = False):
    """Convert a BooleanNet or BNET string into a pyboolnet primes dictionary.

    Parameters
    ----------
    rules : str
        BooleanNet or BNET formatted rules. Hybrid formats are accepted as well.
        For the CellCollective format, use import_primes to read rules from the
        relevant files.
    remove_constants : bool
        Whether or not to remove and percolate constant input values (the default
        is False).

    Returns
    -------
    pyboolnet primes dictionary
        Update rules in pyboolnet format.

    """
    primes = bnet_text2primes(booleannet2bnet(rules))
    if remove_constants:
        pyboolnet.prime_implicants.percolate(primes,remove_constants=True,copy=False)
    return primes
Example #8
0
def bnet2primes(bnet: str, fname_primes: Optional[str] = None) -> dict:
    """
    Generates and returns the prime implicants of a Boolean network in **boolnet** format.
    The primes are saved as a *json* file if *fname_primes* is given.
    The argument *bnet* may be either the name of a *bnet* file or a string containing the file contents.
    Use the function `read_primes` to open a previously saved *json* file.

    .. example of boolnet format::

        Erk,  Erk & Mek | Mek & Raf
        Mek,  Erk | Mek & Raf
        Raf,  !Erk | !Raf

    **arguments**:
        * *bnet*: name of *bnet* file or string contents of file
        * *fname_primes*: *None* or name of *json* file to save primes

    **returns**:
        * *primes*: prime implicants

    **example**::

        >>> primes = bnet2primes("mapk.bnet", "mapk.primes" )
        >>> primes = bnet2primes("mapk.bnet")
        >>> primes = bnet2primes("Erk, !Mek \\n Raf, Ras & Mek")
        >>> primes = bnet2primes("Erk, !Mek \\n Raf, Ras & Mek", "mapk.primes")
    """

    primes = bnet_file2primes(
        fname_bnet=bnet) if os.path.isfile(bnet) else bnet_text2primes(
            text=bnet)

    if fname_primes and os.path.isfile(fname_primes):
        write_primes(primes=primes, fname_json=fname_primes)

    return primes
Example #9
0
rbn_ensemble_rules_K3_pcrit = sm.random_boolean_networks.random_boolean_network_ensemble_kauffman(
    N, K, p, N_ensemble, seed=seed, write_boolean_network=True)
end = default_timer()
print("Time (s) generating ensemble:", end - start)

print(
    "\nGenerating ensemble of 100 Kauffman RBN with K=3 and N=500 not at criticality . . ."
)
N = 500
K = 3
p = 0.5
N_ensemble = 100
seed = 1000
start = default_timer()
rbn_ensemble_rules_K3_p05 = sm.random_boolean_networks.random_boolean_network_ensemble_kauffman(
    N, K, p, N_ensemble, seed=seed, write_boolean_network=True)
end = default_timer()
print("Time (s) generating ensemble:", end - start)

print(
    "\nPrinting out original rules and reduced prime implicant rules for a RBN"
)
rules = rbn_ensemble_rules_K3_pcrit[0]
print("\nOriginal rules:")
print(rules)
rules = sm.format.booleannet2bnet(rules)
primes = bnet_text2primes(rules)
pyboolnet.prime_implicants.percolate(primes, remove_constants=True, copy=False)
print("\nReduced prime implicant rules:")
sm.format.pretty_print_prime_rules(primes)
Example #10
0
def test_bnet_text2primes():
    bnet_text = "\n".join(["v1, v2", "v2, !v1&(v1|v2)"])
    bnet_text2primes(text=bnet_text)
Example #11
0
        print("Trap Space ID (old,new):  ",a2013,", ",round(a2021,9),sep="")
        print("      Control (old,new):  ",c2013,", ",round(c2021,9),sep="")
        print("     Combined (old,new):  ",round(a2013+c2013,9),", ",round(a2021+c2021,9),sep="")
    return (a2013,c2013,a2021,c2021)

Ns = [10,20,30,40,50]
K=2
bias=0.5
N_ensemble=10
seed = 0
rbn_fnames = []
for N in Ns:
    rbns=sm.random_boolean_networks.random_boolean_network_ensemble_kauffman(N,K,bias,N_ensemble,seed=seed)
    for i,rbn in enumerate(rbns):
        rbn_bnet = sm.format.booleannet2bnet(rbn)
        p = bnet_text2primes(rbn_bnet)
        fname = "../models/Control Benchmarks/RBNs_seed="+str(seed)+"/"+str(N)+"_"+str(i)+".txt"
        rbn_fnames.append(fname)
        f = open(fname,"w")
        f.write(sm.format.primes2booleannet(p,header="#BOOLEAN RULES\n"))
        f.close()

f = open("../models/Control Benchmarks/RBNs_seed="+str(seed)+"/timings.csv","w")
f.write("model,a2013,c2013,a2021,c2021\n")

for fname in rbn_fnames:
    print()
    print(fname)
    times = CompareTimes(fname)
    f.write(','.join([fname]+list(map(str,times)))+'\n')