def query(networks, resultsdir, params):
    '''
    :param networks: list of network specification strings in DSGRN format
    :param resultsdir: path to directory where results file(s) will be stored
    :param params: dictionary with key "num_proc" that specifies the (integer) number of processes to be created in the multiprocessing tools.

    :return: Writes count of parameters with a stable FC to a dictionary keyed by
    network spec, which is dumped to a json file.
    '''

    resultsdict = {}
    for k, netspec in enumerate(networks):
        with open("temp.txt", "w") as f:
            f.write(netspec)
        subprocess.call(
            "mpiexec --oversubscribe -n {} Signatures {} {}".format(
                params["num_proc"], "temp.txt", "temp.db"),
            shell=True)
        db = DSGRN.Database("temp.db")
        N = db.parametergraph.size()
        matches = len(DSGRN.StableFCQuery(db).matches())
        resultsdict[netspec] = (matches, N)
        rname = os.path.join(resultsdir, "query_results.json")
        if os.path.exists(rname):
            os.rename(rname, rname + ".old")
        json.dump(resultsdict, open(rname, 'w'))
        subprocess.call(["rm", "temp.db"])
        subprocess.call(["rm", "temp.txt"])
        print("Network {} of {} complete".format(k + 1, len(networks)))
        sys.stdout.flush()
Exemple #2
0
def results(net_str, circuit, truthtables, displaygraph=False):
    # truth tables is list of dictionaries
    datetime = subprocess.check_output(['date +%Y_%m_%d_%H_%M_%S'],
                                       shell=True).decode(
                                           sys.stdout.encoding).strip()
    network = DSGRN.Network()
    network.assign(net_str)
    if displaygraph:
        display(graphviz.Source(network.graphviz()))
    pg = DSGRN.ParameterGraph(network)
    np = pg.size()
    tt = []
    for states in truthtables:
        state_dicts = []
        for name, state in states.items():
            state_dicts.append(
                {network.index(str(k)): state[k]
                 for k in state})
        tt.append(tuple(state_dicts))
    params = get_matching_truthtables(pg, tt, np)
    for k, t in enumerate(tt):
        l = len(params[k])
        print("Truth table:")
        print(t)
        print("Parameters with specified truth table: {}/{} = {:.2f}%".format(
            l, np, l / np * 100))
    D = {"network": net_str}
    D.update({k: t for k, t in enumerate(truthtables)})
    json.dump(D, open('metadata{}_{}.json'.format(datetime, circuit), 'w'))
    json.dump(params, open('params{}_{}.json'.format(datetime, circuit), 'w'))
def get_essential_parameter_neighbors(parametergraph):
    '''
    This function returns the list of co-dimension 1 neighboring parameters of the essential parameters in a network.
    :param parametergraph: Parameter graph of a network with at least one NONESSENTIAL node.
    :return: List of essential parameters and list of neighboring parameters.
    '''
    # If all nodes are essential return empty list
    net_spec = parametergraph.network().specification()
    nonessential, ess_net_spec = make_essential(net_spec)
    if not nonessential:
        print("Essential network. Not computing neighbors.")
        return [], []
    # Get list of indices of essential parameters and its neighbors embedded in the parameter graph of the original network
    ess_parametergraph = DSGRN.ParameterGraph(DSGRN.Network(ess_net_spec))
    ess_par_indices = []  # Essential parameter indices
    ess_par_neighbors = set()  # Neighbors of essential parameters
    for ess_pindex in range(ess_parametergraph.size()):
        # Get the essential parameter
        ess_par = ess_parametergraph.parameter(ess_pindex)
        # Get its index in the original parameter graph
        full_pindex = parametergraph.index(ess_par)
        # Add the index to the list of essential parameters
        ess_par_indices.append(full_pindex)
        # Get the co-dimension 1 neighbors of this essential parameter
        for p_index in parametergraph.adjacencies(full_pindex, "codim1"):
            ess_par_neighbors.add(p_index)
    # Remove neighbors that are essential parameters
    ess_par_neighbors.difference_update(ess_par_indices)
    # Return list of essential parameters and its neighbors
    return ess_par_indices, list(ess_par_neighbors)
