User Interface Package

Base Widgets

class invest_natcap.iui.base_widgets.CSVFieldDropdown(attributes)

Bases: invest_natcap.iui.base_widgets.TableHandler

class invest_natcap.iui.base_widgets.CheckBox(attributes)

Bases: PyQt4.QtGui.QCheckBox, invest_natcap.iui.base_widgets.DynamicPrimitive

This class represents a checkbox for our UI interpreter. It has the ability to enable and disable other elements.

requirementsMet()
setBGcolorSatisfied(state)
setValue(value)

Set the value of this element to value.

value - a string or boolean representing

returns nothing

toggle(event=None)

Enable/disable all elements controlled by this element.

returns nothing.

value()

Get the value of this checkbox.

returns a boolean.

class invest_natcap.iui.base_widgets.Container(attributes, registrar=None)

Bases: PyQt4.QtGui.QGroupBox, invest_natcap.iui.base_widgets.DynamicGroup

Class Container represents a QGroupBox (which is akin to the HTML widget ‘fieldset’. It has a Vertical layout, but may be subclassed if a different layout is needed.

requirementsMet()

This function is used to return whether the container is enabled or not. Used for determining whether other elements should be triggered.

If the container is checkable, the check state is returned. If the container is not checkable, True is returned.

resetValue()
setState(state, includeSelf=False, recursive=True)

Reimplemented from Container.setState. When this container is collapsible, we only want to set the state of contained elements when the collapsible container is open. Otherwise, pass.

setValue(value)
toggleHiding(state)

Show or hide all sub-elements of container (if collapsible) as necessary. This function is a callback for the toggled() signal.

returns nothing.

value()
class invest_natcap.iui.base_widgets.Data

Bases: object

class invest_natcap.iui.base_widgets.Dropdown(attributes)

Bases: invest_natcap.iui.base_widgets.LabeledElement

get_element_state()
setValue(index)
value()
class invest_natcap.iui.base_widgets.DynamicElement(attributes)

Bases: PyQt4.QtGui.QWidget

Create an object containing the skeleton of most functionality in the UI Interpreter’s related classes. It is not invoked directly by other IUI classes, but is instead used as a base class for almost all classes in the UI interpreter. A diagram of this class heirarchy can be found at https://docs.google.com/drawings/d/13QZ6SsUwvoBPjvr0gf_X1X20sc35tLTr9oedX1vaUh8/edit

DynamicElement serves as a base class for DynamicGroup and DynamicPrimitive. The functions and object data it declares are shared by all subclasses.

getElementsDictionary()
getLabel()
getRoot()

Search up the Qt widget tree until we find the root element, which is by definition an instance of the class DynamicUI. A pointer to the root is usually saved to the local object as self.root.

returns a pointer to the instance of DynamicUI

get_element_state()

This function gets the relevant element state information for setting a lastrun dictionary. It defaults to just return the value of the element (whatever its return value is), but can be overridden to return more specific element information. Information saved in this way can be set by using the function ‘set_element_state’.

isRequired()

Check to see if this element is required.

An element is required if element.required == True or if the element has a ‘requiredIf’ attribute list and at least one of the elements in the ‘requiredIf’ list is required.

returns a boolean

requirementsMet()
setState(state, includeSelf=True, recursive=True)
set_element_state(state)

Set the element’s state from state. State is assumed to come from self.get_element_state().

Update dependency links for this element.

All elements (although usually only subclasses of DynamicPrimitive) have the ability to be enabled by other elements

class invest_natcap.iui.base_widgets.DynamicGroup(attributes, layout=<PyQt4.QtGui.QVBoxLayout object at 0x8773440>, registrar=None)

Bases: invest_natcap.iui.base_widgets.DynamicElement

Creates an object intended for grouping other elements together.

DynamicGroup is a subclass of DynamicElement and thus inherits all attributes and functions of the DynamicElement class.

DynamicUI, Container, CollapsibleContainer and List are all subclasses of DynamicGroup.

The DynamicGroup object allows other elements to be grouped together using any arbitrary layout mechanism compatible with Qt. If a custom layout manager is used, it may be necessary to revisit the DynamicGroup.createElements() function to define exactly how the elements created are to be added to the new layout.

As all possible grouping objects in this Interpreter subclass DynamicGroup, if a new widget is to be added, it must likewise be added to the if-elif block in createElements. The element will not be created if there is no corresponding entry in createElements()

createElements(elementsArray, start_index=0)

Create the elements defined in elementsArray as widgets within this current grouping widget. All elements are created as widgets within this grouping widget’s layout.

elementsArray - a python array of elements, where each element is a
python dictionary with string keys to each of its attributes as defined in the input JSON file.
start_index=0 - a python int representing the row to start appending
to.

no return value

getElementsDictionary()

Assemble a flat dictionary of all elements contained in this group.

This function loops through the self.elements array and attempts to retrieve a dictionary for each sub-element. If a sub-element dictionary can be retrieved, it is concatenated with the existing dictionary.

Such a flat dictionary structure is convenient for iterating over all elements in the UI.

returns a python dictionary mapping widget id (a string) to an
element pointer.
getOutputValue()
setValue(value)

TO BE IMPLEMENTED

value()

TO BE IMPLEMENTED

class invest_natcap.iui.base_widgets.DynamicPrimitive(attributes)

Bases: invest_natcap.iui.base_widgets.DynamicElement

DynamicPrimitive represents the class of all elements that can be listed individually in the JSON file that themselves cannot group other elements. As such, DynamicPrimitive is the superclass of all input elements.

DynamicText and CheckBox inherit DynamicPrimitive, and FileEntry, YearEntry inherit DynamicText (thus also inheriting DynamicPrimitive).

There are two defining attributes of DynamicPrimitive:
  • self.elements (a python Array)
  • self.attributes[‘args_id’] (a string)

self.elements is an array of the widgets that make up this element. By default, this is set to [self], implying that a subclass has at least one widget. In cases where a subclass of DynamicPrimitive has multiple widgets, the elements array is used to determine the order in which the elements are added to the GUI in DynamicGroup.createElements().

self.attributes[‘args_id’] is an optional string provided by the user that enables the construction of an arguments dictionary in python that will be passed to the specified python program. The args_id must conform with the API specified by the desired model.

Note that all implemented instances of DynamicPrimitive must implement their own setValue(value) function, specific to the target QWidget.

  • self.setValue(value) is a function that allows a developer to specify

    the value of the current element, depending on how the value needs to be set based on the class and class elements and the type of the value.

cast_value()
check_validation_error()
getElementsDictionary()

Assemble a python dictionary mapping this object’s string ID to its pointer.

self.getElementsDictionary is called to build a flat dictionary of all elements in the entire UI. Considering that subclasses of DynamicPrimitive are the most atomic elements the user can control in the JSON file, it follows that subclasses of DynamicPrimitive should return the most primitive such dictionary.

returns a python dict mapping string ID -> this object’s pointer.

getOutputValue()

Return the output value of this element, applying any necessary filters. This function is intended to be called when assembling the output dictionary. Returns the appropriate output value of this element.

has_error()
has_warning()
resetValue()

If a default value has been specified, reset this element to its default. Otherwise, leave the element alone.

returns nothing.

setState(state, includeSelf=True, recursive=True)
setValue(value)
set_error(error, state)
validate()
class invest_natcap.iui.base_widgets.DynamicText(attributes)

Bases: invest_natcap.iui.base_widgets.LabeledElement

Creates an object containing a label and a sigle-line text field for user input.

DynamicText is a subclass of DynamicPrimitive and thus inherits all its methods and attributes.

FileEntry and YearEntry inherit DynamicText.

As the superclass to a number of text-based elements, DynamicText implements a text-only option, namely validText. DynamicText also implements the attribute defaultValue.

class TextField

Bases: PyQt4.QtGui.QLineEdit

contextMenuEvent(event=None)

Reimplemented from QtGui.QLineEdit.contextMenuEvent.

This function allows me to make changes to the context menu when one is requested before I show the menu.

emit_textchanged(state=None)

This is a wrapper function that allows me to emit the textChanged signal more easily. It simply emits the textChanged signal with the current contents of the textfield.

resizeEvent(event)

Reimplemented from QtGui.QLineEdit.resizeEvent.

This reimplemented function allows me to move around the datatype button when the window is resized, before Qt handles all its normal resize event routines.

DynamicText.isEnabled()

Check to see if this element is ‘enabled’.

This status is commonly used to determine whether other fields should be enabled or disabled (to allow or prevent the user from interacting with the widget)

This is tested by checking the length of the string entered into self.textField. Specific implementations may differ as appropriate to the subclass.

returns a boolean.

DynamicText.parentWidget()

Return the parent widget of one of the QWidgets of this object.

Because DynamicText objects by definition have at least two widgets which individually could be added to separate layouts of separate widgets, it is necessary to specify which local widget we wish to identify as having the parent.

In this case, self.textField has been selected.

returns a pointer to an instance of a QWidget.

DynamicText.requirementsMet()

Determine whether the textfield is considered ‘complete’. This is used to determine whether a dependent element should be enabled or disabled and may need to be reimplemented for a subclass as new text-based elements arise.

As a basic form of completion, we assume that this field is satisfied when some text (any text) has been entered.

returns a boolean

DynamicText.setBGcolorSatisfied(satisfied=True)

Color the background of this element’s label.

satisfied=True - a boolean, indicating whether this element’s
requirements have been satisfied.

returns nothing

DynamicText.setValidateField(regexp)

Set input validation on the text field to conform with the input regular expression. Validation takes place continuously, so the user will be unable to enter text in this field unless it conforms to the regexp.

regexp - a string regular expression

returns nothing

DynamicText.setValue(text)

Set the value of self.textField.

text - a string, the text to be inserted into self.textField.

returns nothing.

DynamicText.toggle()

Toggle all elements associated with this element’s ID.

This function has several purposes:
  • It instructs the root element to update its requirement notification based on the current status of all elements
  • It sets the backgroundColor of this object’s label if its completion requirements have not been met
  • It instructs the root element to toggle all other elements appropriately.

returns nothing.

DynamicText.value()

Fetch the value of the user’s input, stored in self.textField.

returns a string.

class invest_natcap.iui.base_widgets.ElementAssembler(elements_ptr)

Bases: invest_natcap.iui.iui_validator.ValidationAssembler

class invest_natcap.iui.base_widgets.ElementRegistrar(root_ptr)

Bases: invest_natcap.iui.registrar.Registrar

eval(type, op_values)
class invest_natcap.iui.base_widgets.EmbeddedUI(attributes, registrar)

Bases: invest_natcap.iui.base_widgets.Root

find_element_ptr(element_id)

Return an element pointer if found. None if not found.

getOutputValue()
setValue(parameters)
class invest_natcap.iui.base_widgets.ErrorButton(title, body_text='')

Bases: invest_natcap.iui.base_widgets.InformationButton

build_contents()

Take the python string components of this instance of InformationPopup, wrap them up in HTML as necessary and return a single string containing HTML markup. Returns a python string.

setEnabled(state)
set_error(error_string, state)

Set the error string of this InformationPopup and also set this button’s icon according to the error contained in error_string. error_string is a python string.

class invest_natcap.iui.base_widgets.ErrorDialog

Bases: invest_natcap.iui.base_widgets.InfoDialog

showEvent(event=None)
class invest_natcap.iui.base_widgets.ExecRoot(uri, layout=None, object_registrar=None, main_window=None, version=None)

Bases: invest_natcap.iui.base_widgets.Root

addBottomButtons()

Assembles buttons and connects their callbacks.

returns nothing.

closeEvent(event=None)

Terminates the application. This function is a Qt-defined callback for when the window is closed.

returns nothing

closeWindow()

Terminates the application.

This function is called when the user closes the window by any of Qt’s recognized methods (often including closing the window via the little x in the corner of the window and/or pressing the Esc key).

returns nothing

find_element_ptr(element_id)

Return an element pointer if found. None if not found.

initElements()

Set the enabled/disabled state and text from the last run for all elements

returns nothing

load_elements_from_save(save_dict)
load_parameters_from_file()
okPressed()

A callback, run when the user presses the ‘OK’ button.

returns nothing.

remove_lastrun()
resetParametersToDefaults()
runProgram()
saveLastRun()

Saves the current values of all input elements to a JSON object on disc.

returns nothing

save_args_dict_to_file()
save_parameters_to_file()
save_to_json()

Save the current state of the UI to a python file after checking that there are no validation errors.

save_to_python()

Save the current state of the UI to a python file after checking that there are no validation errors.

setWindowSize()
class invest_natcap.iui.base_widgets.FileButton(text, URIfield, filetype='file', filter='all')

Bases: PyQt4.QtGui.QPushButton

This object is the button used in the FileEntry object that, when pressed, will open a file dialog (QtGui.QFileDialog). The string URI returned by the QFileDialog will be set as the text of the provided URIField.

Arguments: text - the string text title of the popup window. URIField - a QtGui.QLineEdit. This object will receive the string URI

from the QFileDialog.
getFileName(filetype='file')

Get the URI from the QFileDialog.

If the user presses OK in the QFileDialog, the dialog returns the URI to the selected file.

If the user presses ‘Cancel’ in the QFileDialog, the dialog returns ‘’. As a result, we must first save the previous contents of the QLineEdit before we open the dialog. Then, if the user presses ‘Cancel’, we can restore the previous field contents.

class invest_natcap.iui.base_widgets.FileEntry(attributes)

Bases: invest_natcap.iui.base_widgets.DynamicText

class FileField

Bases: invest_natcap.iui.base_widgets.TextField

dragEnterEvent(event=None)

Overriding the default dragEnterEvent function for when a file is dragged and dropped onto this qlineedit. This reimplementation is necessary for the dropEvent function to work on Windows.

dropEvent(event=None)

Overriding the default Qt DropEvent function when a file is dragged and dropped onto this qlineedit.

FileEntry.click_in_field(event=None)

Reimplemented event handler taking the place of QLineEdit.mousePressEvent. Checks to see if there’s a file in the textfield. If so, we do nothing. Otherwise (if the uri is blank), we should open up the file dialog for the user. If the user right-clicks in the text field, pass the event on to the normal handler.

FileEntry.setValue(text)

Set the value of the uri field. If parameter ‘text’ is an absolute path, set the textfield to its value. If parameter ‘text’ is a relative path, set the textfield to be the absolute path of the input text, relative to the invest root.

returns nothing.

class invest_natcap.iui.base_widgets.GridList(attributes, registrar=None)

Bases: invest_natcap.iui.base_widgets.DynamicGroup

Class GridList represents a DynamicGroup that has a QGridLayout as a layout manager.

class invest_natcap.iui.base_widgets.HideableElement(attributes)

Bases: invest_natcap.iui.base_widgets.LabeledElement

get_element_state()

Get the state of the HideableElement. Since this is just a base class, we can only really return a dictionary with the checked value.

requirementsMet()
toggleHiding(checked)
class invest_natcap.iui.base_widgets.HideableFileEntry(attributes)

Bases: invest_natcap.iui.base_widgets.HideableElement, invest_natcap.iui.base_widgets.FileEntry

get_element_state()
isEnabled()

IsEnabled is a characteristic of QtGui.QWidget. We need to override it here because the whether the element is enabled depends not just on whether this element is greyed out but whether its value should be retrieved (and the value should only be retrieved when the checkbox is checked).

requirementsMet()
set_element_state(state)
class invest_natcap.iui.base_widgets.InfoDialog

Bases: PyQt4.QtGui.QDialog

set_icon(uri)
set_messages(message_list)
set_title(title)
class invest_natcap.iui.base_widgets.InformationButton(title, body_text='')

Bases: PyQt4.QtGui.QPushButton

This class represents the information that a user will see when pressing the information button. This specific class simply represents an object that has a couple of string attributes that may be changed at will, and then constructed into a cohesive string by calling self.build_contents.

Note that this class supports the presentation of an error message. If the error message is to be shown to the end user, it must be set after the creation of the InformationPopup instance by calling self.set_error().

build_contents()

Take the python string components of this instance of InformationPopup, wrap them up in HTML as necessary and return a single string containing HTML markup. Returns a python string.

deactivate()

Visually disable the button: set it to be flat, disable it, and clear its icon.

set_body(body_string)

Set the body of the InformationPopup. body_string is a python string.

set_title(title_text)

Set the title of the InformationPopup text. title_text is a python string.

show_info_popup()

Show the information popup. This manually (programmatically) enters What’s This? mode and spawns the tooltip at the location of trigger, the element that triggered this function.

class invest_natcap.iui.base_widgets.Label(attributes)

Bases: PyQt4.QtGui.QLabel, invest_natcap.iui.base_widgets.StaticReturn

class invest_natcap.iui.base_widgets.LabeledElement(attributes)

Bases: invest_natcap.iui.base_widgets.DynamicPrimitive

addElement(element)
initState()
isEnabled()
setBGcolorSatisfied(satisfied=True)

Color the background of this element’s label.

satisfied=True - a boolean, indicating whether this element’s
requirements have been satisfied.

returns nothing

setState(state, includeSelf=True, recursive=True)
class invest_natcap.iui.base_widgets.MainWindow(root_class, uri)

Bases: PyQt4.QtGui.QMainWindow

exec_()
class invest_natcap.iui.base_widgets.MessageArea

Bases: PyQt4.QtGui.QLabel

append(string)
clear()

Clear all text and set the stylesheet to none.

setError(state)

Set the background color according to the error status passed in.

state - a python boolean. False if no error. True if error.

returns nothing.

setText(text=None)
class invest_natcap.iui.base_widgets.MultiElement(attributes, registrar=None)

Bases: invest_natcap.iui.base_widgets.Container

Defines a class that allows the user to select an arbitrary number of the same input by providing an hyperlink by which to add another element. Validation applies as usual and the same validation is applied to all elements. As a result, it is best to have a single multi-input element for each desired validation or input type as inputs cannot be mixed and matched.

example JSON:

“id”: “multi-file”, “type”: “multiFile”, “label”: “Test multi-file”, “sampleElement”: {“id”: “sample_id”,

“type”: “text”, “label”: “Input raster”, “validateAs”: {“type”: “GDAL”}},

“linkText”: “Add another”

class MinusButton(row_num, parent)

Bases: PyQt4.QtGui.QPushButton

This class defines the ‘-‘ button that is used by the MultiFile class.

remove_element()

A callback that is triggered when the button is pressed.

MultiElement.add_element(default_value=None)

Add another element entry using the default element json provided by the json configuration. If default_value is not None, the value provided will be set as the element’s value.

MultiElement.add_element_callback(event=None)

Function wrapper for add_element. event is expected to be a Qt event. It is ignored.

MultiElement.clear_elements()

Remove ALL elements in this multi-element.

MultiElement.remove_element(row_num)

Remove the element located at row_num in the layout. row_num is assumed to be 1-based, not zero-based.

MultiElement.resetValue()

Reimplemented from the Container class. Removes all rows in the multiElement and then creates new rows for each JSON-defined default value, if provided.

MultiElement.setValue(values)

Set the local input values to values. values should be a python list of values to be set. A new element will be created for each item in values. Returns nothing.

MultiElement.value()

Return a python list of the values for all enclosed elements.

class invest_natcap.iui.base_widgets.OGRFieldDropdown(attributes)

Bases: invest_natcap.iui.base_widgets.TableHandler

class invest_natcap.iui.base_widgets.OperationDialog(root)

Bases: PyQt4.QtGui.QDialog

ModelDialog is a class defining a modal window presented to the user while the model is running. This modal window prevents the user from interacting with the main UI window while the model is processing and provides status updates for the model.

This window is not configurable through the JSON configuration file.

cancelled()
check_messages()
closeEvent(event=None)

When a closeEvent is detected, run self.closeWindow().

returns nothing.

closeWindow()

Close the window and ensure the modelProcess has completed.

returns nothing.

finished()

Notify the user that model processing has finished.

returns nothing.

okPressed()

When self.runButton is pressed, halt the statusbar and close the window with a siccessful status code.

returns nothing.

showEvent(event)
startExecutor()
start_buttons()
stop_buttons()
write(text)

Write text. If printing to the status area, also scrolls to the end of the text region after writing to it. Otherwise, print to stdout.

text - a string to be written to self.statusArea.

returns nothing.

class invest_natcap.iui.base_widgets.Root(uri, layout, object_registrar)

Bases: invest_natcap.iui.base_widgets.DynamicElement

assembleOutputDict()

Assemble an output dictionary for use in the target model

Saves a python dictionary to self.outputDict. This dictionary has the mapping: element args_id -> element value. Values are converted to their appropriate dataType where specified in the JSON config file.

returns a python dictionary

errors_exist()

Check to see if any elements in this UI have errors.

returns a list of tuples, where the first tuple entry is the element label and the second tuple entry is the element’s error message..

find_and_replace(attributes)
Initiates a recursive search and replace of the attributes

dictionary according to the ‘inheritFrom’ capabilities of the JSON definition.

attributes - a python dictionary representation of the JSON
configuration.

Returns the rendered attributes dictionary.

find_embedded_elements()
find_embedded_value(inherit)
find_inherited_elements(attributes)

Searches the input attributes dictionary for an inheritance object and initializes a search for the value requested by the inheritance object.

attributes - a python dictionary representing an element.

Returns the rendered attributes dictionary.

find_value(inherit, current_dict=None)

Searches the given dictionary for values described in inherit.

inherit - a python dictionary confirming to the attribute
inheritance properties of the JSON definition.
current_dict - a python dictionary of the current scope of the
search. if None (the default value), self.attributes is used for the current_dict.

Returns the value object requested by inherit if found. Returns None if the requested object is not found.

get_element_state()
queueOperations()
resetParametersToDefaults()

Reset all parameters to defaults provided in the configuration file.

returns nothing

set_dict_value(dictionary, key_list, element_value)
updateScrollBorder(min, max)
value()
warnings_exist()

Check to see if any elements in this UI have warnings.

returns a list of tuples, where the first tuple entry is the element label and the second tuple entry is the element’s error message..

class invest_natcap.iui.base_widgets.ScrollArea(attributes, layout=<PyQt4.QtGui.QVBoxLayout object at 0x87737a0>, registrar=None)

Bases: PyQt4.QtGui.QScrollArea

getElementsDictionary()
updateScrollBorder(min=None, max=None)
class invest_natcap.iui.base_widgets.SliderSpinBox(attributes)

Bases: invest_natcap.iui.base_widgets.DynamicPrimitive

expects these attributes: label: string type: sliderSpinBox min: number max: number sliderSteps: int spinboxSteps: int

setSlider()
setSpinbox()
class invest_natcap.iui.base_widgets.StaticReturn(attributes)

Bases: invest_natcap.iui.base_widgets.DynamicPrimitive

value()
class invest_natcap.iui.base_widgets.Tab(attributes, registrar=None)

Bases: invest_natcap.iui.base_widgets.DynamicGroup

isEnabled()
setState(state, includeSelf=True, recursive=True)
set_index(index)
class invest_natcap.iui.base_widgets.TabbedGroup(attributes, registrar=None)

Bases: PyQt4.QtGui.QTabWidget, invest_natcap.iui.base_widgets.DynamicGroup

set_active_tab()

Update the active tab in this tabbedgroup to be the leftmost enabled tab. If there are no enabled tabs, the active tab should be the leftmost tab.

returns nothing.

class invest_natcap.iui.base_widgets.TableHandler(attributes)

Bases: invest_natcap.iui.base_widgets.Dropdown

This class defines a general-purpose class for handling dropdown-based column selection. This class uses IUI’s ‘enabledBy’ attribute to control the contents of the dropdown menu. This element’s ‘enabledBy’ attribute must be set to the id of 0a file element that is validated appropriately.

get_element_state()
populate_fields()

Extract the fieldnames from the fileio table handler class for this instance of TableHandler. Returns nothing, but populates the dropdown with the appropriate fieldnames. If any options are present in the dropdown, they are cleared before the new column names are entered.

setState(state, includeSelf=True, recursive=True)

Reimplemented from Dropdown.setState. When state=False, the dropdown menu is cleared. If state=True, the dropdown menu is populated with values from the corresponding table object.

set_element_state(state)
class invest_natcap.iui.base_widgets.WarningDialog

Bases: invest_natcap.iui.base_widgets.InfoDialog

class invest_natcap.iui.base_widgets.YearEntry(attributes)

Bases: invest_natcap.iui.base_widgets.DynamicText

This represents all the components of a ‘Year’ line in the LULC box. The YearEntry object consists of two objects: a label (QtGui.QLabel) and a year (QtGui.QLineEdit). The year also has a min and max width.

invest_natcap.iui.base_widgets.center_window(window_ptr)

Center a window on whatever screen it appears.

window_ptr - a pointer to a Qt window, whether an application or a
QDialog.

returns nothing.

Executor

class invest_natcap.iui.executor.Controller

Bases: object

The Controller class manages two Thread objects: Executor and PrintQueueChecker. Executor runs models and queues up print statements in a local printqueue list. Printqueue checks on Executor’s printqueue and fetches the next message at a specified interval.

The printqueuechecker exists to offload the work of list-related operations from the main thread, which leaves the main thread free to perform UI-related tasks.

add_operation(op, args=None, uri=None, index=None)

Wrapper method for Executor.addOperation. Creates new executor and message checker thread instances if necessary.

Returns nothing.

cancel_executor()

Trigger the executor’s cancel event. Returns nothing.

finished()

Set the executor and message checker thread objects to none and set the thread_finished variable to True.

Returns nothing.

get_message()

Check to see if the message checker thread is alive and returns the current message if so. If the message checker thread is not alive, None is returned and self.finished() is called.

is_finished()

Returns True if the threads are finished. False if not.

start_executor()

Starts the executor and message checker threads. Returns nothing.

class invest_natcap.iui.executor.Executor

Bases: threading.Thread

addOperation(op, args=None, uri=None, index=None)
cancel()
flush()
format_time(seconds)

Render the integer number of seconds in a string. Returns a string.

getMessage()
hasMessages()
isCancelled()
isThreadFailed()
printTraceback()
print_args(args_dict)
Write args_dict to a formatted string to the self.write() function.
args_dict - a dictionary.

returns noting

print_system_info(function=None)
run()
runModel(module, args)
runValidator(uri, args)
saveParamsToDisk(data=None)
setThreadFailed(state, exception=None)

Set the flag of whether the thread has failed. exception should be a pointer to a python Exception or a boolean.

write(string)
exception invest_natcap.iui.executor.InsufficientDiskSpace

Bases: exceptions.Exception

class invest_natcap.iui.executor.PrintQueueChecker(executor_object)

Bases: threading.Thread

PrintQueueChecker is a thread class that checks on a specified executor thread object. By placing the responsibility of this operation in a separate thread, we allow the main thread to attend to more pressing UI related tasks.

get_message()

Check to see if there is a new message available.

Returns the string message, if one is available. None if not.

run()

Fetch messages as long as the executor is alive or has messages.

This method is reimplemented from threading.Thread and is started by calling self.start().

This function calls the executor object function getMessage(), which uses the collections.deque queue object to manage the printqueue.

The new message is only fetched from the executor if the main thread has fetched the current message from this PrintQueueChecker instance.

returns nothing.

invest_natcap.iui.executor.locate_module(module_list, path=None)

Search for and return an executable module object as long as the target module is within the pythonpath. This method recursively uses the find_module and load_module functions of the python imp module to locate the target module by its heirarchical module name.

module_list - a python list of strings, where each element is the name
of a contained module. For example, os.path would be represented here as [‘os’, ‘path’].
path=None - the base path to search. If None, the pythonpath will be
used.

returns an executeable python module object if it can be found. Returns None if not.

File IO

class invest_natcap.iui.fileio.AbstractTableHandler(uri)

Bases: object

This class provides an abstract class for specific reimplementation for each tabular filetype

__iter__()

Reimplemented, allows the user to iterate through an instance of AbstractTableHandler without actually returning self.table. Having this function allows this class to actually be iterable.

get_fieldnames(case='lower')

Returns a python list of the original fieldnames, true to their original case.

case=’lower’ - a python string representing the desired status of the
fieldnames. ‘lower’ for lower case, ‘orig’ for original case.

returns a python list of strings.

get_file_object()

Getter function for the underlying file object. If the file object has not been retrieved, retrieve it before returning the file object.

returns a file object.

get_map(key_field, value_field)

Returns a python dictionary mapping values contained in key_field to values contained in value_field. If duplicate keys are found, they are overwritten in the output dictionary.

This is implemented as a dictionary comprehension on top of self.get_table_list(), so there shouldn’t be a need to reimplement this for each subclass of AbstractTableHandler.

If the table list has not been retrieved, it is retrieved before generating the map.

key_field - a python string. value_field - a python string.

returns a python dictionary mapping key_fields to value_fields.

get_table_dictionary(key_field)

Returns a python dictionary mapping a key value to all values in that particular row dictionary (including the key field). If duplicate keys are found, the are overwritten in the output dictionary.

key_field - a python string of the desired field value to be used as
the key for the returned dictionary.

returns a python dictionary of dictionaries.

get_table_row(key_field, key_value)

Return the first full row where the value of key_field is equivalent to key_value. Raises a KeyError if key_field does not exist.

key_field - a python string. key_value - a value of appropriate type for this field.

returns a python dictionary of the row, or None if the row does not exist.

set_field_mask(regexp=None, trim=0)

Set a mask for the table’s self.fieldnames. Any fieldnames that match regexp will have trim number of characters stripped off the front.

regexp=None - a python string or None. If a python string, this
will be a regular expression. If None, this represents no regular expression.

trim - a python int.

Returns nothing.

update(uri)

Update the URI associated with this AbstractTableHandler object. Updating the URI also rebuilds the fieldnames and internal representation of the table.

uri - a python string target URI to be set as the new URI of this
AbstractTableHandler.

Returns nothing.

class invest_natcap.iui.fileio.CSVHandler(uri)

Bases: invest_natcap.iui.fileio.AbstractTableHandler

class invest_natcap.iui.fileio.DBFHandler(uri)

Bases: invest_natcap.iui.fileio.AbstractTableHandler

class invest_natcap.iui.fileio.JSONHandler(uri)

Bases: object

delete()
get_attributes()
write_to_disk(dict)
class invest_natcap.iui.fileio.LastRunHandler(modelname, version=None)

Bases: invest_natcap.iui.fileio.JSONHandler

class invest_natcap.iui.fileio.OGRHandler(uri)

Bases: invest_natcap.iui.fileio.AbstractTableHandler

class invest_natcap.iui.fileio.ResourceHandler(resource_dir)

Bases: invest_natcap.iui.fileio.JSONHandler

This class allows actually handles reading a resource handler file from disk.

check(dictionary=None)

Iterate through all nested key-value pairs in this resource file and print an error message if the file cannot be found. Returns nothing.

icon(icon_key)

Fetch the URI based on the icon_key. If the key is not found, raises a keyError.

icon_key - a python string key to be accessed from the resources
file.

Returns an absolute path to the resource.

class invest_natcap.iui.fileio.ResourceManager(user_resource_dir='')

Bases: object

ResourceManager reconciles overrides supplied by the user against the default values saved to the internal iui_resources resource file. It adheres to the ResourceInterface interface and will print messages to stdout when defaulting to iui’s internal resources.

icon(icon_key)

Return the appropriate icon path based on the path returned by the user’s resource file and the path returned by the default resource file. Defaults are used if the specified python string key cannot be found in the user_resources file

icon_key - a python string key for the desired icon.

Returns a python string.

invest_natcap.iui.fileio.find_handler(uri)

Attempt to open the file provided by uri.

uri - a string URI to a table on disk.

returns the appropriate file’s Handler. Returns None if an appropriate handler cannot be found.

invest_natcap.iui.fileio.save_model_run(arguments, module, out_file)

Save an arguments list and module to a new python file that can be executed on its own.

arguments - a python dictionary of arguments. module - the python module path in python package notation (e.g.

invest_natcap.pollination.pollination)
out_file - the file to which the output file should be written. If the
file exists, it will be overwritten.

This function returns nothing.

invest_natcap.iui.fileio.save_model_run_json(arguments, module, out_file)
invest_natcap.iui.fileio.settings_folder()

Return the file location of the user’s settings folder. This folder location is OS-dependent.

Validator

This module provides validation functionality for the IUI package. In a nutshell, this module will validate a value if given a dictionary that specifies how the value should be validated.

class invest_natcap.iui.iui_validator.CSVChecker

Bases: invest_natcap.iui.iui_validator.TableChecker

open(valid_dict)

Attempt to open the CSV file

class invest_natcap.iui.iui_validator.Checker

Bases: invest_natcap.iui.registrar.Registrar

The Checker class defines a superclass for all classes that actually perform validation. Specific subclasses exist for validating specific features. These can be broken up into two separate groups based on the value of the field in the UI:

  • URI-based values (such as files and folders)
    • Represented by the URIChecker class and its subclasses
  • Scalar values (such as strings and numbers)
    • Represented by the PrimitiveChecker class and its subclasses
There are two steps to validating a user’s input:
  • First, the user’s input is preprocessed by looping through a list of operations. Functions can be added to this list by calling self.add_check_function(). All functions that are added to this list must take a single argument, which is the entire validation dictionary. This is useful for guaranteeing that a given function is performed (such as opening a file and saving its reference to self.file) before any other validation happens.

  • Second, the user’s input is validated according to the validation dictionary in no particular order. All functions in this step must take a single argument which represents the user-defined value for this particular key.

    For example, if we have the following validation dictionary:
    valid_dict = {‘type’: ‘OGR’,

    ‘value’: ‘/tmp/example.shp’, ‘layers: [{layer_def ...}]}

    The OGRChecker class would expect the function associated with the ‘layers’ key to take a list of python dictionaries.

add_check_function(func, index=None)

Add a function to the list of check functions.

func - A function. Must accept a single argument: the entire
validation dictionary for this element.
index=None - an int. If provided, the function will be inserted
into the check function list at this index. If no index is provided, the check function will be appended to the list of check functions.

returns nothing

run_checks(valid_dict)

Run all checks in their appropriate order. This operation is done in two steps:

  • preprocessing

    In the preprocessing step, all functions in the list of check functions are executed. All functions in this list must take a single argument: the dictionary passed in as valid_dict.

  • attribute validation

    In this step, key-value pairs in the valid_dict dictionary are evaluated in arbitrary order unless the key of a key-value pair is present in the list self.ignore.

class invest_natcap.iui.iui_validator.DBFChecker

Bases: invest_natcap.iui.iui_validator.TableChecker

open(valid_dict, read_only=True)

Attempt to open the DBF.

class invest_natcap.iui.iui_validator.FileChecker

Bases: invest_natcap.iui.iui_validator.URIChecker

This subclass of URIChecker is tweaked to validate a file on disk.

In contrast to the FolderChecker class, this class validates that a specific file exists on disk.

open(valid_dict)

Checks to see if the file at self.uri can be opened by python.

This function can be overridden by subclasses as appropriate for the filetype.

Returns an error string if the file cannot be opened. None if otherwise.

class invest_natcap.iui.iui_validator.FlexibleTableChecker

Bases: invest_natcap.iui.iui_validator.TableChecker

This class validates a file in a generic ‘table’ format.

Currently, this supports DBF and CSV formats.

This class is essentially a wrapper that first determines which file format we’re dealing with, and then delegates the rest of the work to the appropriate Checker class for that specific file format.

open(valid_dict)

Attempt to open the file

class invest_natcap.iui.iui_validator.FolderChecker

Bases: invest_natcap.iui.iui_validator.URIChecker

This subclass of URIChecker is tweaked to validate a folder.

check_contents(files)

Verify that the files listed in files exist. Paths in files must be relative to the Folder path that we are validating. This function strictly validates the presence of these files.

files - a list of string file URIs, where each file is relative to
the Folder stored in self.uri.

Conforming with all Checker classes, this function returns a string error if one of the files does not exist or None if all required files are found.

check_exists(valid_dict)

Verify that the file at valid_dict[‘value’] exists. Reimplemented from URIChecker class to provide more helpful, folder-oriented error message.

class invest_natcap.iui.iui_validator.GDALChecker

Bases: invest_natcap.iui.iui_validator.FileChecker

This class subclasses FileChecker to provide GDAL-specific validation.

open(valid_dict)

Attempt to open the GDAL object. URI must exist. This is an overridden FileChecker.open()

Returns an error string if in error. Returns none otherwise.

class invest_natcap.iui.iui_validator.NumberChecker

Bases: invest_natcap.iui.iui_validator.PrimitiveChecker

greater_than(b)
greater_than_equal_to(b)
less_than(b)
less_than_equal_to(b)
class invest_natcap.iui.iui_validator.OGRChecker

Bases: invest_natcap.iui.iui_validator.TableChecker

check_layers(layer_list)

Attempt to open the layer specified in self.valid.

open(valid_dict)

Attempt to open the shapefile.

class invest_natcap.iui.iui_validator.PrimitiveChecker

Bases: invest_natcap.iui.iui_validator.Checker

check_regexp(valid_dict)

Check an input regular expression contained in valid_dict.

valid_dict - a python dictionary with the following structure: valid_dict[‘value’] - (required) a python string to be matched valid_dict[‘allowed_values’] - (required) a python dictionary with the

following entries:
valid_dict[‘allowed_values’][‘pattern’] - (‘required’) must match
one of the following formats:
  • A python string regular expression formatted according to the re module (http://docs.python.org/library/re.html)

  • A python list of values to be matched. These are treated as logical or (‘|’ in the built regular expression). Note that the entire input pattern will be matched if you use this option. For more fine-tuned matching, use the dict described below.

  • A python dict with the following entries:
    ‘values’ - (optional) a python list of strings that are

    joined by the ‘join’ key to create a single regular expression. If this a ‘values’ list is not provided, it’s assumed to be [‘.*’], which matches all patterns.

    ‘join’ - (optional) the character with which to join all

    provided values to form a single regular expression. If the ‘join’ value is not provided, it defaults to ‘|’, the operator for logical or.

    ‘sub’ - (optional) a string on which string substitution

    will be performed for all elements in the ‘values’ list. If this value is not provided, it defaults to ‘^%s$’, which causes the entire string to be matched. This string uses python’s standard string formatting operations: http://docs.python.org/library/stdtypes.html#string-formatting-operations but should only use a single ‘%s’

valid_dict[‘allowed_values’][‘flag’] - (optional) a python string
representing one of the python re module’s available regexp flags. Available values are: ‘ignoreCase’, ‘verbose’, ‘debug’, ‘locale’, ‘multiline’, ‘dotAll’. If a different string is provided, no flags are applied to the regular expression matching.
example valid_dicts:

# This would try to match ‘[a-z_]* in ‘sample_string_pattern’ valid_dict = {‘value’ : ‘sample_string pattern’,

‘allowed_values’ : {‘pattern’: ‘[a-z_]*’}}

# This would try to match ‘^test$|^word$’ in ‘sample_list_pattern’ valid_dict = {‘value’ : ‘sample_list_pattern’,

‘allowed_values’: {‘pattern’: [‘test’, ‘word’]}}

