def make_plotplotly(results_json: str, *args, **kwargs) -> str: import plotly.io as plotlyio results = Results.from_json(results_json) plot = Results.plotplotly(results, return_plotly_figure=True, **kwargs) plot_json = plotlyio.to_json(plot) return plot_json
def test_to_csv_single_result_no_stamp(self): test_data = {'time': [0]} result = Results(data=test_data) test_nametag = "test_nametag" with tempfile.TemporaryDirectory() as tempdir: result.to_csv(nametag=test_nametag, path=tempdir) assert len(os.listdir(tempdir)) is not 0
def test_to_csv_single_result_no_data(self): result = Results(data=None) test_nametag = "test_nametag" test_stamp = "test_stamp" with tempfile.TemporaryDirectory() as tempdir: result.to_csv(stamp=test_stamp, nametag=test_nametag, path=tempdir) test_path = tempdir + "/" + test_nametag + test_stamp assert not os.path.isdir(test_path)
def test_to_csv_single_result_no_path(self): test_data = {'time': [0]} result = Results(data=test_data) test_nametag = "test_nametag" test_stamp = "test_stamp" with tempfile.TemporaryDirectory() as tempdir: os.chdir(tempdir) result.to_csv(stamp=test_stamp, nametag=test_nametag) assert len(os.listdir(tempdir)) is not 0
def test_to_csv_single_result_no_nametag(self): test_data = {'time': [0]} test_model = Model('test_model') result = Results(data=test_data, model=test_model) result.solver_name = 'test_solver' test_stamp = "test_stamp" with tempfile.TemporaryDirectory() as tempdir: result.to_csv(stamp=test_stamp, path=tempdir) assert len(os.listdir(tempdir)) is not 0
def test_to_csv_single_result_file_exists(self): test_data = {'time': [0]} result = Results(data=test_data) test_nametag = "test_nametag" test_stamp = "test_stamp" with tempfile.TemporaryDirectory() as tempdir: result.to_csv(stamp=test_stamp, nametag=test_nametag, path=tempdir) test_path = tempdir + "/" + test_nametag + test_stamp + "/" + test_nametag + ".csv" assert os.path.isfile(test_path)
def resolve(self) -> Results: """ Finish the remote job and return the results. This function will block until the remote job is complete. :returns: Results """ # Poll the job status until it finishes. while not self.__poll_job_status(): time.sleep(5) # Request the results of the finished job. results_response = self.server.get(Endpoint.RESULT, f"/{self.result_id}/get") if not results_response.ok: raise Exception(ErrorResponse.parse_raw(results_response.text).msg) print(f"Results size: {sys.getsizeof(results_response.content)}") results_json = bz2.decompress(results_response.content).decode() print(f"Expanded to: {sys.getsizeof(results_json)}") # Parse and return the response body into a valid Results object. results = Results.from_json(results_json) return results
def make_plot(memory_id: str): # Make sure we can grab a memory with this ID. if not delegate.job_complete(memory_id): status = delegate.job_status(memory_id) return status.status_text, 404 # Grab the memory. memory: Results = Results.from_json(delegate.job_results(memory_id)) # Swap the pyplot backend so the Results#plot call wont try to write to a GUI. pyplot.switch_backend("template") # Write the plot as a .png to the tempfile. _, temp = tempfile.mkstemp(suffix=".png") memory.plot(save_png=temp) # Read the contents of the temp file and cleanup. with open(temp, "rb") as infile: plot_bytes = infile.read() os.remove(temp) compressed_plot = bz2.compress(plot_bytes) response = make_response(compressed_plot) response.headers["Content-Encoding"] = "bzip2" return response, 200
def test_job(*args, **kwargs): data = [] for result in args: data = data + result.data from gillespy2.core import Results return Results(data)
def test_equality_of_named_results(self): """ Test that Model simulation results can be converted to JSON and back. """ for model in self.runnable_models: target = model() results = target.run() results_from = Results.from_json(results.to_json()) self.assertEquals(results.to_json(), results_from.to_json())
def test_equality_of_named_results(self): """ Test that anonymous Model simulation results can be converted to JSON and back. """ for model in self.runnable_models: target = model() results = target.run() results._translation_table = target.get_translation_table() results = results.to_anon().to_json() self.assertEqual(results, Results.from_json(results).to_json())
def join_results(results): # Save the dependent trajectories in memory. from distributed import get_client client = get_client() client.publish_dataset(dependencies, name=f"{model_id}-trajectories", override=True) data = [] for i, result in enumerate(results): with open(os.path.join(cache_dir, keys[i]), "w+") as outfile: outfile.write(result.to_json()) data = data + result.data from gillespy2.core import Results result_json = Results(data).to_json() with open(os.path.join(cache_dir, job_id), "w+") as outfile: outfile.write(result_json) return result_json
def __init__(self, result_id: str, server: ComputeServer): Results.__new__(Results) self.result_id = result_id self.server = server self.local_results = None
def run(self=None, model: Model = None, t: int = None, number_of_trajectories: int = 1, timeout: int = 0, increment: int = None, seed: int = None, debug: bool = False, profile: bool = False, variables={}, resume=None, live_output: str = None, live_output_options: dict = {}, **kwargs): from gillespy2 import log """ :param model: The model on which the solver will operate. (Deprecated) :type model: gillespy2.Model :param t: End time of simulation. :type t: int :param number_of_trajectories: The number of times to sample the chemical master equation. Each trajectory will be returned at the end of the simulation. By default number_of_trajectories = 1. :type number_of_trajectories: int :param timeout: If set, if simulation takes longer than timeout, will exit. :type timeout: int :param increment: Time step increment for plotting. :type increment: float :param seed: The random seed for the simulation. Optional, defaults to None. :type seed: int :param variables: Dictionary of species and their data that will override existing species data. :type variables: dict :param resume: Result of a previously run simulation, to be resumed. :type resume: gillespy2.Results :param live_output: The type of output to be displayed by solver. Can be "progress", "text", or "graph". :type live_output: str :param live_output_options: dictionary contains options for live_output. By default {"interval":1}. "interval" specifies seconds between displaying. "clear_output" specifies if display should be refreshed with each display. :type live_output_options: dict :returns: A result object containing the results of the simulation. :rtype: gillespy2.Results """ if self is None: # Post deprecation block # raise SimulationError("SSACSolver must be instantiated to run the simulation") # Pre deprecation block log.warning(""" `gillespy2.Model.run(solver=SSACSolver)` is deprecated. You should use `gillespy2.Model.run(solver=SSACSolver(model=gillespy2.Model)) Future releases of GillesPy2 may not support this feature. """) self = SSACSolver(model, resume=resume) if model is not None: log.warning( 'model = gillespy2.model is deprecated. Future releases ' 'of GillesPy2 may not support this feature.') if self.model is None: if model is None: raise SimulationError( "A model is required to run the simulation.") self._set_model(model=model) self.model.compile_prep() self.validate_model(self.model, model) self.validate_sbml_features(model=self.model) self.validate_tspan(increment=increment, t=t) if increment is None: increment = self.model.tspan[-1] - self.model.tspan[-2] if t is None: t = self.model.tspan[-1] # Validate parameters prior to running the model. self._validate_type(variables, dict, "'variables' argument must be a dictionary.") self._validate_resume(t, resume) self._validate_kwargs(**kwargs) if resume is not None: t = abs(t - int(resume["time"][-1])) number_timesteps = int(round(t / increment + 1)) args = { "trajectories": number_of_trajectories, "timesteps": number_timesteps, "end": t, "interval": str(number_timesteps), } if self.variable: populations = cutils.update_species_init_values( self.model.listOfSpecies, self.species, variables, resume) parameter_values = cutils.change_param_values( self.model.listOfParameters, self.parameters, self.model.volume, variables) args.update({ "init_pop": populations, "parameters": parameter_values }) seed = self._validate_seed(seed) if seed is not None: args.update({"seed": seed}) if live_output is not None: live_output_options['type'] = live_output display_args = { "model": self.model, "number_of_trajectories": number_of_trajectories, "timeline": np.linspace(0, t, number_timesteps), "live_output_options": live_output_options, "resume": bool(resume) } else: display_args = None args = self._make_args(args) decoder = IterativeSimDecoder.create_default( number_of_trajectories, number_timesteps, len(self.model.listOfSpecies)) sim_exec = self._build(self.model, self.target, self.variable, False) sim_status = self._run(sim_exec, args, decoder, timeout, display_args) if sim_status == SimulationReturnCode.FAILED: raise ExecutionError( "Error encountered while running simulation C++ file:\n" f"Return code: {int(sim_status)}.\n") trajectories, time_stopped = decoder.get_output() simulation_data = self._format_output(trajectories) if sim_status == SimulationReturnCode.PAUSED: simulation_data = self._make_resume_data(time_stopped, simulation_data, t) if resume is not None: simulation_data = self._update_resume_data(resume, simulation_data, time_stopped) self.result = simulation_data self.rc = int(sim_status) return Results.build_from_solver_results(self, live_output_options)
def results_to_json(results_json): results = Results.from_json(results_json) return results.average_ensemble().to_json()