def PathMatch(network, posets, domain, stablefc, dsgrn_param):
    '''
    Test for the existence of at least one pattern match in the domain graph and/or stable full cycles.
    :param network: DSGRN.Network object
    :param dsgrn_params: list of tuples of parameter indices and DSGRN.Parameter objects.
    :param posets: The partially ordered sets that are to be matched at each epsilon in DSGRN format.
    :param domain: True or False, search over whole domain graph.
    :param stablefc: True or False search over stable full cycles only.
    :return: {"domain" : {tsfile : {str(eps) : True or False}}, "match" : {tsfile : {str(eps) : True or False}, "stablefc" : True or False}
    '''
    param_index, param = dsgrn_param
    DomMatch = {tsfile: {} for tsfile, _ in posets.items()}
    FCMatch = {tsfile: {} for tsfile, _ in posets.items()}
    FC = False
    domaingraph = DSGRN.DomainGraph(param)
    for tsfile, poset_list in posets.items():
        for (eps, (events, event_ordering)) in poset_list:
            patterngraph = DSGRN.PatternGraph(
                DSGRN.PosetOfExtrema(network, events, event_ordering))
            if domain:
                DomMatch[tsfile][eps] = domain_check(domaingraph, patterngraph)
            if stablefc:
                FCMatch[tsfile][eps], FC = stableFC_check(
                    domaingraph, patterngraph)
    results = {}
    if domain:
        results["domain"] = DomMatch
    if stablefc:
        results["stablefc"] = FC
        results["match"] = FCMatch
    return (param_index, results)
def get_one_change_params(logic, out="GFP", topvalout=1, print_output=True):
    '''

    :param logic: A function handle specifying one of the logics in this module.
    :return: A dictionary of truth tables and parameters counts, a corresponding dictionary of the parameter indices, and a dictionary of the most parsimonious hex codes for each truth table (the hex codes where there is exactly one change from design spec.
    '''
    dbname, in1, topval1, in2, topval2, design_spec = logic()
    sfile, pfile = do_all_queries(dbname, in1, topval1, in2, topval2, out,
                                  topvalout, print_output)

    summary = json.load(open(sfile))
    params = json.load(open(pfile))

    pg = DSGRN.ParameterGraph(DSGRN.Network(get_network(dbname)))

    one_change_hexes = {}
    for s, v in summary.items():
        try:
            w = int(v[0])
        except:
            continue
        if w > 0:
            hlist = []
            for p in params[s]:
                hexlist = get_hex(p, pg)
                if sum([1 for h, d in zip(hexlist, design_spec)
                        if h != d]) == 1:
                    hlist.append(hexlist)
            one_change_hexes.update({s: hlist})
    return summary, params, one_change_hexes
Exemple #6
0
def search_over_networks(count, N, enum_network):
    '''
    Work function for parallelization.
    :param count: True or False, count DSGRN parameters or shortcut to existence
    :param N: Size of the DSGRN parameter graph
    :param enum_network: An (integer, DSGRN network specification) pair
    :return: (DSGRN network specification, results) pair
    '''
    k, netspec = enum_network
    numparams = 0
    network = DSGRN.Network(netspec)
    parametergraph = DSGRN.ParameterGraph(network)
    for p in range(parametergraph.size()):
        parameter = parametergraph.parameter(p)
        dg = DSGRN.DomainGraph(parameter)
        mg = DSGRN.MorseGraph(dg)
        stable_FC_annotations = [
            mg.annotation(i)[0] for i in range(0,
                                               mg.poset().size())
            if is_FC(mg.annotation(i)[0]) and len(mg.poset().children(i)) == 0
        ]
        if count and len(stable_FC_annotations) > 0:
            numparams += 1
        elif len(stable_FC_annotations) > 0:
            print("Network {} of {} complete".format(k + 1, N))
            sys.stdout.flush()
            return netspec, (True, parametergraph.size())
    print("Network {} of {} complete".format(k + 1, N))
    sys.stdout.flush()
    if count:
        return netspec, (numparams, parametergraph.size())
    else:
        return netspec, (False, parametergraph.size())
