示例#1
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)
示例#2
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)
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()
示例#4
0
def PathMatches_with_count_stablefc_only(network, posets, N):
    '''
    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 N: network identifying integer
    :return: dictionary of results
    '''
    if len(posets) > 1:
        totalFC = {"all": {str(eps[0]) : set() for eps in posets[next(iter(posets))]} }
    numFCMatch = { tsfile : {str(eps[0]) : 0 for eps in poset_list} for tsfile,poset_list in posets.items()}
    paramgraph = DSGRN.ParameterGraph(network)
    # make DSGRN database to pull out stable FC parameters
    specfile = "temp{}.txt".format(N)
    dbfile = "temp{}.db".format(N)
    open(specfile,"w").write(network.specification())
    make_db(specfile,dbfile)
    params = DSGRN.StableFCQuery(DSGRN.Database(dbfile)).matches()
    os.remove(specfile)
    os.remove(dbfile)
    for paramind in params:
        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))
                stabmatch, _ = stableFC_check(domaingraph,patterngraph)
                if stabmatch:
                    numFCMatch[tsfile][str(eps)]+=1
                    if len(posets) > 1:
                        totalFC["all"][str(eps)].add(paramind)
    fcmatches = {tsfile : [(float(eps),count,len(params),paramgraph.size()) for eps,count in edict.items()] for tsfile,edict in numFCMatch.items()}
    if len(posets)>1:
        fcmatches.update({"all" : [(float(eps),len(totalFC["all"][eps]),len(params),paramgraph.size()) for eps in totalFC["all"]]})
    return {},fcmatches
def do_all_queries(dbname,
                   in1,
                   topval1,
                   in2,
                   topval2,
                   out,
                   topvalout,
                   print_output=False):
    '''
    Take a database and record the parameters for each of the possible 16 truth tables for two inputs.

    :param dbname: String with the file name of a precomputed database via mpiexec Signatures.
    :param in1: String with the name of the first input node.
    :param topval1: The highest state (integer) that the input node can achieve.
    :param in2: Name of second input.
    :param topval2: Highest value of the second input.
    :param out: String with the name of the output variable.
    :param topvalout: Highest value of the output variable.
    :param print_output: True or False. Print the output for each truth table in pretty format

    :return: File names where the results are deposited. The keys to each json dictionary are
             integers that link truth tables in one file to parameters in the second file.
    '''
    database = DSGRN.Database(dbname)
    names = [database.names[k] for k in range(database.D)]
    for n in [in1, in2, out]:
        if n not in names:
            raise ValueError(
                "{} is not a variable in the network for {}".format(n, dbname))
    truthtables = truth_table_constructor_2in(in1, topval1, in2, topval2, out,
                                              topvalout)
    all_matches = []
    lengths = []
    for bounds in truthtables:
        matches = truth_table_query(database, bounds)
        all_matches.append(sorted(list(matches)))
        lengths.append(len(matches))
    np = database.parametergraph.size()
    if print_output:
        for l, tt in sorted(zip(lengths, truthtables),
                            key=lambda t: t[0],
                            reverse=True):
            if l > 0:
                print(
                    "Parameters with specified truth table: {}/{} = {:.2f}%\n".
                    format(l, np, l / np * 100))
                print(format_truth_table(tt, in1, in2, out))
    sum_file = 'summary_{}.json'.format(dbname[:-3])
    param_file = 'params_{}.json'.format(dbname[:-3])
    D = {"database": dbname, "num_params": np}
    D.update({k: (l, t) for (k, t), l in zip(enumerate(truthtables), lengths)})
    json.dump(D, open(sum_file, 'w'))
    json.dump({k: a for k, a in enumerate(all_matches)}, open(param_file, 'w'))
    return sum_file, param_file
def query(network_file,params_file,resultsdir=""):
    '''
    :param network_file: a .txt file containing either a single DSGRN network specification or a list of network specification strings in DSGRN format
    :param params_file: A json file with the keys
            "num_proc" = number of processes to use for each database creation
            "count" = True or False (true or false in .json format)
                        whether or not to return the number of matches (True) or just whether or not there is at least one match (False)
            "datetime" : optional datetime string to append to subdirectories in resultsdir, default = system time
    :param resultsdir: optional path to directory where results will be written, default is current directory

    :return: Writes a .json file containing a dictionary keyed by DSGRN network specification with a list of results.
            The results are DSGRN parameter count that have at least one Morse set that is a stable full cycle,
            or True (existence of at least one stable full cycle) or False (none exist), depending on the value of the parameter "count".
            The size of the DSGRN parameter graph for the network is also recorded.
            { networkspec : [result, DSGRN param graph size] }.
    '''

    networks = read_networks(network_file)
    params = json.load(open(params_file))
    datetime = None if "datetime" not in params else params["datetime"]
    if not networks:
        raise ValueError("No networks available for analysis. Make sure network file is in the correct format.")
    else:
        num_proc, count = sanity_check(params)
        results = {}
        for k,netspec in enumerate(networks):
            netfile = "temp{}.txt".format(k)
            dbfile = "temp{}.db".format(k)
            if os.path.exists(dbfile):
                os.remove(dbfile)
            with open(netfile,"w") as f:
                f.write(netspec)
            subprocess.check_call("mpiexec -n {} Signatures {} {}".format(num_proc,netfile,dbfile),shell=True)
            db = DSGRN.Database(dbfile)
            N = db.parametergraph.size()
            matches = len(DSGRN.StableFCQuery(db).matches())
            if count:
                results[netspec] = (matches,N)
            else:
                results[netspec] = (matches > 0, N)
            subprocess.call(["rm",netfile])
            subprocess.call(["rm",dbfile])
            print("Network {} of {} complete".format(k + 1, len(networks)))
            sys.stdout.flush()
        record_results(network_file,params_file,results,resultsdir,datetime)
示例#7
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 10:57:44 2019

@author: g91k227
"""

import DSGRN
import sqlite3
from DSGRN.Query.Logging import LogToSTDOUT

database = DSGRN.Database(
    '/home/local/MSU/g91k227/DSGRN/networks/start_wavepool.db')
mgis = [i for i in range(5)]

stable_fc_query_object = DSGRN.StableFCQuery(database)
stableFC_list = [l for l in stable_fc_query_object.matches()]

conn = sqlite3.connect(
    '/home/local/MSU/g91k227/DSGRN/networks/start_wavepool.db')
cursor = conn.cursor()

bistablequery = 'select MorseGraphIndex from (select MorseGraphIndex, count(*) as StableCount from (select MorseGraphIndex,Vertex from MorseGraphVertices except select MorseGraphIndex,Source from MorseGraphEdges) group by MorseGraphIndex) where StableCount=2;'
bistable_mgi = set([row[0] for row in cursor.execute(bistablequery)])
#bistable_mgi = cursor.fetchall()

piseBS = 'select ParameterIndex from Signatures where MorseGraphIndex in {}'.format(
    tuple(bistable_mgi))
cursor2 = conn.cursor()
paramsBS = set([row[0] for row in cursor2.execute(piseBS)])