def start_sim(self, **parameters):
        """Start a simulation with given parameters.

        Note that parameters are subject to changes in the kappa remote api.

        Parameters
        ----------
        plot_period : int or float
            The time period between output (plot) points returned by the
            simulation. Default: 10
        pause_condition : string or None
            A Kappa Boolean expression defining a pause condition for the
            simulation. Default: None
        seed: int
            A random seed for the stochastic simulation. Default: None
        store_trace : bool
            Presumably you can choose whether to store the trace. Hopefully
            interpretation is straightforward. Default: True
        """
        complete_params = {
            'plot_period': 10,
            'pause_condition': '[false]',
            'seed': None,
            'store_trace': True
        }
        complete_params.update(parameters)
        sim_params = kappy.SimulationParameter(**complete_params)
        self.kappa_instance.simulation_start(sim_params)
    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()
Beispiel #3
0
    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
Beispiel #4
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
Beispiel #5
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
Beispiel #6
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
Beispiel #7
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
Beispiel #8
0
    def test_run_simulation(self):
        project_id = str(uuid.uuid1())
        runtime = self.getRuntime(project_id)
        file_id = str(uuid.uuid1())
        with open("../models/abc-pert.ka") as kappa_file:
            data = kappa_file.read()
            file_content = str(data)
            file_metadata = kappy.FileMetadata(file_id, 0)
            file_object = kappy.File(file_metadata, file_content)
            runtime.file_create(file_object)
            runtime.project_parse()
            pause_condition = "[T] > 10.0"
            simulation_parameter = kappy.SimulationParameter(
                0.1, pause_condition)
            runtime.simulation_start(simulation_parameter)

            simulation_info = runtime.simulation_info()

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

            # test that no limit returns all entries
            last_status = runtime.simulation_plot()
            test_count = 101
            self.assertEqual(test_count, len(last_status['series']))

            print(simulation_info)
            plot_limit_offset = 100
            test_time = 10.0
            test_count = 1
            limit = kappy.PlotLimit(plot_limit_offset)
            last_status = runtime.simulation_plot(limit)
            self.assertEqual(test_count, len(last_status['series']))
            self.assertEqual(test_time, last_status['series'][0][0])

            plot_limit_offset = 10
            plot_limit_points = 1
            test_time = 1.0
            test_count = 1
            limit = kappy.PlotLimit(plot_limit_offset, plot_limit_points)
            last_status = runtime.simulation_plot(limit)
            self.assertEqual(test_count, len(last_status['series']))
            self.assertEqual(test_time, last_status['series'][0][0])

            plot_limit_offset = 50
            test_time = 10.0
            test_count = 51
            limit = kappy.PlotLimit(plot_limit_offset)
            last_status = runtime.simulation_plot(limit)
            self.assertEqual(test_count, len(last_status['series']))
            self.assertEqual(test_time, last_status['series'][0][0])

            runtime.simulation_continue("[T] > 35")

            simulation_info = runtime.simulation_info()

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

            # test that no limit returns all entries
            last_status = runtime.simulation_plot()
            self.assertEqual(351, len(last_status['series']))