def test():
    network_spec = """
    x : (x)(y)(~z) : E
    y : (x)(~z) : E
    z : (y) : E"""
    network = DSGRN.Network(network_spec)
    num_inedges, num_outedges, groups, essential = get_info_from_network(
        network)
    logic_files = ["3_2_1_1_1_E.dat", "2_2_1_1_E.dat", "1_2_1_E.dat"]
    for ni, no, mm, e, lf in zip(num_inedges, num_outedges, groups, essential,
                                 logic_files):
        l = build_logic_file_name(ni, no, mm, e)
        assert (l == lf)
    network_spec = """
    x : (x + y)(~z) : E
    y : (x)(~z)
    z : (y + z) : E"""
    network = DSGRN.Network(network_spec)
    num_inedges, num_outedges, groups, essential = get_info_from_network(
        network)
    logic_files = ["3_2_1_2_E.dat", "2_2_1_1.dat", "2_3_2_E.dat"]
    for ni, no, mm, e, lf in zip(num_inedges, num_outedges, groups, essential,
                                 logic_files):
        l = build_logic_file_name(ni, no, mm, e)
        assert (l == lf)
def findAllOrderedExtremaDomainGraph(paramlist=None,networkfile=None,networkspec=None):
    if networkfile:
        network = DSGRN.Network(networkfile)
    elif networkspec:
        network = DSGRN.Network()
        network.assign(networkspec)
    else:
        raise ValueError("No input network.")
    names = [network.name(i) for i in range(network.size())]
    paramgraph = DSGRN.ParameterGraph(network)
    paths = []
    start = time.time()
    if not paramlist:
        paramlist=range(paramgraph.size())
    for paramind in paramlist:
        if time.time()-start >= 2:
            print("{} / {} parameters analyzed\n".format(paramind,paramgraph.size()))
            start = time.time()
        domaingraph = DSGRN.DomainGraph(paramgraph.parameter(paramind))
        digraph = makeNXDigraph(domaingraph)
        cycles = findCycles(digraph)
        extrema  = orderedExtrema(names,cycles)
        p = removeCyclicPermutations(extrema,set([]))
        paths.append(list(p))
    return paths
def get_parameter_neighbors_from_list_in_nonessential_pg(
        parametergraph, paramlist):
    '''
    This function returns the list of co-dimension 1 neighboring parameters IN THE NONESSENTIAL PARAMETER GRAPH
    for each of the parameters in paramlist associated to the supplied parameter graph. If the supplied parameter graph
    is nonessential, then all neighbors will be found.
    :param parametergraph: Parameter graph of a network with at least one ESSENTIAL node.
    :param paramlist: list of parameter indices to find neighbors for in the full nonessential graph
    :return: List of new parameter indices in the nonessential graph for each index in paramlist and
    list of neighboring parameter indices.
    '''
    # If all nodes are essential return empty list
    net_spec = parametergraph.network().specification()
    essential, noness_net_spec = make_nonessential(net_spec)
    noness_parametergraph = DSGRN.ParameterGraph(
        DSGRN.Network(noness_net_spec))
    parlist_indices = []
    parlist_neighbors = set([])
    for pindex in paramlist:
        # Get the parameter object
        par = parametergraph.parameter(pindex)
        # Get its index in the nonessential parameter graph
        full_pindex = noness_parametergraph.index(par)
        # Add the index to the list of essential parameters
        parlist_indices.append(full_pindex)
        # Get the co-dimension 1 neighbors of this essential parameter
        for p in noness_parametergraph.adjacencies(full_pindex, "codim1"):
            parlist_neighbors.add(p)
    # Remove neighbors that are in the input list
    parlist_neighbors.difference_update(parlist_indices)
    # Return list of essential parameters and its neighbors
    return parlist_indices, list(parlist_neighbors)
def getpg(tup,N):
    (k, netspec) = tup
    print("Network {} of {}".format(k+1, N))
    sys.stdout.flush()
    network = DSGRN.Network(netspec)
    parametergraph = DSGRN.ParameterGraph(network)
    return netspec,network,parametergraph
