예제 #1
0
 def reset_project(self):
     if self.use_rest:
         self.kappa_instance = kappy.KappaRest(KAPPA_URL,
                                               project_id=self.project_name)
         self.kappa_instance.get_info()
     else:
         self.kappa_instance = kappy.KappaStd()
    def simulation(self):
        """ Run a KaSim simulation on each model found in pop_dir.  """

        self.clear_previous()
        for surv in self.survivors:
            input_path = "{}/{}.ka".format(self.pop_dir, surv)
            print(
                "Skipping {} which was already simulated.".format(input_path))
        for model in self.new_model_list:
            input_path = "{}/{}.ka".format(self.pop_dir, model)
            kappa_file = open(input_path, "r").read()
            for sim_num in range(self.replicates):
                if self.replicates > 1:
                    letter_id = self.letters[sim_num]
                    replicate = "{}{}".format(model, letter_id)
                    print("Running simulation {} on {}.".format(
                        sim_num + 1, input_path))
                else:
                    replicate = model
                    print("Running simulation on {}.".format(input_path))
                client = kappy.KappaStd()
                client.add_model_string(kappa_file)
                client.project_parse()
                sim_params = kappy.SimulationParameter(
                    pause_condition="[T] > {}".format(self.sim_time),
                    plot_period=self.out_period)
                client.simulation_start(sim_params)
                while client.get_is_sim_running():
                    time.sleep(0.1)
                results = client.simulation_plot()
                # Write simulation results to output file.
                self.write_output(replicate, results)
                client.shutdown()
예제 #3
0
def _prepare_kappa(model):
    """Return a Kappa STD with the model loaded."""
    import kappy
    kappa = kappy.KappaStd()
    model_str = export(model, 'kappa')
    kappa.add_model_string(model_str)
    kappa.project_parse()
    return kappa
예제 #4
0
파일: mra.py 프로젝트: djmilstein/bioagents
def make_contact_map(pysb_model):
    """Return a Kappa contact map."""
    kappa = kappy.KappaStd()
    model_str = export(pysb_model, 'kappa')
    kappa.add_model_string(model_str)
    kappa.project_parse()
    cmap = kappa.analyses_contact_map()
    cm = cm_json_to_graph(cmap)
    return cm
예제 #5
0
 def __init__(self, project_name=None, debug=False, use_rest=False):
     """Create a Kappa client."""
     if debug:
         logger.setLevel(DEBUG)
     if use_rest:
         self.kappa_instance = kappy.KappaRest(KAPPA_URL,
                                               project_id=project_name)
         self.kappa_instance.get_info()
     else:
         self.kappa_instance = kappy.KappaStd()
     return
예제 #6
0
def make_influence_map(pysb_model):
    """Return a Kappa influence map."""
    kappa = kappy.KappaStd()
    model_str = export(pysb_model, 'kappa')
    kappa.add_model_string(model_str)
    kappa.project_parse()
    imap = kappa.analyses_influence_map()
    im = im_json_to_graph(imap)
    for param in pysb_model.parameters:
        try:
            im.remove_node(param.name)
        except:
            pass
    return im
예제 #7
0
파일: sim.py 프로젝트: ptti/lmic-testing
    def __call__(self, params):
        ## assemble the model
        kasim = kappy.KappaStd()
        ## variable declarations for those that are fixed for this simulation
        kasim.add_model_string(self.fixed_vars, 1, file_id="fixed")
        ## variable declarations for those that we are trying to fit
        fit_vars = "\n".join("%var: {} {}".format(k, v)
                             for k, v in params.items())
        kasim.add_model_string(fit_vars, 2, file_id="fit")
        ## model files
        for i, f in enumerate(self.model_files):
            kasim.add_model_file(f, i + 3)
        kasim.project_parse()

        ## conduct the simulation
        meta = kappy.SimulationParameter(self.stepsize,
                                         "[T] > {}".format(self.tmax))
        kasim.simulation_start(meta)
        kasim.wait_for_simulation_stop()
        plot = kasim.simulation_plot()
        ## make the result usable
        df = pd.DataFrame(np.array(plot["series"])[::-1, :],
                          columns=plot["legend"])

        ## compute R(t) according to S9.3 of
        ## https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6002118
        N = self.fixed["N"]
        t = df["[T]"]
        Sn = df["Sn"]
        In = df["In"]
        I = df["In"] + df["Iy"]
        c = df["contact"]
        n = len(df)

        X = np.zeros(len(I))
        np.true_divide(Sn * In, I, out=X, where=I != 0)
        ker = np.exp(-0.14 * t)
        bcs = params["beta"] * c * X

        R = []
        for i, tau in enumerate(t):
            s = np.pad(bcs, (n - i - 1, 0), mode="edge")
            R.append(np.trapz(s[:n] * ker[::-1] / N, t))
        df["R"] = np.array(R)

        ## done
        return df
