facade module

Facade module.

Front-end of the model. Coordinate model simulations and handle the model output.

Required installation

  • Anaconda for matplotlib and numpy for chart plotting
  • progressbar2 (run pip install progresbar2) for showing model run progress
  • xlwings (run pip install xlwings) for running Excel macros

Author - Christopher Teh Boon Sung


Facade class

Facade class.

Coordinate model simulations, show the progress of a model run, format and write model simulation results to a file, trace a program flow, model debugging, and export model results into Excel for further data processing and plotting.

ATTRIBUTES

  • fname_in (str): file name and path for model input parameters
  • fname_out (str): file name and path for model simulation results
  • fname_aux (str): file name and path for auxiliary simulation results (for debugging)
  • fout (io.TextIOWrapper): file object for daily data results
  • faux (io.TextIOWrapper): file object for auxiliary data results
  • out (OrderedDict): holds values for daily model simulation results
  • auxlist (list): auxiliary list of model parameters to additionally output along wih model output (for debugging)
  • progbar (ProgressBar): progressbar object to display progress of model run
  • bdailyrun (bool): True for daily runs, else False for hourly runs
  • model (EnergyBal): the model (oil palm model)

METHODS

  • create_network_graph: Create network graphs to track program flow
  • print_elapsed_time: Format and print the elapsed time
  • runxlmacro: Export model results to an Excel workbook
  • close_files: Close all files
  • dump: Dump the values of all or selected model parameters to a file
  • trace: Trace a single daily model run to create the network graphs, showing the complete program flow through the model components
  • set_auxiliaries: Set the auxiliary model parameters to additionally output
  • output_auxiliary: Write auxiliary results to auxiliary file (for debugging)
  • output_dailyrun: Initialize or retrieve and store daily model output results
  • output_hourlyrun: Initialize or retrieve and store hourly model output results
  • output_headers: Output the column headers (titles) to file
  • output_results: Save the model simulation results, and write results to file and screen
  • run_simulation: Run daily or hourly model simulations
  • plot_weather: Plot charts on weather properties

Constructor __init__

Facade(self, fname_in, fname_out)

Create and initialize the Facade object.

Arguments

  • fname_in (str): path and filename of the model initialization file
  • fname_out (str): path and filename of the model simulation reults file

__del__

Facade.__del__(self)

Class destructor.

Override to call close_files() to ensure all opened files, if any, are closed before this object is destroyed.

Returns

None:

close_files

Facade.close_files(self)

Close all files.

Returns

None:

set_auxiliaries

Facade.set_auxiliaries(self, fname_aux, auxlist)

Set the auxiliaries to output (used for debugging or checking calculation results).

Set attributes fname_aux and auxlist to the given auxiliary file name and auxiliary model parameters to output, respectively.

Arguments

  • fname_aux (str): path and filename to store auxiliary results
  • auxlist (list): list of variables to output during a model run

Example

For example, we want to save the trunk maintenance and water influx into the 2nd soil layer at the end of every run cycle. To access these parameters, we would normally call them like the this:

self.model.parts.trunk.maint   # maintenance of the trunk
self.model.layers[1].fluxes['influx'] # influx of water into second soil layer

but for brevity, just use:

parts.trunk.maint
layers[1].fluxes['influx']

where 'self.model.' will be prefixed in this class for each item in the auxlist. So, our sample code could look like this:

# a list of what we want to output (remember: remove 'self.model.'):
aux = ['parts.trunk.maint', "layers[1].fluxes['influx']"]

# debug.txt is the file name to store the auxiliary results:
fac.set_auxiliaries('debug.txt', aux)  # fac is a Facade object

# the usual model output plus the auxiliary results
fac.run_simulation(True, 365)

Returns

None:

dump

Facade.dump(self, fname, include=('.', '*'), exclude=None)

Dump the values of all or selected model parameters.

The user can specify which model parameters to include and exclude in the dump.

Note

SoilLayer objects have links to other SoilLayer objects, so these links create an infinite recursion during program flow tracing, so SoilLayer.prevlayer and SoilLayer.nextlayer attributes must be excluded. This method automatically appends these two parameters in the exclude argument.

Arguments

  • fname (str): path and name of file to store the model dump
  • include (list): list of model parameters to include in the dump (default is to include all)
  • exclude (list): list of model parameters to exclude in the dump (default is to exclude none -- but see Note above)

Example

A list of model parameters to include (uses regular expression)

incl = [r'.*Meteo',
        r'.*Crop']

and a list of model parameters to exclude (uses regular expression)