Exemple #11
0
def PathMatches_without_count(network, posets, domain, stablefc):
    '''
    Test for the existence of at least one pattern match in the domain graph and/or stable full cycles.
    :param network: DSGRN network object.
    :param posets: The partially ordered sets that are to be matched at each epsilon in DSGRN format.
    :param domain: True or False, search over whole domain graph.
    :param stablefc: True or False search over stable full cycles only.
    :return: dictionary of results
    '''
    def format(numDomMatch, numFCMatch):
        dommatches = {
            tsfile:
            [(float(eps), b, paramgraph.size()) for eps, b in edict.items()]
            for tsfile, edict in numDomMatch.items()
        }
        fcmatches = {
            tsfile:
            [(float(eps), b, paramgraph.size()) for eps, b in edict.items()]
            for tsfile, edict in numFCMatch.items()
        }
        return dommatches, fcmatches

    numDomMatch = {
        tsfile: {str(eps[0]): False
                 for eps in poset_list}
        for tsfile, poset_list in posets.items()
    }
    numFCMatch = {
        tsfile: {str(eps[0]): False
                 for eps in poset_list}
        for tsfile, poset_list in posets.items()
    }
    paramgraph = DSGRN.ParameterGraph(network)
    for paramind in range(paramgraph.size()):
        domaingraph = DSGRN.DomainGraph(paramgraph.parameter(paramind))
        for tsfile, poset_list in posets.items():
            for (eps, (events, event_ordering)) in poset_list:
                patterngraph = DSGRN.PatternGraph(
                    DSGRN.PosetOfExtrema(network, events, event_ordering))
                if domain and not numDomMatch[tsfile][str(eps)]:
                    dommatch = domain_check(domaingraph, patterngraph)
                    if dommatch:
                        numDomMatch[tsfile][str(eps)] = True
                if stablefc and not numFCMatch[tsfile][str(eps)]:
                    stabmatch, newFC = stableFC_check(domaingraph,
                                                      patterngraph)
                    if stabmatch:
                        numFCMatch[tsfile][str(eps)] = True
        b = True
        for tsfile, poset_list in posets.items():
            b = bool(
                b *
                all([numDomMatch[tsfile][str(eps[0])] for eps in poset_list]))
            b = bool(
                b *
                all([numFCMatch[tsfile][str(eps[0])] for eps in poset_list]))
        if b:
            return format(numDomMatch, numFCMatch)
    return format(numDomMatch, numFCMatch)
Exemple #12
0
def getGraphs(events, event_ordering, network):
    '''
    Make pattern graph and parameter graph for the network and poset.
    '''
    poe = DSGRN.PosetOfExtrema(network, events, event_ordering)
    patterngraph = DSGRN.PatternGraph(poe)
    paramgraph = DSGRN.ParameterGraph(network)
    return paramgraph, patterngraph
Exemple #13
0
def initialize(ind):
    # ind = parameter index where match should occur
    spec = "x : ~y : E\ny : x : E\nz : x : E"
    network = DSGRN.Network(spec)
    pg = DSGRN.ParameterGraph(network)
    dgs = [DSGRN.DomainGraph(pg.parameter(p)) for p in range(pg.size())]
    sgs = [DSGRN.SearchGraph(dg) for dg in dgs]
    return network, sgs[ind]
Exemple #14
0
def getpg(netspec):
    '''
    Calculate DSGRN parameter graph
    :param netspec: DSGRN network specification
    :return: (DSGRN.Network object, DSGRN.ParameterGraph object)
    '''
    network = DSGRN.Network(netspec)
    parametergraph = DSGRN.ParameterGraph(network)
    return network, parametergraph
Exemple #15
0
def test3():
    network_file = "toggle_switch_33node_reduction_4node.txt"
    network = DSGRN.Network(network_file)
    boolean_params = selectbool.subset_boolean_parameters(network)
    assert (len(boolean_params) == 48000)
    network_file = "toggle_switch_33node_reduction_4node_E.txt"
    network = DSGRN.Network(network_file)
    boolean_params = selectbool.subset_boolean_parameters(network)
    assert (len(boolean_params) == 1458)
