|
| 1 | +''' |
| 2 | +PRMS-Python: Powerful, sane tools for manipulating PRMS input data to create |
| 3 | +new scenarios or parameterizations for sensitivity analysis, scenario |
| 4 | +modeling, or whatever other uses this might have. |
| 5 | +
|
| 6 | +The fundamental process in scenario development is to modify some "base" |
| 7 | +starting data to create some "scenario" data. No matter what data we're using, |
| 8 | +once it's ready, we run a PRMS "simulation" on that data. |
| 9 | +
|
| 10 | +This module presents a Simulation and Scenario class, where each tracks |
| 11 | +relevant provenance information and input files to facilitate better |
| 12 | +data management techniques to streamline later analyses. |
| 13 | +''' |
| 14 | +import os |
| 15 | +import subprocess |
| 16 | + |
| 17 | + |
| 18 | +class Simulation(object): |
| 19 | + """ |
| 20 | + Simulation class for tracking the inputs and outputs of a single |
| 21 | + PRMS simulation. |
| 22 | + """ |
| 23 | + def __init__(self, simulation_dir): |
| 24 | + """ |
| 25 | + Create a new Simulation object from a simulation directory. Check that |
| 26 | + all required PRMS inputs (control, parameters, data) exist in the |
| 27 | + expected locations. |
| 28 | +
|
| 29 | + Also parses the control file to make sure that the data and parameter |
| 30 | + file specified match the ones in the simulation_dir |
| 31 | +
|
| 32 | + Arguments: |
| 33 | + simulation_dir (str): location of control, parameter, and data |
| 34 | + files for the Simulation |
| 35 | + """ |
| 36 | + sd = simulation_dir |
| 37 | + |
| 38 | + self.control = os.path.join(sd, 'control') |
| 39 | + self.parameter = os.path.join(sd, 'parameter') |
| 40 | + self.data = os.path.join(sd, 'data') |
| 41 | + |
| 42 | + if not os.path.exists(self.control): |
| 43 | + raise RuntimeError('Control file missing from ' + sd) |
| 44 | + |
| 45 | + if not os.path.exists(self.parameter): |
| 46 | + raise RuntimeError('Parameter file missing from ' + sd) |
| 47 | + |
| 48 | + if not os.path.exists(self.data): |
| 49 | + raise RuntimeError('Data file missing from ' + sd) |
| 50 | + |
| 51 | + self.has_run = False |
| 52 | + |
| 53 | + def run(self): |
| 54 | + |
| 55 | + prms_finished = False |
| 56 | + while not prms_finished: |
| 57 | + |
| 58 | + p = subprocess.Popen( |
| 59 | + 'prms ' + self.control, shell=True, |
| 60 | + stdout=subprocess.PIPE, stderr=subprocess.PIPE |
| 61 | + ) |
| 62 | + |
| 63 | + p.communicate() |
| 64 | + |
| 65 | + poll = p.poll() |
| 66 | + prms_finished = poll != 0 |
| 67 | + |
| 68 | + self.has_run = True |
| 69 | + |
| 70 | + def visualize(self): |
| 71 | + |
| 72 | + if not self.has_run: |
| 73 | + raise RuntimeError( |
| 74 | + 'You must first run the model before performing visualizations' |
| 75 | + ) |
| 76 | + |
| 77 | + return None |
0 commit comments