Ejemplo n.º 1
0
def mutate_model(model, circuit, database):
    #    logging.info("mutate: circuit is %s", circuit)
    nmodel = Graph()
    nmodel += model

    i = choice(range(len(circuit)))
    #    logging.info("mutate: replacing part %d: %s", i, circuit[i])

    try:
        part = replace_part(nmodel, circuit, i, database)
    except Exception as e:
        dump_graph(model)
        raise e
    ncircuit = circuit.copy()
    ncircuit[i] = part

    ## fixup the "next" linkage for RBS
    if exists(nmodel, (part, GCC["next"], None)):
        _, _, next = get_one(nmodel, (part, GCC["next"], None))
        _, _, label = get_one(nmodel, (circuit[i + 1], GCC["part"], None))
        nmodel.remove((part, GCC["next"], next))
        nmodel.add((part, GCC["next"], label))

#    logging.info("mutate: repacement part is %s", circuit[i])
    return (nmodel, ncircuit)
Ejemplo n.º 2
0
def compile_stage2(ir, debug=False, **kw):
    """
    Translate the transitive closure of data, model under inference rules
    into a simple python dictionary that can be dealt with by Jinja2
    """
    logging.info("stage2: generating python representation")
    ir2 = {"circuits": []}

    model, _, _ = get_one(ir, (None, RDF["type"], RBMO["Model"]))

    _, _, prefix = get_one(ir, (model, RBMC["prefix"], None))
    ir2["prefix"] = prefix.toPython()

    for _, _, parts in ir.triples((model, RBMC["linear"], None)):
        circuit = list(
            map(lambda x: describe_part(ir, x), Collection(ir, parts)))
        ir2["circuits"].append({"topology": "linear", "parts": circuit})

    for _, _, parts in ir.triples((model, RBMC["circular"], None)):
        circuit = list(
            map(lambda x: describe_part(ir, x), Collection(ir, parts)))
        ir2["circuits"].append({"topology": "circular", "parts": circuit})

    logging.debug("=" * 80)
    logging.debug("stage2: output")
    logging.debug("-" * 80)
    from pprint import pformat
    for line in pformat(ir2).split("\n"):
        logging.debug(line)
    logging.debug("=" * 80)

    return ir2
Ejemplo n.º 3
0
 def parts():
     for _, _, pl in g.triples((m, GCC["linear"], None)):
         ps = Collection(g, pl)
         for p in ps:
             _, _, label = get_one(g, (p, GCC["part"], None))
             yield str(label)
     for _, _, pl in g.triples((m, GCC["circular"], None)):
         ps = Collection(g, pl)
         for p in ps:
             _, _, label = get_one(g, (p, GCC["part"], None))
             yield str(label)
Ejemplo n.º 4
0
def gen_model(model, database):
    circuit = extract_circuit(model, database)
    proto = extract_proto(model)
    ## the "next" linkage for RBS needs to be fixed up in the model.
    for i in range(len(circuit)):
        part = circuit[i]
        if exists(model, (part, GCC["next"], None)):
            _, _, next = get_one(model, (part, GCC["next"], None))
            _, _, label = get_one(model, (circuit[i + 1], GCC["part"], None))
            model.remove((part, GCC["next"], next))
            model.add((part, GCC["next"], label))
    return (model, circuit)
Ejemplo n.º 5
0
def add_defaults(g, part):
    for _, _, kind in g.triples((URIRef(part["uri"]), RDF["type"], None)):
        for _, _, token in g.triples((kind, RBMC["tokens"], None)):
            try:
                _, _, label = get_one(g, (token, SKOS["prefLabel"], None))
            except Exception as e:
                logging.error("could not find label for %s" % token)
                raise
            if label.toPython() in part:
                continue
            if exists(g, (token, RBMC["default"], None)):
                _, _, default = get_one(g, (token, RBMC["default"], None))
                part[label.toPython()] = default.toPython()
    return part
Ejemplo n.º 6
0
def extract_proto(model):
    """
    Extract circuit prototype -- the list of part types that make up the circuit
    """
    mid, _, _ = get_one(model, (None, RDF["type"], RBMO["Model"]))
    if (mid, GCC["linear"], None) in model:
        _, _, cid = get_one(model, (mid, GCC["linear"], None))
    elif (mid, GCC["circular"], None) in model:
        _, _, cid = get_one(model, (mid, GCC["circular"], None))
    proto = []
    for part in Collection(model, cid):
        _, _, kind = get_one(model, (part, RDF["type"], None))
        proto.append(kind)
    return proto
Ejemplo n.º 7
0
def describe_operators(g, oplist):
    operators = []
    oplist = Collection(g, oplist)
    for desc in oplist:
        state = {}
        if exists(g, (desc, RDF["type"], RBMO["BoundState"])):
            state["bound"] = True
        elif exists(g, (desc, RDF["type"], RBMO["UnboundState"])):
            state["bound"] = False
        if exists(g, (desc, RBMO["stateOf"], None)):
            _, _, operator = get_one(g, (desc, RBMO["stateOf"], None))
            _, _, label = get_one(g, (operator, SKOS["prefLabel"], None))
            state["site"] = label.toPython()
        operators.append(state)
    return operators
Ejemplo n.º 8
0
def extract_circuit(model, database):
    """
    Extract the list of parts that make up the circuit, filling in any that
    are identified with blank nodes randomly.
    """
    mid, _, _ = get_one(model, (None, RDF["type"], RBMO["Model"]))
    if (mid, GCC["linear"], None) in model:
        _, _, cid = get_one(model, (mid, GCC["linear"], None))
    elif (mid, GCC["circular"], None) in model:
        _, _, cid = get_one(model, (mid, GCC["circular"], None))

    circuit = list(Collection(model, cid))
    for i in range(len(circuit)):
        part = circuit[i]
        if isinstance(part, BNode):
            circuit[i] = replace_part(model, circuit, i, database)
    return circuit
Ejemplo n.º 9
0
def describe_part(g, parturi):
    """
    Emit a Python dictionary with a description of a single part,
    used by the second-stage compiler.
    """
    def literal(v):
        v = v.toPython()
        if isinstance(v, str):
            return v
        return "%.16f" % v

    part = {"uri": parturi.toPython()}
    try:
        _, _, template = get_one(g, (parturi, RBMC["kappaTemplate"], None))
    except Exception as e:
        logging.error("%s could not find template" % (parturi, ))
        raise e

    part["template"] = template.toPython()
    for _, _, replace in g.triples((parturi, RBMC["replace"], None)):
        try:
            _, _, token = get_one(g, (replace, RBMC["string"], None))
        except Exception as e:
            logging.error("%s could not find replacement token" % (parturi, ))
            raise e

        try:
            _, _, value = get_one(g, (replace, RBMC["value"], None))
        except Exception as e:
            logging.error("%s could not find value for %s" % (parturi, token))
            raise

        if isinstance(value, Literal):
            part[token.toPython()] = literal(value)
            continue
        if exists(g, (value, SKOS["prefLabel"], None)):
            _, _, label = get_one(g, (value, SKOS["prefLabel"], None))
            part[token.toPython()] = label.toPython()
            continue

        ## if we are here, we are concerned with the states of operators
        data = {}
        replace = value
        _, _, value = get_one(g, (replace, RBMC["value"], None))
        data["value"] = literal(value)
        if exists(g, (replace, RBMC["upstream"], None)):
            _, _, oplist = get_one(g, (replace, RBMC["upstream"], None))
            data["upstream"] = list(reversed(describe_operators(g, oplist)))
        if exists(g, (replace, RBMC["downstream"], None)):
            _, _, oplist = get_one(g, (replace, RBMC["downstream"], None))
            data["downstream"] = describe_operators(g, oplist)

        data["upstream_size"] = len(data.get("upstream", []))
        data["downstream_size"] = len(data.get("downstream", []))
        data["context_size"] = data["upstream_size"] + data[
            "downstream_size"] + 1

        part.setdefault(token.toPython(), []).append(data)

    return add_defaults(g, part)
Ejemplo n.º 10
0
def compile_stage5(g, docs, **kw):
    """
    Derive initialisation for genetic circuits present
    in the model
    """
    model, _, _ = get_one(g, (None, RDF["type"], RBMO["Model"]))
    for _, _, inc in g.triples((model, RBMC["include"], None)):
        logging.info("stage5: including %s" % inc)
        fp = create_input_source(inc.toPython()).getByteStream()
        doc = fp.read()
        fp.close()
        docs.insert(0, doc)
    return docs
Ejemplo n.º 11
0
def name_model(g):
    m, _, _ = get_one(g, (None, RDF["type"], RBMO["Model"]))

    def parts():
        for _, _, pl in g.triples((m, GCC["linear"], None)):
            ps = Collection(g, pl)
            for p in ps:
                _, _, label = get_one(g, (p, GCC["part"], None))
                yield str(label)
        for _, _, pl in g.triples((m, GCC["circular"], None)):
            ps = Collection(g, pl)
            for p in ps:
                _, _, label = get_one(g, (p, GCC["part"], None))
                yield str(label)

    name = "_".join(parts())
    return name
Ejemplo n.º 12
0
def replace_part(model, circuit, idx, database):
    """
    Replace the part in the model at the given index
    """
    part = circuit[idx]
    #dump_graph(model)
    _, _, kind = get_one(model, (part, RDF["type"], None))
    sremove = list(model.triples((part, None, None)))
    oreplace = list(model.triples((None, None, part)))
    for triple in sremove:
        model.remove(triple)
    for triple in oreplace:
        model.remove(triple)
    pid_ = get_random_part(database, kind)
    pid = URIRef(pid_ + ascii_letters[idx])

    ## put in statements with renamed new part as subject
    ## and alpha-rename any blank nodes
    bnodes = {}
    for s, p, o in cbd(database, (pid_, None, None)):
        if s == pid_: s = pid
        elif isinstance(s, BNode):
            if s not in bnodes:
                bnodes[s] = BNode()
            s = bnodes[s]
        if p == GCC["part"]:
            o = Literal(o + ascii_letters[idx])
        elif p == RBMO["stateOf"]:
            ### fix to support multi-operators
            o = circuit[idx - 1]
        if isinstance(o, BNode):
            if o not in bnodes:
                bnodes[o] = BNode()
            o = bnodes[o]
        model.add((s, p, o))
    ## link in to statements referring to old part
    for s, p, _ in oreplace:
        model.add((s, p, pid))
    return pid