Exemple #16
0
def test5():
    network_file = "toggle_switch_33node_reduction_4node.txt"
    network = DSGRN.Network(network_file)
    single_order, all_orders = selectbool.count_boolean_parameters(network)
    assert (single_order == 48000)
    network_file = "toggle_switch_33node_reduction_4node_E.txt"
    network = DSGRN.Network(network_file)
    single_order, all_orders = selectbool.count_boolean_parameters(network)
    assert (single_order == 1458)
def test4():
    network_spec = "A : A + B\nB : (B)(~A)(~C)\nC : A + C"
    network = DSGRN.Network(network_spec)
    assert (build.index2name(network, build.name2index(network, "A")) == "A")
    assert (build.index2name(network, build.name2index(network, "B")) == "B")
    assert (build.index2name(network, build.name2index(network, "C")) == "C")
    network_spec = "A : A + B : E\nB : (B)(~A) : E\nC : A : E"
    network = DSGRN.Network(network_spec)
    assert (build.index2name(network, build.name2index(network, "A")) == "A")
    assert (build.index2name(network, build.name2index(network, "B")) == "B")
    assert (build.index2name(network, build.name2index(network, "C")) == "C")
 def test_pstring_parser(self):
     # only checking that it runs. That the parameters are correct needs to be
     # checked manually.
     N, L, Delta, theta, gamma = self.toggle_switch_parameters()
     par_index = 0
     sampler = DSGRN.ParameterSampler(N)
     pg = DSGRN.ParameterGraph(N)
     parameter = pg.parameter(par_index)
     sample_string = sampler.sample(parameter)
     RS = get_ramp_system_from_parameter_string(sample_string, N)
     assert (RS.is_regular())
Exemple #19
0
def check_Morsegraphs(spec):
    net = DSGRN.Network(spec)
    pg = DSGRN.ParameterGraph(net)
    test = {}
    for pi in range(pg.size()):
        param = pg.parameter(pi)
        dg = DSGRN.DomainGraph(param)
        md = DSGRN.MorseDecomposition(dg.digraph())
        mg = DSGRN.MorseGraph(md, dg)
        test[pi] = ast.literal_eval(mg.annotation(0).stringify())[0]
    return test
Exemple #20
0
def PathMatches_with_count(network, posets, domain, stablefc):
    '''
    Count the number of pattern matches in the domain graph and/or stable full cycles.
    :param network: DSGRN network object.
    :param posets: The partially ordered sets that are to be matched at each epsilon in DSGRN format.
    :param domain: True or False, search over whole domain graph.
    :param stablefc: True or False search over stable full cycles only.
    :return: dictionary of results
    '''
    if len(posets) > 1:
        totalDom= {"all": {str(eps[0]) : set() for eps in posets[next(iter(posets))]} }
        totalFC = {"all": {str(eps[0]) : set() for eps in posets[next(iter(posets))]} }
    numDomMatch = { tsfile : {str(eps[0]) : 0 for eps in poset_list} for tsfile,poset_list in posets.items()}
    numFCMatch = { tsfile : {str(eps[0]) : 0 for eps in poset_list} for tsfile,poset_list in posets.items()}
    numFC = 0
    paramgraph = DSGRN.ParameterGraph(network)
    for paramind in range(paramgraph.size()):
        FC = False
        domaingraph = DSGRN.DomainGraph(paramgraph.parameter(paramind))
        for tsfile, poset_list in posets.items():
            for (eps, (events, event_ordering)) in poset_list:
                patterngraph = DSGRN.PatternGraph(DSGRN.PosetOfExtrema(network,events,event_ordering))
                if stablefc:
                    stabmatch, newFC = stableFC_check(domaingraph,patterngraph)
                    if newFC and not FC:
                        numFC +=1
                        FC = True
                    if stabmatch:
                        numFCMatch[tsfile][str(eps)]+=1
                        if len(posets) > 1:
                            totalFC["all"][str(eps)].add(paramind)
                    if stabmatch and domain:
                        numDomMatch[tsfile][str(eps)] += 1
                        if len(posets) > 1:
                            totalDom["all"][str(eps)].add(paramind)
                    elif not stabmatch and domain:
                        dommatch = domain_check(domaingraph, patterngraph)
                        if dommatch:
                            numDomMatch[tsfile][str(eps)] += 1
                            if len(posets) > 1:
                                totalDom["all"][str(eps)].add(paramind)
                if domain and not stablefc:
                    dommatch = domain_check(domaingraph,patterngraph)
                    if dommatch:
                        numDomMatch[tsfile][str(eps)]+=1
                        if len(posets) > 1:
                            totalDom["all"][str(eps)].add(paramind)
    dommatches = {tsfile : [(float(eps),count,paramgraph.size()) for eps,count in edict.items()] for tsfile,edict in numDomMatch.items()}
    fcmatches = {tsfile : [(float(eps),count,numFC,paramgraph.size()) for eps,count in edict.items()] for tsfile,edict in numFCMatch.items()}
    if len(posets)>1:
        dommatches.update({"all": [(float(eps),len(totalDom["all"][eps]),paramgraph.size()) for eps in totalDom["all"]]})
        fcmatches.update({"all" : [(float(eps),len(totalFC["all"][eps]),numFC,paramgraph.size()) for eps in totalFC["all"]]})
    return dommatches,fcmatches