excl = [r'_Meteo__g$',
        r'_Crop__assim4gen',
        r'.*wind',
        r'.box*',
        r'.*ini']

If incl argument is omitted, all will be included by default (unless excluded by excl). If excl argument is omitted, none will be excluded (unless incl specfies what to include). If incl contradicts excl, excl wins (i.e., a parameter will be excluded even though incl specified that this parameter should be included).

Returns

None:

create_network_graph

Facade.create_network_graph(fname, fn, *args)

Note

create_network_graph is a static method

Trace the program flow to aid in understanding the structure of the whole model.

Two graph files will be created: a DOT (.dot) file and a GML (.gml) file type.

Arguments

  • fname (str): file name (without extension) for DOT and GML graph files to create
  • fn: the function which serves as the entry point to trace the program flow
  • args: variable lengh arguments, if any, for the entry point function fn()

Returns

None:

trace

Facade.trace(self, fname)

Create a network map to trace the program flow.

Program flows begins from Facade.run_simulation() method. A single daily run, just to capture the one cycle of the program flow through the model components/classes/methods.

Arguments

  • fname (str): files for DOT and GML map (do not specify the file extension)

Returns

None:

print_elapsed_time

Facade.print_elapsed_time(totsecs)

Note

print_elapsed_time is a static method

Format and print the elapsed time from total secs to hrs, mins, and secs.

Arguments

  • totsecs (int): total number of seconds elapsed

Returns

None:

output_auxiliary

Facade.output_auxiliary(self)

Write auxiliary results to the auxiliary file (for debugging).

Returns

None:

output_dailyrun

Facade.output_dailyrun(self, initialize=False)

Prepare the list of daily model output, then retrieve and store their results.

Arguments

  • initialize (bool): True to initialize the output dictionry, else False to retrieve and store model output results in dictionary

Returns

None:

output_hourlyrun

Facade.output_hourlyrun(self, initialize=False)

Prepare the list of hourly model output, then retrieve and store their results.

Returns

None:

output_headers

Facade.output_headers(self)

Output the column headers (titles) to file.

Returns

None:

output_results

Facade.output_results(self)

Save the model simulation results, and write results to file and screen.

Returns

None:

run_simulation

Facade.run_simulation(self, bdailyrun, duration=None, auxfile=None, auxlist=None)

Model simulation runs.

Run the model for a selected number of days or hours. Allow for auxiliary model paramters to be outputted and stored in a file. Auxiliaries are for debugging purposes to monitor the values of certain model parameters.

Arguments

  • bdailyrun (bool): True for daily simulation runs, else False for hourly simulation runs
  • duration (int): no. of simulation days to run (default is 1 day)
  • auxfile (str): auxiliary file name and path to store the output of selected model parameters
  • auxlist (list): list of model parameters to additionally output

Note

For hourly runs, the duration argument is always set for 24 simulation hours, regardless of the supplied argument value.

Example

Example of an auxiliary list:

aux = ['doy',
       'sla',
       'lookup_sla_lai()[1]',
       'parts.trunk.maint',
       'layers[1].fluxes["influx"]']

will output the following model parameters

    doy (day of year)
    sla (specific leaf area),
    lai (leaf area index),
    trunk maintenance, and
    water influx into the first soil layer

Returns

None:

runxlmacro

Facade.runxlmacro(xl_fname, xl_macroname, *args)

Note

runxlmacro is a static method

Run Excel macro stored in an Excel workbook (needs xlwings to be installed). Can be used, for instance, to export model results into Excel for charting or data analysis.

Arguments

  • xl_fname (str): name of Excel workbook to receive the model output (and has the macro)
  • xl_macroname (str): the name of the Excel macro in xl_fname
  • args: variable length arguments, if any, to pass into xl_macroname macro function

Returns

None:

plot_weather

Facade.plot_weather(self, fig_no, annwthr, fname)

Plot charts showing the distribution and statistics of several weather properties.

Arguments

  • fig_no (int): figure number, used to create multiple windows
  • annwthr (dict): dictionary holding the annual daily weather data
  • fname (str): weather stats file name and path

Returns

None:

output_weather_stats

Facade.output_weather_stats(self, fname, append_to_file=False)

Write to file the daily weather parameters for the whole year and their statistics.

Daily weather parameters to be written to an output file are min. and max. air temperatures, wind speed, rain, and solar irradiance. Some basic statistics will be computed and written together to the file as well.

Charts will be drawn as visual output.

Arguments

  • fname (str): output file (plain text file)
  • append_to_file (bool): False (default) to create a new output file, else True to append output to an exisiting file

Returns

None: