Python bindings
The geodms module embeds the GeoDMS engine in Python: a script loads a configuration, finds its items, changes an expression and reads the calculated values back, in the same process. It is installed from PyPI:
pip install geodms
import geodms
engine = geodms.Engine() # one per process
config = engine.load_config("model.dms")
item = config.const_root().find("/results/total").asDataItem()
item.update() # calculates the item and what it depends on
print(item.get_value_as_float(0))
A process has one Engine and one loaded configuration at a time; closing a configuration gives the rules. The item path is relative to the root of the configuration, so for a model.dms that holds container model { container results { parameter<float64> total := 1.5 + 2.0; } } the script prints 3.5.
The geodms module runs the engine inside the Python process. Exchanging data files between a GeoDMS configuration and a separate Python script is another way to combine the two: write and read tabular data as Parquet (or Csv) and, if needed, let GeoDMS run the script on demand with Exec_ec. GeoDMS through Python compares the three ways.
Installation
The package geodms on PyPI has wheels for CPython 3.12, 3.13 and 3.14 on 64-bit Windows and on 64-bit Linux with glibc 2.39 or newer, such as Ubuntu 24.04, Debian 13, Fedora 40 and RHEL 10, and pip picks the one that matches the Python that runs it. A wheel holds the engine and the libraries it uses, such as GDAL, PROJ, GEOS and Arrow, together with the GDAL and PROJ data and the GeoDMS library folder, so import geodms needs no GeoDMS setup and no change to sys.path or PATH. The licence texts of the bundled libraries are in the .dist-info/licenses folder of the wheel.
On Windows the libraries in the wheel carry names of their own, so that the module can share a process with the GDAL, PROJ and SQLite of QGIS, of another Python package or of a GeoDMS setup, whichever was loaded first. On Linux GDAL, PROJ, GEOS and the libraries they use are linked into the engine libraries themselves, which hide their symbols, so that the engine calls its own copies. There the module shares a process with another GDAL whichever was loaded first: with an osgeo that Python imports in the usual way, before or after geodms, and with a GDAL that is already in the global symbol scope of the process when geodms is imported, as in a program that links GDAL itself or after a library was loaded with RTLD_GLOBAL.
The version of the package is the GeoDMS version, and PyPI has the full releases only. To use the engine of a particular release, for a configuration written for it, pin the version:
pip install geodms==20.26.0
In the GLOBIO environment
The GLOBIO 4 model runs in a conda environment with GDAL 3.1.4 and CPython 3.9, globio4env. For that environment the package geodms-globio holds the GLOBIO build of GeoDMS, made with the GDAL, PROJ and GEOS of that environment, for CPython 3.9 on 64-bit Windows. It is imported as geodms as well:
pip install geodms-globio
The wheel carries its own copies of those libraries under names of their own, so a script can import osgeo and geodms in either order, and each uses its own copy of the same GDAL version. Do not install geodms and geodms-globio in one environment: both install the package geodms.
From a GeoDMS setup
The setups also contain the module, for 64-bit CPython 3.12, 3.13 and 3.14; 3.9 is provided only by the GLOBIO (.g) setup. A setup holds one ABI-tagged geodms extension per CPython minor, and Python selects the matching file. In the Linux setup it is in the installation folder /opt/ObjectVision/GeoDms<version>.l, and adding that folder to sys.path is enough. In a Windows setup, add the installation folder to sys.path, so that Python finds the module, and put it at the front of PATH, so that the engine finds GDAL, which it loads only at its first use:
import os
import sys
geodms_dir = r'C:\Program Files\ObjectVision\GeoDms20.26.0.m' # the folder of the installed version
sys.path.append(geodms_dir)
os.environ['PATH'] = geodms_dir + os.pathsep + os.environ['PATH']
from geodms import *
Imported this way, the engine uses the gdal.dll of the setup, and import geodms stops with an error when a gdal.dll from another folder is already loaded in the process, because the engine would bind to that copy. Import geodms before anything that loads another GDAL, or use the wheel.
The setup does not bundle Python itself. Release builders supply the development installations through PYTHON312_ROOT, PYTHON313_ROOT and PYTHON314_ROOT (and PYTHON39_ROOT for the GLOBIO flavour), or the corresponding ABI-specific *_INCLUDE_DIR and *_LIBRARIES pairs. The Linux build takes the headers of each version from the python3.XY-dev package.
Getting started
The code examples below show how to use the functions of the module: loading a configuration and querying it, building a configuration in memory, setting parameter values and reading results back. They use the names of the module without prefix, after:
from geodms import *
Retrieving the geodms version:
dms_version = version()
Initializing the geodms module:
dms_engine = Engine()
Loading and querying a configuration
Loading a dms configuration:
dms_config = dms_engine.load_config('./prj/config.dms')
Get the root item of a loaded dms configuration:
root = dms_config.root()
Finding an item in a loaded dms configuration from the root item:
parameters = root.find("/parameters")
Testing if the item is found by asserting that it is not null:
if (parameters.is_null()):
raise Exception(f"Cannot find output item: '/parameters'")
Get the name (or full path) of a found item:
item_name = parameters.name()
item_full_name = parameters.full_name()
Get the dms expression of a found item:
item_expr = parameters.expr()
Iterating over the direct sub-items of a container (the kind of an item follows from isUnitItem() / isDataItem()):
for child in root.sub_items():
kind = 'unit' if child.isUnitItem() else ('attr' if child.isDataItem() else 'container')
print(child.name(), kind)
Inspecting an item that failed to calculate:
reason = some_item.fail_reason() # empty string when the item is valid
Listing the red items of a configuration
The GUI colours an item red when determining its meta info has failed. update_metainfo() runs exactly that step and reports its outcome:
ok = some_item.update_metainfo() # False when the item failed
if not ok:
print(some_item.full_name(), some_item.fail_reason())
update_metainfo() resolves the calculation rule, the domain and values units, the storage and the sub-items the rule implies, which is everything a configuration error shows up in, and reads no primary data. update() does read primary data, of the item and of all of its suppliers, which for a raster attribute is a full calculation; that is why a configuration-wide check must use update_metainfo() and not update().
Template bodies are inert and are not meant to be updated at all, so a walker skips them with in_template() (true for a template and for everything inside one; is_template() is true for the template item itself):
def red_items(item):
if item.in_template():
return
if not item.update_metainfo():
yield item.full_name(), item.fail_reason()
for child in item.sub_items():
yield from red_items(child)
for name, reason in red_items(config.const_root()):
print(f"{name}: {reason}")
An item that failed an earlier calculation reports False here too, exactly as the tree-view colours it red: its meta info is fine, but the item is not valid.
Change the expression of a found item:
out_dir = root.find("/parameters/input/OutDir")
out_dir.set_expr("path/to/new/out/dir")
Update an item:
target_item_fullname = "dms/target/item"
target_item = root.find(target_item_fullname)
if target_item.is_null():
raise Exception(f"Cannot find output item: {target_item}")
target_item.update()
Closing a configuration
A process has one loaded configuration at a time. A configuration stays loaded for as long as the script holds its Config or any item that came from it, so an item can also be used without a variable for the Config:
total = dms_engine.load_config('./prj/config.dms').const_root().find('/results/total').asDataItem()
total.update()
print(total.get_value_as_float(0))
close() closes a configuration and releases its items. In a with block the configuration is closed at the end of the block, also when the block ends with an exception:
with dms_engine.load_config('./prj/config.dms') as dms_config:
total = dms_config.const_root().find('/results/total').asDataItem()
total.update()
print(total.get_value_as_float(0))
# here the configuration is closed
Every method of an item of a closed configuration, is_null() included, raises a RuntimeError that says that the configuration has been closed, and so do root() and const_root() of a closed Config. To use the items again, load the configuration again.
load_config() and create_config_root() refuse to load a configuration while the Config of the loaded one still exists, with a message that names close(). When only items of the loaded configuration are left, they close it and load the new one, and those items raise from then on. When the interpreter exits, a configuration that is still loaded is closed before Python releases the remaining objects. That happens in an atexit handler that import geodms registers, so a handler that the script registers after the import still finds its items usable, and one that it registers before the import finds them closed.
A Config and its items keep the Engine alive. A process has one Engine at a time; a new one can be made once the previous Engine, its configurations and their items are all gone.
Building a configuration in memory
Instead of loading a .dms model script, a configuration can be built from scratch in Python. Start from an empty configuration root:
engine = Engine()
config = engine.create_config_root('demo') # an empty in-memory configuration
root = config.root()
Add sub-containers, units, attributes and parameters:
# a sub-container
data = root.add_container('data')
# a domain unit of a basic value type, sized by an expression. A domain's element
# count comes from its calculation rule; range(uint32, 0, n) defines an n-element domain.
entities = root.create_unit('Entity', 'uint32')
entities.set_expr('range(uint32, 0, 5)')
# an attribute over that domain, with a values unit of a basic value type
value = data.add_attribute('value', entities.asConst(), 'float64')
# an attribute with an explicit domain unit, values unit and value composition
geometry = data.add_data_item('geometry', point_domain, point_values, ValueComposition.Polygon)
# a parameter (Void domain) of a basic value type
nr_entries = root.add_param('nrEntries', 'uint32')
Attach a storage manager (e.g. to read a source file), or force in-memory / calculator-only operation:
src = root.add_container('src')
src.set_storage_manager('path/to/source.gpkg', 'gdal.vect', read_only=True)
derived.disable_storage()
Define derived items purely by an expression, exactly as in a model script:
doubled = data.add_attribute('doubled', entities.asConst(), 'float64')
doubled.set_expr('value * 2.0')
total = root.add_param('total', 'float64')
total.set_expr('sum(data/value)') # names resolve as in a model script, here from the root
The Engine also exposes the shared default unit of a basic value type (handy as a values unit) and the Void unit (the domain of every parameter):
f64 = engine.default_unit('float64')
void = engine.void_unit()
Setting parameter values
Parameters (items with a Void domain) can be assigned a value directly:
nr_entries.set_param_int(5)
pi = root.add_param('pi', 'float64'); pi.set_param_float(3.14159)
greeting = root.add_param('greeting', 'string'); greeting.set_param_str('hello from python')
print(pi.get_param_float()) # 3.14159
Querying results (Primary Data Access)
After updating an item, its values can be read back through the Primary Data Access functions of a DataItem. The read-only tree gives one directly: asDataItem() on an item of config.const_root() returns a DataItem.
result = config.const_root().find('/data/doubled')
result.update() # (re)calculate first
di = result.asDataItem()
print(di.size()) # number of values (= domain unit count)
print(di.get_value_as_float(0)) # a single value, by index
print(di.get_values_as_float_list()) # all values as a python list
print(di.get_values_as_int_list()) # all values, converted to int
# a value of a string attribute
print(config.const_root().find('/greeting').asDataItem().get_value_as_str(0))
On an item of the mutable tree of config.root(), asDataItem() returns a MutableDataItem, which writes values; its own asDataItem() gives the DataItem that reads them, as in root.find('/data/doubled').asDataItem().asDataItem(). The builders, such as add_attribute(), also return a MutableDataItem.
Writing primary data into a fresh in-memory attribute is done in bulk; the list length should equal the domain element count:
value.set_values_from_float_list([1.0, 2.0, 3.0, 4.0, 5.0])
value.set_values_from_int_list([1, 2, 3, 4, 5])
The list must hold exactly one value per domain element: a list of another length is an error. The values are written tile by tile, so a domain of more than one tile is filled as well.
A data item also exposes its domain and values unit, and the unit its entity count / numeric range:
dom = di.domain_unit()
print(dom.value_type_id(), dom.count()) # e.g. ValueTypeId.UInt32 5
print(di.values_unit().value_type_id()) # e.g. ValueTypeId.Float64
print(di.values_unit().value_type_id().name) # 'Float64'
API reference
module geodms
version()→str: the GeoDMS version stringValueComposition, an enum:Single,Polygon,Sequence,MultiPointValueTypeId, an enum of value types:Float64,Float32,UInt32,Int32,UInt16,Int16,UInt8,Int8,UInt64,Int64,Bool,UInt4,SPoint,WPoint,IPoint,UPoint,FPoint,DPoint,String,Void,Unknown
class Engine
The engine of the process. Constructing it also registers a message callback that prints GeoDMS diagnostics (warnings, calculation errors) to stderr, so failures are visible rather than silently yielding undefined values.
Engine(): construct; a process has oneEngineat a timeload_config(config_file_name)→Config: load a.dmsconfiguration, one at a time, as closing a configuration describescreate_config_root(name)→Config: create an empty in-memory configuration, under the same ruledefault_unit(value_type)→UnitItem: the shared default unit of a basic value typevoid_unit()→UnitItem: theVoidunit (domain of parameters)
class Config
root()→MutableTreeItem: the (mutable) root itemconst_root()→ConstTreeItem: a read-only root itemclose(): close the configuration, after which every method of its items raises; closing a closed configuration does nothingwith engine.load_config(path) as config:closes the configuration at the end of the block
class ConstTreeItem and MutableTreeItem
An item in the tree.
is_null()→boolfind(item_path)→ tree item: look up an item by pathname()→str,full_name()→str,expr()→str,descr()→strsub_items()→list,parent()→ tree item,fail_reason()→strupdate(): calculate/update the item (and its storage, if configured)update_metainfo()→bool: determine the meta info without calculating;Falsefor a failed item, whose reasonfail_reason()then givesin_template()→bool,is_template()→bool:in_template()is true for a template and for every item inside oneisDataItem()/asDataItem(): test / cast to a data item, aDataItemfrom aConstTreeItemand aMutableDataItemfrom aMutableTreeItemisUnitItem()/asUnitItem(): test / cast to a unit item
asDataItem() and asUnitItem() raise an exception, on both the read-only and the mutable tree item, for an item of another kind and for the null item that find() returns for a name that does not exist. Test with isDataItem(), isUnitItem() or is_null() first where either can happen.
ConstTreeItem additionally exposes first_subitem() and next() for tree traversal. MutableTreeItem additionally exposes:
set_expr(str),set_descr(str),asConst()add_container(name)→MutableTreeItemcreate_unit(name, value_type)→MutableUnitItemadd_data_item(name, domain, values, vc=ValueComposition.Single)→MutableDataItemadd_attribute(name, domain, values_value_type)→MutableDataItemadd_param(name, values_value_type)→MutableDataItemset_storage_manager(storage_name, storage_type, read_only=True),disable_storage()
class UnitItem and MutableUnitItem
is_null(),name(),full_name(),value_type_id()→ValueTypeIdcount()→int,get_range()→(begin, end)MutableUnitItem:set_expr(str)(e.g.'range(uint32, 0, n)'to size a domain),set_count(n),set_range(begin, end),asConst(). The range thatset_countorset_rangegives a unit is lost when the unit is first used, which leaves a uint32 unit with 4294967294 elements (#1373); size a domain withset_exprinstead.
class DataItem
is_null()→boolname(),full_name()domain_unit()/values_unit()→UnitItem,value_composition()size()→int,update()get_value_as_float(i),get_value_as_int(i): the value at indexi, converted tofloatorintget_values_as_float_list(),get_values_as_int_list(): all values, convertedget_value_as_str(i)→str: the value at indexiof a string attribute; it does not convert, and raises for an attribute of another value type.LockAndGetStringValue(i)is the same function under its older name.
class MutableDataItem
asDataItem()→DataItem: the read-only view, which reads the values;domain_unit(),values_unit(),value_composition(),size(),name(),full_name(),update(),set_expr(str)set_values_from_float_list(list),set_values_from_int_list(list): write primary data (list length = domain element count)set_param_float(v),set_param_int(v),set_param_str(v),get_param_float()
example usage
Adapted from python/tst/UnitTests.py, which with the option --installed tests the module installed by pip, and otherwise the module in the build folder bin\Release\x64, which it adds to sys.path and PATH as for a setup:
from geodms import *
# initialise the engine and load a configuration
engine = Engine()
config = engine.load_config('basic_data_test.dms')
# navigate the item tree from the root
root = config.root()
param_item = root.find("/parameters/test_param")
print(param_item.is_null()) # False if found
# change an expression and (re)calculate a dependent result
param_item.set_expr("3b")
result_item = root.find("/export/IntegerAtt")
result_item.update() # updates the item and writes its storage, if configured
A complete in-memory example (build a configuration without a model script and read results back) is available in python/tst/InMemoryConfig.py.
since version
- 15.0.1: the geodms module, with the bindings that load a configuration and query it.
- 20.5.0: building a configuration in memory, setting parameter values and Primary Data Access, with
ValueTypeId,create_config_root(),default_unit(),void_unit(),const_root(),full_name(),descr(),sub_items(),parent(),fail_reason(), the building methods ofMutableTreeItem, the classesUnitItem,MutableUnitItemandMutableDataItem, and the members ofDataItemother thanis_null(),name()andLockAndGetStringValue(). - 20.23.1:
update_metainfo(),in_template()andis_template();fail_reason()on an item that has not failed; the exception ofasDataItem()andasUnitItem()for an item of another kind or a null item; andset_values_from_float_list()andset_values_from_int_list()on a domain of more than one tile. - 20.26.0: the wheels on PyPI,
pip install geodms. In the wheels of 20.26.0,import geodmsstops with an error when agdal.dllfrom another folder, such as that of a GeoDMS setup, is already loaded; import geodms first. - 20.29.0: a wheel shares the process with a
gdal.dllthat was loaded before it;close()and thewithblock ofConfig, and an item that keeps its configuration loaded without a variable for theConfig. - 20.30.0: the wheels for Linux, the module in the Linux setup, and the package
geodms-globiofor the GLOBIO environment.