Exemple #21
0
def query(networks, resultsdir, params):
    '''
    :param networks: list of network specification strings in DSGRN format
    :param resultsdir: path to directory where results file(s) will be stored
    :param params: dictionary containing the key "bounds". bounds is a dictionary
    of variable names common to all network specifications with a range of values
    assigned to each. Example: {"X1":[2,2],"X2":[1,1],"X3":[0,1]}. The integer ranges
    are the matching conditions for an FP. For example, if there are four variables
    X1, X2, X3, X4 in the network spec, the FP (2,1,0,*) would be a match for any
    value of *.

    :return: Writes count of parameters with an FP match to a dictionary keyed by
    network spec, which is dumped to a json file.
    '''
    bounds = dict(params["bounds"])

    def is_FP(annotation):
        return annotation.startswith("FP")

    def is_FP_match(bounds_ind, annotation):
        digits = [
            int(s) for s in annotation.replace(",", "").split() if s.isdigit()
        ]
        return all(
            digits[k] >= bounds_ind[k][0] and digits[k] <= bounds_ind[k][1]
            for k in bounds_ind)

    resultsdict = {}
    for net in networks:
        count = 0
        network = DSGRN.Network()
        network.assign(net)
        bounds_ind = {network.index(str(k)): bounds[k] for k in bounds}
        parametergraph = DSGRN.ParameterGraph(network)
        for p in range(parametergraph.size()):
            parameter = parametergraph.parameter(p)
            dg = DSGRN.DomainGraph(parameter)
            md = DSGRN.MorseDecomposition(dg.digraph())
            mg = DSGRN.MorseGraph(dg, md)
            stable_FP_annotations = [
                mg.annotation(i)[0] for i in range(0,
                                                   mg.poset().size()) if
                is_FP(mg.annotation(i)[0]) and len(mg.poset().children(i)) == 0
            ]
            if any([is_FP_match(bounds_ind, a)
                    for a in stable_FP_annotations]):
                count += 1
        resultsdict[net] = [count, parametergraph.size()]

    rname = os.path.join(resultsdir, "query_results.json")
    if os.path.exists(rname):
        os.rename(rname, rname + ".old")
    json.dump(resultsdict, open(rname, 'w'))
Exemple #22
0
def DSGRN_Computation(parameter):
    '''
    Get DSGRN annotations for all Morse sets that are fixed points.
    :param parameter: DSGRN.Parameter object
    :return: list of DSGRN annotations
    '''
    dg = DSGRN.DomainGraph(parameter)
    mg = DSGRN.MorseGraph(dg)
    return [
        mg.annotation(i)[0] for i in range(0,
                                           mg.poset().size())
        if is_FP(mg.annotation(i)[0]) and len(mg.poset().children(i)) == 0
    ]