# This would try to match ‘test.words’ in sample_dict_pattern valid_dict = {‘value’ : ‘sample_dict_pattern’,

‘allowed_values’: {‘pattern’: {
‘values’: [‘test’, ‘words’], ‘join’: ‘.’, ‘sub’: ‘%s’}

This function builds a single regular expression string (if necessary) and checks to see if valid_dict[‘value’] matches that string. If not, a python string with an error message is returned. Otherwise, None is returned.

class invest_natcap.iui.iui_validator.TableChecker

Bases: invest_natcap.iui.iui_validator.FileChecker, invest_natcap.iui.iui_validator.ValidationAssembler

This class provides a template for validation of table-based files.

get_matching_fields(field_defn)
verify_fields_exist(field_list)

This is a function stub for reimplementation. field_list is a python list of strings where each string in the list is a required fieldname. List order is not validated. Returns the error string if an error is found. Returns None if no error found.

verify_restrictions(restriction_list)
class invest_natcap.iui.iui_validator.URIChecker

Bases: invest_natcap.iui.iui_validator.Checker

This subclass of Checker provides functionality for URI-based inputs.

check_exists(valid_dict)

Verify that the file at valid_dict[‘value’] exists.

check_permissions(permissions)

Verify that the URI has the given permissions.

permissions - a string containing the characters ‘r’ for readable,
‘w’ for writeable, and/or ‘x’ for executable. Multiple characters may be specified, and all specified permissions will be checked. ‘rwx’ will check all 3 permissions. ‘rx’ will check only read and execute. ‘’ will not check any permissions.

Returns a string with and error message, if one is found, or else None.

class invest_natcap.iui.iui_validator.ValidationAssembler

Bases: object

This class allows other checker classes (such as the abstract TableChecker class) to assemble sub-elements for evaluation as primitive values. In other words, if an input validation dictionary contains two fields in a table, the ValidationAssembler class provides a framework to fetch the value from the table.

assemble(value, valid_dict)

Assembles a dictionary containing the input value and the assembled values.

class invest_natcap.iui.iui_validator.ValidationThread(validate_funcs, type_checker, valid_dict)

Bases: threading.Thread

This class subclasses threading.Thread to provide validation in a separate thread of control. Functionally, this allows the work of validation to be offloaded from the user interface thread, thus providing a snappier UI. Generally, this thread is created and managed by the Validator class.

get_error()

Returns a tuple containing the error message and the error state, both being python strings. If no error message is present, None is returned.

run()

Reimplemented from threading.Thread.run(). Performs the actual work of the thread.

set_error(error, state='error')

Set the local variable error_msg to the input error message. This local variable is necessary to allow for another thread to be able to retrieve it from this thread object.

error - a string. state - a python string indicating the kind of message being

reported (e.g. ‘error’ or ‘warning’)

returns nothing.

class invest_natcap.iui.iui_validator.Validator(validator_type)

Bases: invest_natcap.iui.registrar.Registrar

Validator class contains a reference to an object’s type-specific checker. It is assumed that one single iui input element will have its own validator.

Validation can be performed at will and is performed in a new thread to allow other processes (such as the UI) to proceed without interruption.

Validation is available for a number of different values: files of various types (see the FileChecker and its subclasses), strings (see the PrimitiveChecker class) and numbers (see the NumberChecker class).

element - a reference to the element in question.

get_error()

Gets the error message returned by the validator.

Returns a tuple with (error_state, error_message). Tuple is (None, None) if no error has been found or if the validator thread has not been created.

init_type_checker(validator_type)

Initialize the type checker based on the input validator_type.

validator_type - a string representation of the validator type.

Returns an instance of a checker class if validator_type matches an
existing checker class. Returns None otherwise.
thread_finished()

Check to see whether the validator has finished. This is done by calling the active thread’s is_alive() function.

Returns a boolean. True if the thread is alive.

validate(valid_dict)

Validate the element. This is a two step process: first, all functions in the Validator’s validateFuncs list are executed. Then, The validator’s type checker class is invoked to actually check the input against the defined restrictions.

Note that this is done in a separate thread.

returns a string if an error is found. Returns None otherwise.

invest_natcap.iui.iui_validator.get_fields(feature)

Return a dict with all fields in the given feature.

feature - an OGR feature.

Returns an assembled python dict with a mapping of fieldname -> fieldvalue

Model UI

class invest_natcap.iui.modelui.ModelUI(uri, main_window)

Bases: invest_natcap.iui.base_widgets.ExecRoot

queueOperations()
class invest_natcap.iui.modelui.ModelUIRegistrar(root_ptr)

Bases: invest_natcap.iui.base_widgets.ElementRegistrar

invest_natcap.iui.modelui.getFlatDefaultArgumentsDictionary(args)
invest_natcap.iui.modelui.main(uri, use_gui=True)

Registrar

class invest_natcap.iui.registrar.DatatypeRegistrar

Bases: invest_natcap.iui.registrar.Registrar

eval(mapKey, opValues)
class invest_natcap.iui.registrar.Registrar

Bases: object

eval(mapKey, opValues)
get_func(mapKey)
update_map(updates)

Module contents

invest_natcap.iui.get_ui_logger(name)