예제 #8
0
    def generate_im(self, model):
        """Return a graph representing the influence map generated by Kappa

        Parameters
        ----------
        model : pysb.Model
            The PySB model whose influence map is to be generated

        Returns
        -------
        graph : networkx.MultiDiGraph
            A MultiDiGraph representing the influence map
        """
        kappa = kappy.KappaStd()
        model_str = export.export(model, 'kappa')
        kappa.add_model_string(model_str)
        kappa.project_parse()
        imap = kappa.analyses_influence_map(accuracy='medium')
        graph = im_json_to_graph(imap)
        return graph
예제 #9
0
    def run(self, t0, tmax, steps, kappa_text):
        """
        For the Kappa model, the state is simply the Kappa text
        """
        stepsize = (tmax - t0) / steps

        client = kappy.KappaStd()
        client.add_model_string(kappa_text)
        client.project_parse()

        client.simulation_start(
            kappy.SimulationParameter(stepsize, "[T] > {0}".format(tmax - t0)))
        client.wait_for_simulation_stop()

        plot = client.simulation_plot()
        series = np.array(plot["series"])[::-1, :]

        t = series[:, 0]
        traj = series[:, 1:]

        ## Kappa will stop running when no more events are possible,
        ## so pad to the end
        skipped = steps - traj.shape[0]
        if skipped > 0:
            maxt = max(t)
            stepsize = (tmax - t0) / steps
            t = np.hstack(
                [t, np.linspace(t[-1] + stepsize, tmax - t0, skipped)])
            traj = np.pad(traj, ((0, skipped), (0, 0)), "edge")

        ## correct time-series because Kappa always starts at 0
        t = t + t0

        ## construct a new Kappa program to support exogeneous interventions
        last = traj[-1]
        onames = [o["name"] for o in self.observables]
        init = dict((o, last[self.colindex(o)]) for o in onames)
        N = np.sum(last[i] for i in self.pcols[:8])
        kappa_text = self.initial_conditions(N, **init)

        return t, traj, kappa_text
예제 #10
0
def simulate(model, limit=100000, plot=100, facts=[], rules=[], **kw):
    try:
        temp = tempfile.NamedTemporaryFile(delete=False)
        temp.file.write(bytes(model, "utf-8"))
        temp.file.close()

        program = compile(temp.name, facts=facts, rules=rules).decode("utf-8")

        client = kappy.KappaStd()
        client.set_default_sim_param(plot, "[T] > %d" % limit)
        client.add_model_string(program)
        client.project_parse()
        client.simulation_start()
        client.wait_for_simulation_stop()
        data = client.simulation_plot(kappy.PlotLimit(points=int(limit /
                                                                 plot)))
        data["kappa"] = program
        client.simulation_delete()
        return data
    finally:
        os.unlink(temp.name)
예제 #11
0
def run_sim(params):
    client = kappy.KappaStd()

    with open('base_model.ka', 'r') as file:
        model = file.read()

    for species in ['NAD', 'DNA', 'PARP', 'PARG']:
        model = model.replace("init: _ " + species,
                              "init: " + str(params[species]) + " " + species)

    for rate in ['base_rev', 'base_fwd', 'catalysis_rate', 'cut_rate']:
        model = model.replace("'" + rate + "' _",
                              "'" + rate + "' " + str(params[rate]))

    model = model.replace(
        "mod: ([E] [mod] _ )=0",
        "mod: ([E] [mod] " + str(params['time'] / 100) + " )=0")

    client.add_model_string(model)
    client.project_parse()
    sim_params = kappy.SimulationParameter(pause_condition="[T] > " +
                                           str(params['time']),
                                           plot_period=params['time'] / 10)
    client.simulation_start(sim_params)
    client.wait_for_simulation_stop()
    results = client.simulation_plot()
    snaps = client.simulation_snapshots()
    snap = client.simulation_snapshot(snaps['snapshot_ids'][0])

    #for i in rng(snaps['snapshot_ids']):
    #	snap  = client.simulation_snapshot(snaps['snapshot_ids'][i])
    #	if snap != []:
    #		break

    client.simulation_delete()
    client.shutdown()

    return snap
예제 #12
0
import kappy

client = kappy.KappaStd()

with open('base_model.ka', 'r') as file:
    model = file.read()

client.add_model_string(model)
client.project_parse()
sim_params = kappy.SimulationParameter(pause_condition="[T] > " +
                                       str(params['iterations']),
                                       plot_period=1)
client.simulation_start(sim_params)
client.wait_for_simulation_stop()
results = client.simulation_plot()
snaps = client.simulation_snapshots()
snap = client.simulation_snapshot(snaps['snapshot_ids'][0])
client.simulation_delete()
client.shutdown()


def get_branch_number(graph):
    counter = 0
    for agent in graph[1]:
        for node_site in agent['node_sites']:
            if node_site['site_name'] == 'branch' and node_site['site_type'][
                    1]['port_links']:
                #if branch site is not empty
                counter += 1
    return counter
예제 #13
0
import kappy

# Modify the path according to the location of the kappa agent on your system
p_thibaut = "../../Kappapp/resources/bin"

path_to_agent = p_thibaut

#creation du client
client = kappy.KappaStd(path_to_agent)

#choice of model
f = open("turing_model.ka", "r")
model = f.read()
f.close()

f = open("turing_rules.ka", "r")
rules = f.read()
f.close()

f = open("turing_init_test.ka", "r")
init = f.read()
f.close()

client.add_model_string(model)
client.add_model_string(rules)
client.add_model_string(init)
client.project_parse()

#do stuff

client.shutdown()
예제 #14
0
 def getRuntime(self):
     return kappy.KappaStd(BIN_DIR)
예제 #15
0
def main():
    # command line
    argv = sys.argv[1:]
    cmd = "kappa_client.py"

    # default arguments
    inputfile = None  # if missing input file just get version
    url = None
    pause_condition = "[false]"
    plot_period = 0.1
    seed = None

    help_line = (cmd +
                 ' -k <kappafile> ' +
                 ' -u <url or path to stdsim> ' +
                 ' -t <max_time> ' +
                 ' -e <max_events> ' +
                 ' -pp <plot_period> ' +
                 ' -s <random_seed> ')
    try:
        opts, args = getopt.getopt(argv,
                                   "h:k:u:t:e:pp:s",
                                   ["help","kappafile=",
                                    "url=",
                                    "max_time=",
                                    "max_event=",
                                    "plot_period=",
                                    "seed="])
    except:
        print(help_line)

        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print(help_line)
            sys.exit()
        elif opt in ("-k", "--kappafile"):
            inputfile = arg
        elif opt in ("-u", "--url"):
            url = arg
        elif opt in ("-t", "--max_time"):
            pause_condition = "[T]>"+arg+" || "+pause_condition
        elif opt in ("-e", "--max_events"):
            pause_condition = "[E]>"+arg+" || "+pause_condition
        elif opt in ("-pp", "--plot_period"):
            plot_period = float(arg)
        elif opt in ("-s", "--seed"):
            seed = int(arg)

    print('Input file is : {0} '.format(inputfile))
    print('Endpoint url : {0} '.format(url))
    print('Pause conditon : {0}'.format(pause_condition))
    print('Plot period : {0} '.format(plot_period))
    print('Random seed : {0} '.format(seed))

    try:
        project_id = "{0}-{1}".format(cmd,str(uuid.uuid1()))
        if url and url.startswith('http'):
            runtime = kappy.KappaRest(url,project_id)
        else:
            runtime = kappy.KappaStd(url)
        print("project_id : {0}".format(project_id))
        if inputfile:
            with open(inputfile) as f:
                code = f.read()
                file_content = str(code)
                file_metadata = kappy.FileMetadata(inputfile,0)
                file_object = kappy.File(file_metadata,file_content)
                runtime.file_create(file_object)
                runtime.project_parse()

                end_time = 10.0
                simulation_parameter = kappy.SimulationParameter(plot_period,
                                                                 pause_condition,
                                                                 seed)
                runtime.simulation_start(simulation_parameter)

                simulation_info = runtime.simulation_info()

                while simulation_info["simulation_info_progress"]["simulation_progress_is_running"] :
                    time.sleep(1)

                    percentage = ""
                    time_percentage = simulation_info["simulation_info_progress"]["simulation_progress_time_percentage"]
                    event_percentage = simulation_info["simulation_info_progress"]["simulation_progress_event_percentage"]

                    if time_percentage or time_percentage == 0 :
                        percentage = time_percentage
                    if event_percentage or event_percentage == 0 :
                        percentage = event_percentage

                    sys.stdout.write("..{0}.. ".format(percentage))
                    sys.stdout.flush()
                    simulation_info = runtime.simulation_info()

                print("")
                print("info")
                print(simulation_info)
                plot_detail = runtime.simulation_plot()
                print("plot")
                print(plot_detail)
        else:
            print(runtime.get_info())
    except kappy.KappaError as exception:
        print(exception.errors)
    return None
    None
예제 #16
0
 def getRuntime(self, project_id):
     return (kappy.KappaStd(KAPPA_BIN))