def domain_check(domaingraph, patterngraph):
    '''
    Check for match in domain graph for one parameter
    :param domaingraph: DSGRN domain graph object
    :param patterngraph: DSGRN pattern graph object
    :return: True or False
    '''
    ismatch = False
    searchgraph = DSGRN.SearchGraph(domaingraph)
    matchinggraph = DSGRN.MatchingGraph(searchgraph, patterngraph)
    if DSGRN.PathMatch(matchinggraph):
        ismatch = True
    return ismatch
Exemple #24
0
def test4():
    network_spec = """
    A : (~B) : E
    B : (~A)(~C) : E
    C : (A) : E"""
    network = DSGRN.Network(network_spec)
    boolean_params = selectbool.subset_boolean_parameters_all_orders(network)
    assert (len(boolean_params) == 4)
    logics = set([
        tuple([param.logic()[j].hex() for j in range(network.size())])
        for param in boolean_params
    ])
    logics_predict = set(
        [tuple(l) for l in itertools.product(["C"], ["8", "E"], ["2"])])
    assert (logics == logics_predict)
    orders = set([
        tuple([param.order()[j].stringify() for j in range(network.size())])
        for param in boolean_params
    ])
    orders_predict = set([
        tuple(o)
        for o in itertools.product(["[0,1]", "[1,0]"], ["[0]"], ["[0]"])
    ])
    assert (orders == orders_predict)

    network_spec = """
    A : (~B)
    B : (~A)(~C)
    C : (A)"""
    network = DSGRN.Network(network_spec)
    boolean_params = selectbool.subset_boolean_parameters_all_orders(network)
    logics = set([
        tuple([param.logic()[j].hex() for j in range(network.size())])
        for param in boolean_params
    ])
    print(logics)
    assert (len(boolean_params) == 108)
    logics_predict = set([
        tuple(l) for l in itertools.product(
            ["0", "C", "F"], ["0", "A", "C", "8", "E", "F"], ["0", "2", "3"])
    ])
    assert (logics == logics_predict)
    orders = set([
        tuple([param.order()[j].stringify() for j in range(network.size())])
        for param in boolean_params
    ])
    orders_predict = set([
        tuple(o)
        for o in itertools.product(["[0,1]", "[1,0]"], ["[0]"], ["[0]"])
    ])
    assert (orders == orders_predict)
Exemple #25
0
def DatabaseJSON(network,
                 param_indices=None,
                 verts_colors=None,
                 eq_cells=False,
                 thres_type=''):
    if network.size() not in [2, 3]:
        print('Only available for dimensions 2 and 3!')
        return
    parameter_graph = DSGRN.ParameterGraph(network)
    # Use all parameter indices if None
    if param_indices == None:
        param_indices = range(parameter_graph.size())
    network_json_data = network_json(network)
    cell_complex_json_data = cubical_complex_json(network)
    param_graph_json_data = parameter_graph_json(parameter_graph,
                                                 param_indices, verts_colors,
                                                 thres_type)
    dynamics_database = []  # Dynamics database
    for par_index in param_indices:
        # Compute DSGRN dynamics
        parameter = parameter_graph.parameter(par_index)
        domain_graph = DSGRN.DomainGraph(parameter)
        morse_decomposition = DSGRN.MorseDecomposition(domain_graph.digraph())
        morse_graph = DSGRN.MorseGraph(domain_graph, morse_decomposition)
        morse_graph_json_data = morse_graph_json(morse_graph)
        morse_sets_json_data = morse_sets_json(network, morse_graph,
                                               morse_decomposition)
        stg_json_data = state_transition_graph_json(network, domain_graph)
        if eq_cells:  # Include equilibrium cells if true
            eq_cells_json_data = equilibrium_cells_json(
                parameter, morse_sets_json_data["morse_sets"])
        else:
            eq_cells_json_data = {"equilibrium_cells": []}
        # Dynamics data for this parameter
        dynamics_json_data = {
            "parameter": par_index,
            "morse_graph": morse_graph_json_data["morse_graph"],
            "morse_sets": morse_sets_json_data["morse_sets"],
            "equilibrium_cells": eq_cells_json_data["equilibrium_cells"],
            "stg": stg_json_data["stg"]
        }
        dynamics_database.append(dynamics_json_data)
    morse_graph_database = {
        "network": network_json_data["network"],
        "complex": cell_complex_json_data["complex"],
        "parameter_graph": param_graph_json_data["parameter_graph"],
        "dynamics_database": dynamics_database
    }
    return morse_graph_database
Exemple #26
0
def test1():
    db2D1 = DSGRN.Database("2D_Example_A.db")
    db2D2 = DSGRN.Database("2D_test.db")
    for i in range(1600):
        assert db2D1(i) == db2D2(i)
    sqlexpression = "select * from MorseGraphAnnotations where MorseGraphIndex = ?"
    c = db2D1.cursor
    d = db2D2.cursor
    for i in range(77):
        c.execute(sqlexpression, (i,))
        ann1 = c.fetchall()
        d.execute(sqlexpression, (i,))
        ann2 = d.fetchall()
        assert ann1 == ann2
    subprocess.call("rm 2D_test.db",shell=True)
Exemple #27
0
def test2():
    db3D1 = DSGRN.Database("3D_Haase_II.db")
    db3D2 = DSGRN.Database("3D_test.db")
    for i in range(40824):
        assert db3D1(i) == db3D2(i)
    sqlexpression = "select * from MorseGraphAnnotations where MorseGraphIndex = ?"
    c = db3D1.cursor
    d = db3D2.cursor
    for i in range(177):
        c.execute(sqlexpression, (i,))
        ann1 = c.fetchall()
        d.execute(sqlexpression, (i,))
        ann2 = d.fetchall()
        assert ann1 == ann2
    subprocess.call("rm 3D_test.db",shell=True)
Exemple #28
0
def calculate_poset(params, networks):
    '''

    :param params: A dictionary with the keys
                    'timeseriesfname' : a .csv or .tsv file name
                    'tsfile_is_row_format' : True if time series are in rows, False if they are in columns.
                    "epsilons" : a list of noise values between 0.0 and 0.5

    :param networks:
    :return:
    '''
    data, times = readrow(params['timeseriesfname']
                          ) if params['tsfile_is_row_format'] else readcol(
                              params['timeseriesfname'])
    posets = {}
    new_networks = []
    missing_names = set([])
    for networkspec in networks:
        network = DSGRN.Network(networkspec)
        names = tuple(sorted([network.name(k) for k in range(network.size())]))
        missing_names = missing_names.union(
            set(name for name in names if name not in data))
        if set(names).intersection(missing_names):
            continue
        if names not in posets.keys():
            curves = [curve.Curve(data[name], times, True) for name in names]
            pos = make_posets.eps_posets(dict(zip(names, curves)),
                                         params["epsilons"])
            if pos is None:
                raise ValueError("poset is None!")
            posets[names] = pos
        new_networks.append(networkspec)
    return posets, new_networks, missing_names
Exemple #29
0
 def toggle_plus_additive(self):
     N = DSGRN.Network("X0 : (~X1)+(X0) \n X1:(~X0)+(X1)")
     L = np.array([[.25, .25], [.25, .25]])
     Delta = np.array([[2.1, 1], [1, 2.1]], dtype='float')
     theta = np.array([[2.1, 1.3], [1, 2.1]])
     gamma = np.array([[1], [1]])
     return N, L, Delta, theta, gamma
Exemple #30
0
 def three_node_network(self):
     N = DSGRN.Network("X0: X2 \n X1 : X0 \n X2 : X1")
     L = np.array([[0, 0, .5], [.5, 0, 0], [0, .5, 0]])
     Delta = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
     theta = [[0, 0, 1.4], [1, 0, 0], [0, 1, 0]]
     gamma = np.array([[1], [1], [1]])
     return N, L, Delta, theta, gamma