Welcome to Spine Toolbox’s User Guide!
Spine Toolbox is an application, which provides means to define, manage, and execute complex data processing and computation tasks, such as energy system models.
If you are new to Spine Toolbox, Getting Started section is a good place to start. If you want to run SpineOpt.jl using Spine Toolbox, How to Set up SpineOpt.jl provides step-by-step instructions on how to get started. For information on how to set up Python, Julia, or Gams for Spine Toolbox, see Setting up Consoles and External Tools. Please see Settings chapter for information on user customizable Spine Toolbox settings. If you need help in understanding the terms we use throughout the app and this User Guide, please check the Terminology section. If you want to contribute to this project, please see the Contribution Guide. The last section contains the complete code reference of Spine Toolbox.
What’s New?
Here’s the Changelog for Spine Toolbox.
# Changelog
All **notable** changes to this project are documented here.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
## [Unreleased]
### Added
### Changed
### Deprecated
### Removed
### Fixed
### Security
## 0.8.1
### Added
- Importer: it is now possible to reorder source tables by dragging and dropping.
- Importer: it is now possible to reorder mappings by dragging and dropping.
- Importer: it is now possible to copy mappings between source tables by dragging selected
mappings from Mappings list onto destination source table item.
### Removed
- Scenario active flag mappings have been removed from Importer and Exporter.
The flag is not used anywhere and has not been accessible in Database editor
for a long time.
## 0.8.0
### Added
- New context menu action (Select superclass) for entity class items in the entity tree.
- Added Tool Specification type (Python, Gams, etc.) icons on Design View.
- There is now a new filter type, Alternative filter available in Link properties.
Unlike scenario filters, the execution is not parallelized.
Instead, a successor item sees parameter values of all selected alternatives.
Because of this behavior,
alternative filters cannot be used at the same time with scenario filters.
Link properties tab has a combo box that lets one choose which filter type to use.
### Changed
#### Spine data structure
Many parts of the Spine data structure have been redesigned.
- *Entities* have replaced objects and relationships.
Zero-dimensional entities correspond to objects while multidimensional entities replace the former relationships.
Unlike relationships, the *elements* of multidimensional entities can now be other multidimensional entities.
- Simple inheritance is now supported by *superclasses*.
- Tools, features and methods have been removed.
The functionality that was previously implemented using the is_active parameter
has been replaced by *entity alternatives*.
Entity classes have a default setting for the entity alternative called *active by default*.
Database migration should automatically replace tools, features and methods
by entity alternatives and set active by default to whatever default value `is_active`
or similar parameter had.
The `is_active` parameter is not removed from entity classes but its values are.
- Note that new zero-dimensional entity classes have *active by default* set to `false` initially.
This means that the entities of those classes are hidden when using scenario filters
unless specifically shown using entity alternatives.
#### Miscellaneous changes
- "Rubber band" selection of items in Design and Graph views is now done with **left mouse button**
(no need to press Ctrl anymore). The views can be dragged around by holding the **right mouse button**.
- Spine Database Editor now remembers the configuration of the docs in each view for a specific URL. The docks
can be reset from the hamburger menu **View->Docks...->Reset docks**.
- You can now select a different Julia executable & project or Julia kernel for each Tool spec.
This overrides the global setting from Toolbox Settings.
- Headless mode now supports remote execution (see 'python -m spinetoolbox --help')
- Commit Viewer's UI has undergone some redesigning and can now handle large databases.
### Removed
- Project dock widget
- Dependency on Dagster
## [0.7.4]
### Changed
- Microsoft build tools are not needed anymore when installing Toolbox requirements on Python 3.10 and up.
## [0.7.3]
### Added
- On Toolbox startup, a link appears in Event log that opens Upgrade notification window
offering information about the upcoming 0.8 update.
## [0.7.2] - 2023-12-04
### Added
- Data Connection items now support schemas in database references
- Importer Specification Editor now supports database schemas
## [0.7.1] - 2023-10-06
### Added
- Allow choosing of highlight color for items found in entity graph
### Fixed
- Fixed issues when remote databases were used as references in Data Connections
- Fixed a bug where the order of scenario alternatives would be messed up when copy-pasting
the alternatives in the Scenario Tree
- Fixed a bug with time series plots
- Fixed issues with Pivot table
## [0.7.0] - 2023-08-25
### Added
- Support for version 11 Spine Toolbox projects.
- Executable Tool Specifications can be used to run any (shell) command. This enhancement
duplicates the functionality of Gimlet project items and makes them obsolete.
- There is now an option to select if new scenarios or tools are automatically used
for filtering in Link properties.
- The new "Filer validation" button in Link properties allows forcing at least one scenario or tool
filter to be checked.
- Python 3.11 support.
- PySide6 support. The app has been ported from PySide2 to PySide6.
- In addition to dragging and dropping,
it is now possible to copy alternatives from Alternative tree and paste them to the scenario tree
in Database editor.
- Scenarios can now be copied and pasted between databases in Database editor.
- Scenarios can now be duplicated in Database editor.
- Tool project item's Python and Julia consoles can now be killed from the right-click context menu.
A killed console can be restored by restarting it.
- A new option "Kill consoles at the end of execution" has been added to Tool properties,
that kills Python and Julia console processes after execution saving some memory and computing resources.
- A new option "Log process output to a file" has been added to Tool properties,
that logs all the 'console' output of the Tool to a file in the logs subfolder.
- You can now open a 'Detached' Jupyter Console on any kernel you have installed in your system from the *Consoles*
main window menu.
- "Make Julia Kernel" and "Make Python Kernel" buttons in Settings->Tools page. Clicking them creates a new
Julia or Python kernel based on selected Julia/Python executable on the same page if the kernel does not exist.
If the kernel already exists, it is selected automatically.
- ``project.json`` now has an experimental option ["project"]["settings"]["enable_execute_all"] which disables the
Execute Project button when set to ``false``. The option is currently not settable in the UI.
- New context menu action (Find...) to find items by name in DB editor's entity graph.
### Changed
- The console settings of Python tools as well as the command and shell settings of executable tools
are now treated as project-specific data
and stored in ``<project root>/.spinetoolbox/local/specification_local_data.json``.
This should make it easier to share projects over e.g. Git.
- Scenario and tool filters are now ON by default.
If new scenario or tool is added to a database it will be automatically selected in outgoing connections.
NOTE: In existing projects, if a connection did not have any scenarios/tools selected,
they will all be selected when opening a project for the first time after this change.
If this is not desired, the scenarios/tools need to be deselected manually
before saving the project on disk.
- Project name is now the project directory name and cannot be changed unless by moving the project to another
directory manually or by using the File -> Save project as... menu item.
- Scenario filters now filter unrelated scenarios and alternatives as well.
- Alternative/Scenario tree in Database editor has been split into separate Alternative tree and Scenario tree docks.
This will hopefully make dragging and dropping alternatives to scenarios easier.
- Logic of executing selected project items. URL's passed by unselected Data Transformers are not included automatically
into selective execution anymore. When selecting project items for execution, make sure to select also preceding
Data Transformers if needed.
- Names for duplicate items/scenarios/etc now use the format `prefix (xx)` instead of `prefix xx`.
Duplicating a previously duplicated item now has the number `xx` incremented instead of having a new number appended.
- "Open kernel spec editor" buttons in Settings->Tools page have been changed "Make Julia kernel" and
"Make Python Kernel" buttons
-
### Deprecated
### Removed
- Python 3.7 support
- GdxExporter project item. Please use Exporter instead.
- Gimlet project item. Please use Tool instead.
- The possibility to import parameter values when importing object groups using Importer.
Existing mappings will not import group parameters anymore.
Please add explicit parameter import mappings if needed.
- The possibility to export parameter values when exporting object groups using Exporter.
Existing mappings will not export group parameters anymore.
Please add explicit parameter export mappings if needed.
- Execute in work setting in Tool Specification Editor. Please use Execute in work setting
in Tool Properties instead.
- Kernel Spec Editor widget and the "Open Kernel Spec Editor" button in Tool Specification Editor
### Fixed
- Deleting the last item of a mapping in the importer specification editor no longer disables the 'add' button.
- Group Id's for Jupyter Consoles
- Kill consoles at end of execution for Jupyter Consoles
- Crash when typing exit, exit(), quit, or quit() into Jupyter Console
### Security
## [0.6.5] - 2021-09-08
### Added
- Support for loops has been added. Loops can be created using a special *loop link* which is initiated by
holding down the **Alt** key while drawing a new link in Design view.
- Performance boost for Spine Db Editor when working with large databases.
### Changed
- Installation does not require cx-Oracle and psycopg2 packages anymore.
- install_requires and requirements.txt files have been revised.
### Fixed
- Spine Db Editor Graph View works on Python 3.7 again.
- Spine Db Editor Graph View 'Add objects' and 'Save position' actions.
- Export to SQLite in Spine Db Editor
## [0.6.3] - 2021-09-03
### Added
- Plenty of stability improvements and bug fixes
### Fixed
- Fixed 'ImportError: DLL load failed while importing win32api' on (Conda) Python 3.8 when trying to execute Tools
in Jupyter Console
## [0.6.1] - 2021-06-28
### Added
- Data Transformer now supports parameter value transformations.
- Project execution shortcuts: F5 to execute all DAGs, F6 to execute selected items
and F7 to stop execution.
- Time series, maps and other compound values have gained the ability to have names for their indexes.
Index names can be edited in parameter value editors, and they are also supported by Importer and Exporter items.
- Support for running Python Tools (specifications) in a Conda environment
- Execution mode (kernel spec, console, interpreter) can now be selected individually for each Python
Tool specification
### Changed
- Data Transformer's specification editor has now a new interface.
- Parameter renaming in Data Transformer requires now entity class names to identify the parameters.
Data Transformer's icon will show a notification if class names are missing.
- Installation instructions advice to install directly from PyPI.
- Stand-alone DB Editor is now opened with the `spine-db-editor [URL]` command
- Python settings on the *Tools* page of *File->Settings* are now the default settings for new Python Tool
specifications. I.e. they are not global settings anymore.
### Deprecated
- GdxExporter has been deprecated. Use the general purpose Exporter item instead.
GdxExporter will be removed in a future release. Please replace existing items by Exporter.
## [0.6.0-final.2] - 2021-06-03
### Fixed
- [win-x64] Running Python or Julia Tools does not open an extra console window anymore
### Security
- urllib3 v1.26.5 now required because of a security vulnerability in earlier versions
## [0.6.0-final.1] - 2021-06-01
### Fixed
- Event Log and Item Execution Logs now automatically scroll to the bottom when there are new messages
- [win-x64] Resolve correct GAMS, Python, and Julia paths in Settings->Tools
## [0.6.0-final.0] - 2021-05-07
### Added
- Support for parallel/multicore processing
- New project item: Data Transformer. Can be used to configure Spine database filters for successor items.
Currently, it supports renaming entity classes.
- New project item: Exporter. A general-purpose tabular data exporter.
- Support for version 3 Spine Toolbox projects and an automatic upgrade of version 2 projects to version 3.
- Support for version 4 Spine Toolbox projects.
- Support for version 5 Spine Toolbox projects.
- Support for version 6 Spine Toolbox projects.
- Support to create sysimages for Julia tools.
- New requirement: jill, for installing Julia.
- The SpineOpt configuration assistant has been moved from File->Configuration assistants,
to File->Settings->Tools->Julia, and renamed to SpineOpt Installer.
- New wizard to install Julia, accessible from File->Settings->Tools->Julia.
- File->Close project option
- Support for Python 3.8
- Automated kernel creation, if the user selects to run tools in console without having created a kernel.
- Option to pack CSV resource files into one datapackage.json file for advertising, available from Link properties.
- Option to color project item icons in the toolbar, available frm File->Settings->General.
- Reorganize project item icons in the toolbar with drag and drop.
### Changed
- Project Item (Tool, Data Store, Importer, etc.) code has been removed from Spine Toolbox.
Project Items are now in a separate package called spine_items, which is upgraded at Spine
Toolbox's startup.
- Importer item now applies the same mapping to all input files. If the user needs to apply different
mappings, they need to create different Importers. The specification can be shared using the json file.
- The .gdx exporter project item is now called GdxExporter.
- [win-x64] Installer does not require admin rights anymore
- [win-x64] Installer always asks for an installation directory, even if a previous installation exists
- [win-x64] Installer wizard style changed to modern
### Removed
- Combiner project item. The same functionality can be achieved by connecting a Data Store to another Data Store.
- Upgrade support for original (.proj file based) Spine Toolbox projects.
- Python 3.6 is no longer supported.
- The Spine Datapackage Editor is gone. There wasn't enough reason to keep this widget
- The app no longer checks that Spine dependencies are up to date. Users are asked to follow the upgrade procedure
which involves manually upgrading requirements after pulling the latest master branch.
### Fixed
- [win-x64] returning_process.py when frozen
- Traceback in GdxExporter when there are indexing settings for a parameter that is not in the database
- Bug in installing Plugins
- Traceback when removing Plugins
## [0.5.0-final.1] - 2020-02-03
### Added
- Tutorial for case study A5 in the documentation
### Fixed
- [win-x64] Fixed /tools/python.exe by adding sitecustomize.py and a missing python37.dll
## [0.5.0-final.0] - 2020-12-14
### Added
- Exporting graphs as PDF files from the *Graph* menu in the Data Store form.
- Pruning entire classes from the graph view. The option is available both from the *Graph* menu and
from *Entity Graph* context menus. Also, pruned items can be restored gradually.
- A new Input type *Indexed parameter expansion* is now available in Data Store view's Pivot table.
In this Input type the indexes, e.g. time stamps of time series get expanded as a new dimension in the table.
- Import editor now has a new Source type: Table name. It can be used e.g. to pick an Excel sheet's
or GAMS domain's name as the object class name.
- Import editor now supports multidimensional maps. The number of dimensions can be set using the
*Map dimensions* spin box in mappings options.
- Executing a project from the command line without opening the Toolbox GUI (i.e. headless execution).
The headless execution is enabled by the new command line option ``--execute-only``.
- Toolbox now supports scenarios and alternatives. They can be accessed via Data store view's new Alternative tree.
- New Project Item: Gimlet. Can be used to run any command as part of the workflow
with or without a shell. Supported shells at the moment are cmd and powershell for
Windows and bash for other OS's.
- Python and Julia Kernel spec Editor. Provides the means to make new kernel specs for Python Console and Julia
Console without leaving Spine Toolbox. Kernel (spec) Editor can be found in Settings->Tools tab.
- [win-x64] Includes Tools/python.exe for running Python Tools for systems that do not have a Python installation.
Also, pyvenv.cfg and path.pth files for configuring the included python.exe.
### Fixed
- Signal disconnection issue in Graph View
- Bugs in removing objects and object classes in Spine db editor's Graph View
### Changed
- Data Store Form is now called 'Spine database editor'
- Spine db editor Graph View behavior. Now selecting objects in the object tree not only shows those objects but also
all the cascading relationships. One can still go back to the previous behavior in Settings.
- Moving object items in the graph view also causes relationship icons to follow. This behavior can be disabled in the
Settings.
- Required PySide2 version is now 5.14. The version is checked at startup.
- Indexed parameter handling has been overhauled in Exporter allowing parameters to share indexing domains.
**Note**: Due to numerous changes in the backend, Exporters in old project files will not load properly
and need to be re-configured.
- The way Exporter handles missing parameter values and None values has changed. The item now ignores missing
values instead of replacing them by the default value. Further, there is a new option to replace None values by
the default value and another option to replace Nones by not-a-numbers or skip exporting them.
- The numerical indicator on the upper left corner of project items no longer indicates the execution order for
each individual item because the exact order is not know before the Execute button is actually clicked.
The number still indicates the execution order but may show the same numbers for items in different parallel
branches.
- Project.json file format has been upgraded to version 2. Version 1 project.json files are upgraded to version 2
automatically when a project is opened.
- Default Python interpreter is now {sys.executable} i.e. the one that was used in launching the app.
This affects the Python used by Python Tool specifications and the PyCall used by SpineOpt.jl configuration
assistant.
- [win-x64] Default Python interpreter is the Python in user's PATH if available. If Python is not defined in
user's PATH, the default Python interpreter is the <app_install_dir>/Tools/python.exe.
- User's now need to explicitly choose the kernel specs for the Python Console and the Julia Console. They are
not chosen (nor created) automatically anymore. The kernel specs can be selected in the drop-down menus
in application Settings->Tools.
- Database revision handling has been improved. Id est, the app does not offer to upgrade databases
that are more recent than the current version of Spine Toolbox can handle.
- Links to User Guide and Getting Started documents open only the online versions. The docs have been
published on readthedocs.org.
- Clearing the line edits for Julia executable and Python Interpreter (in Settings->Tools) shows
the full paths to their respective files as placeholder text.
### Deprecated
- CustomQtKernelManager class
### Removed
- python_repl_widget.py
- julia_repl_widget.py
## [0.4.0-final.0] - 2020-04-03
### Added
- A small notification icon is painted next to project items in the design view whenever they
are missing some configuration. Hovering the icon shows tips for completing the
configuration.
- A small icon is painted next to the project items in the design view to show the order in
which they will be executed
- Main Window menu 'File -> Open recent'. Shortcut for opening a recent project.
- A new project item *Exporter* allows a database contained in a *Data Store* to be exported
as GAMS `.gdx` file.
- It is now possible to copy and paste project items for example between projects.
- It is now possible to duplicate project items.
- Changes made in the tree view are also seen in the graph view and viceversa.
- New Setting: *Sticky selection in Graph View*. Enables users to select if they want to use
multi-selection or single selection in the Graph view Object tree when selecting items with
the **left-mouse button**.
- Projects can be saved to any directory
- Project name can be changed in Settings
- The graph view features a short live demonstration that new users can follow to discover
the basic functionality.
- New Setting: *Curved links*. When active, links on the Design View follow a smooth curve
rather than a straight line.
- When execution traverses a link, a small animation is played to denote the flow of data.
Users can set how quick they want this animation to be in Settings. The fastest setting
effectively disables the animation.
- Special 'tag' command line arguments are now available in Tool Specification which expand
to, for example, input database URLS or paths to optional input files when a Tool is executed.
- It is now possible to undo/redo database changes in the Data Store form.
- It is now possible to visualize the history of database changes in the Data Store form. The
option is available in the Session menu.
- Support for Tool command line arguments. You can now give Tool (project item) command line
arguments in addition to Tool Specification command line arguments.
- Undo/Redo in Design View
- It is now possible to add new plots to existing plot windows in Data Store View.
- Objects in Data Store's Tree View are sorted alphabetically
- A new parameter value type, *map* has been added. There is now a dedicated editor to
modify maps. Plotting of non-nested maps is supported, as well.
- [win-x64] importer_program.py has been built as an independent application. This program is
now distributed with the Spine Toolbox single-file installer. When installing Spine Toolbox,
the Importer Program app can be found in the Spine Toolbox install directory
(/importer_program).
- Import preview window now supports copy-pasting mappings and options from a source table to
another
- Import preview window header context-menus for the preview table which, allows users to
change all data types at once.
- Provide data for EditRole for nicer editor experience in MappingSpecModel.
- Red background is displayed for invalid values in MappingSpecModel
- Object tooltips now show the descriptions Data Store view's
### Fixed
- Data advertised by a project item during execution is only accessible by its direct
successors. In other words, resources are passed to the next items in line but not beyond.
- [win-x64] Executing the Importer project item has been fixed on Windows release version
- Bug fixes for Data Store View
- Disappearing object names in entity graph
- Spine db manager error dialogs
- Tool configuration assistant for SpineModel.jl
- [win-x64] A problem with displaying special characters in Process Log when executing the
Importer project item.
- The context menu in Graph view's pivot table resulted in a traceback when an entity class
did not have parameter definitions.
- Combobox delegate in Import preview window had wrong list of choices.
- Don't set mapping to NoneMapping if user gives a None value.
- Exporter now also exports empty object classes and empty parameters into GDX files
- A bug that sometimes made duplicate entries to File->Open recents menu
- Bug where an Excel import with empty rows would return a None in it's get_data_iterator
- [win-x64] Executing Julia tools in the embedded Julia Console
- [win-x64] Setting up Python Console. Installing ipykernel and kernel specs now works.
- [win-x64] Setting up Julia Console. Installing IJulia and kernel specs now works.
- Column indexing in Import Editor. When entering a time or time pattern index column
manually in Import Editor's lower right corner table, the colors in the preview table
failed to update. This should fix the bug and allow column selection both by column index
or column header text.
### Changed
- spinetoolbox is now a Python package. To start the app, use command
`python -m spinetoolbox` or `python spinetoolbox.py` as spinetoolbox.py has been moved to
repository root.
- Tool templates are now called Tool specifications
- File->Open Project opens a file dialog, where you can open projects by selecting an old
<project_name>.proj file or a Spine Toolbox Project directory. Valid Spine Toolbox projects
are decorated with the Spine logo.
- Old style projects (.proj files) cannot be opened anymore. The old style projects need to
be upgraded before opening. You can upgrade your .proj file projects into new ones with
*Project Upgrade Wizard* found in `File->Upgrade project` menu item.
- Project information is not saved to a <project_name>.proj file anymore. This information
is now located in file <project_dir>/.spinetoolbox/project.json. Every Spine Toolbox project
has this file.
- Work directory is now a global setting instead of a project setting
- Renamed *Data Interface* project item to *Importer*. The corresponding category
*Data Importers* was renamed to *Importers*.
- Tree, graph, and tabular views have been merged into one consolidated view. You can choose
your preferred style from the Data Store View's `View` menu.
- The graph view behavior has changed. Now selecting objects in the object tree not only
shows those objects but also all the cascading relationships. This is to facilitate exploring
the system without a previous knowledge.
- importer_program.py now uses the Python interpreter that the app was started with and not
the one that is given by user in Settings -> Tools.
- Importer now uses QProcessExecutionManager for running the importer_program.py
### Removed
- The status bar of the Data store view is gone. Instead, notifications are printed in a box
on the right side of the form.
- Saving project information to .proj files is not happening anymore
## [0.3] - 2019-09-06
### Added
- Welcome message including a link to Getting Started guide.
- Zooming (by using the mouse wheel) is now enabled in Design View. You can also select multiple project.
items by pressing the Ctrl-key down and dragging the mouse.
- New project item icons on Design View.
- Two options for the Design View background (grid or solid). See Settings (F1).
- Python Console (menu View -> Dock Widgets -> Python Console).
- Python interpreter can be selected in Settings (Also Python 2.7 supported).
- Support for Python Tool templates
- Python Tool execution using the command line approach.
- Python Tool execution using the embedded Python Console (checkbox in Settings)
- The Data Store treeview now also has a relationship tree.
- Support for reordering columns in the treeview.
- Selecting 'edit object classes' in the treeview now also allows the icon to be selected.
- Play button to main window Toolbar that executes all Directed Acyclic Graphs in the Project one after another.
- Another Play button to main window Toolbar to execute selected Directed Acyclic Graph. Selecting a DAG happens by
selecting one or more project items belonging to the wanted DAG in the Design View or in Project Items list.
- Stop button to main window Toolbar, which terminates execution.
- Possibility to specify a dedicated Julia project or environment for Spine Toolbox in the settings.
- Feature to Export project to GraphML format. Each graph in Design View is written to its own file. To do this, just
select *Export project to GraphML* from the Project Item list context-menu or from *File ->
Export project to GraphML*.
- New project item: *Data Interface*
- Parameter and relationship parameter values can now be edited in a dedicated editor window in Tree, Graph and Tabular
views. The editor is accessible by right-clicking a value and selecting `Open in editor...`.
- It is now possible to plot parameter and relationship parameter values in Tree, Graph and Tabular views.
### Fixed
- There is now an upper limit on how much text is logged in Event Log and Process Log. The oldest lines are removed
if the limit is exceeded. This fixes a problem with excessive memory usage when running long processes.
- Mouse click problems in Design View
- Mouse cursor problem in Tool Configuration Assistant
- Welcome message is now shown for first time users
- NameError: SpineDBAPIError when executing Data Stores.
- .py files in *spinedb_api\alembic\versions* are now copied to the installation bundle without compiling them to
.pyc files first. Also, if there's a previous version installed, *spinedb_api\alembic* directory is deleted
before installation begins [Win-x64].
- Added missing modules from *spinedb_api\alembic\versions* package into installation bundle [Win-x64].
- *numpy* is now deleted before installation begins so installing over an existing installation of Spine Toolbox
works again [Win-x64].
- *packaging* and *appdirs* packages are now included in the installation bundle [Win-x64].
### Changed
- Selecting the Julia environment in Settings now requires picking the Julia interpreter **file**
(e.g. julia.exe on Windows) instead of the directory where the Julia interpreter is located.
- Selecting the GAMS program (**file**) in Settings now requires picking the GAMS program (e.g. gams.exe
on Windows) instead of the directory where the GAMS program is located.
- All application Settings are now saved using Qt's QSettings class. Old configuration file,
*conf/settings.conf* file has been removed.
- New Spine databases can be created in any backend supported by spinedb_api. The Data Store item properties
have been changed to allow for this.
- Executing Directed Acyclic Graphs instead of just Tools.
- Executing project items does not happen from the Tool Properties anymore. It happens instead by pressing the
Play button in the main window Toolbar.
### Removed
- An unnecessary error dialog in Import Preview widget.
- ConfigurationParser class in configuration.py.
- Execute button in Tool Properties.
- Stop button in Tool Properties.
- Console window that opened in addition to the application window is not shown anymore [Win-x64].
## [0.2] - 2019-01-17
### Added
- New Setting. You can now select whether to delete project item's data directory
when removing a project item.
- Graph View is also available from Data Store items, allowing to insert new
relationships more graphically.
- You can now execute Tools in the work directory or the source directory (where the
main program file is located). The Setting is in the Tool template editor and in Tool
properties.
- Tabular view: New view for Data Store items, allowing to view and edit data in a
pivot table.
- Tool Properties now shows all information about the attached Tool template
- Context-menus for Data Connection Properties, Tool Properties, and View Properties
- Support for optional input files for Tool templates. You can now use Unix style wildcards (`*` and `?`)
to specify the optional files that a Tool may exploit, e.g. `*.csv`.
- Wildcard support for Tool template output files
- Tool template output files now support subdirectories
- You can now create a new (blank) main program file in the Tool template editor by pressing the the *+* button
and selecting `Make new main program`
- A shortcut to Tool template main directory, accessible e.g. in Tool Properties context-menu
- New Setting. You can select whether the zoom in the Graph view is smooth or discrete
- Windows installer default location is /Program Files/SpineToolbox/. When new versions are released, the
installer will automatically upgrade Spine Toolbox to a new version in that directory.
- Support for executing Executable type tools in Linux&Mac. (Windows support was added previously)
- Tool configuration assistant. Available in menu `File->Tool configuration assistant`. Checks automatically
if the Julia you have selected in Settings supports running Spine Model. If not, the required packages are
automatically installed.
### Fixed
- Better support for scaling screen resolutions
- Exporting a datapackage to Spine format failed if datapackage.json was not explicitly saved
### Changed
- Importing items with names into a spinedatabase moved to spinedatabase_api to
allow for easier adding of new import formats in future versions.
- Tool template list is now located in the Project dock widget below the list of Project items
- New look for Spine Datapackage editor
### Removed
- Templates tab in `Project` dock widget.
## [0.1.75] - 2018-11-23
### Added
- New Setting (F1). You can now select whether to delete project item's data
directory when removing a project item.
- Application icon (Spine symbol)
- New installer for 64-bit Windows:
- Installation file extension is now *.exe* instead of *.msi*
- Show license file before installation (users must agree to continue)
- Default install folder is now `C:\Program Files\ `.
- **No** need to *Run as Administrator* even if installed to the default location
because write permissions for sub-folders that need them (\conf, \projects,
\work) are set automatically
- Create a shortcut on desktop (if wanted)
- Create a Start Menu folder (if wanted)
- Uninstaller. Available in the Start Menu folder or in Windows
Add/Remove Programs
- Remove app related registry entries when uninstalling (if wanted)
### Fixed
- Data Package editor. Some files were missing from the tabulator package.
- Bug when exiting the app when there is no project open in close_view_forms() when
exiting the application without a project open
### Changed
- settings.conf file is now in /conf directory
## [0.1.71] - 2018-11-19
### Added
- Added PyMySQL package, which was missing from the previous release
- Improved Graph View for the View project item (work in progress)
### Changed
- Some main window components have been renamed
- Main view is now called *Design View*
- Julia REPL is now called *Julia Console*
- Subprocess Output is now called *Process Log*
- Project item info window is now called *Properties*
## [0.1.7] - 2018-11-01
### Added
- New option to refresh the data store tree view and get latest changes from the database.
- Several performance enhancements in tree view form (accessing internal data more efficiently,
optimizing queries to the database.)
- Now the data store tree view offers to commit pending changes at exit.
- Better support for batch operations in data store tree view.
- data store tree view can be fully operated by using the keyboard.
- New options to edit object tree items in the data store tree view, including changing the objects involved
in a relationship.
- The dialogs to add/edit tree view items are not closed in case of an error, so the user can adjust their choices
and try again.
- Stop button now terminates tool execution.
- New context menu options to fully expand and collapse object tree items in the data store tree view.
- The autofilter in the data store tree view now also filters work in progress rows.
- In the Data store item controls, the path to the SQLite file can be specified by dropping a file.
- Parameter and parameter value tables in the data store tree view now have an empty row at the end,
which can be used to enter data more easily.
- JSON data can be visualized and edited more easily in the data store tree view.
- Tools can now execute (Windows) batch files and other executables (.exe). Linux support pending.
- About Qt dialog added to Help menu
### Fixed
- Clicking on the open treeview button while the data store tree view is open now raises it, rather than opening a
second one.
- Work folder is not created for Tools if the Tool template requirements are not met.
- Result folder is not created if the Tool template fails to start.
- The embedded Julia REPL now uses the Julia that is given in application Settings (F1).
Previously, this used the default Julia of your OS.
### Removed
- Connections tab has been removed (actually, it is just hidden and can be restored with a keyboard shortcut)
- Refresh Tools button on Templates tab has been removed as it was not needed anymore
- Set Debug message level in Settings has been removed
## [0.1.5] - 2018-09-28
### Added
- Advanced copy/pasting and multiple selection support for the data store tree view.
- Import data from Excel files into the data store tree view.
- Export Spine database from the data store tree view into an Excel file.
- Save at exit prompt.
- Import data from datapackage into the data store tree view.
- Restore Dock Widgets in the main window.
- Parameter tables can be filtered by clicking on their headings in the data store tree view.
- Parameter and parameter values are added and edited directly in the data store tree view,
without need for an additional dialog.
- On-the-fly creation of necessary relationships when entering parameters in data store tree view.
- View item feature for visualizing networks from a Spine database. A view item can visualize databases
from all data store items connected to it.
- Packages numpy, scipy, and matplotlib are now mandatory requirements.
- Drag files between data connections. File items can be dragged from the references and data lists.
Data connection items can be selected by hovering them while dragging a file. Dropping files onto a Data Connection
item copies them to its data directory.
- datapackage.json files in data connections are now opened with the Spine datapackage form. This is a dedicated
interface to prepare the datapackage for importing in the data store tree view.
- The data store tree view does not lock the database when there are uncommitted changes anymore.
### Changed
- Changed DBAPI package mysqlclient (GPL license, not good) to pymysql (MIT license, good)
- spinedatabase_api is not included in Spine Toolbox repository anymore. It is a required
package from now on.
- Data Store item can have only one database, not many. When opening a project created with a
previous version, the first database in the list of saved references will be loaded for each Data Store.
- In the data store tree view, the object tree presents all relationship classes at the same level,
regardless of how many object classes are involved. The same applies for relationships and objects.
- In the data store tree view, the relationship parameter value view now has different columns for each object
in the relationship.
## [0.1] - 2018-08-20
### Added
- Basic functionality
Getting Started
Welcome to the Spine Toolbox’s getting started guide. In this guide you will learn two ways of running a “Hello, World!” program on Spine Toolbox. If you need help on how to run SpineOpt.jl using Spine Toolbox, see chapter How to Set up SpineOpt.jl. For small example projects utilizing SpineOpt.jl, see SpineOpt tutorials.
This chapter introduces the following topics:
Spine Toolbox Interface
The central element in Spine Toolbox’s interface is the Design View, which allows you to visualize and manipulate your project workflow. In addition to the Design View there are a few dock widgets that provide additional functionality:
Properties provides an interface to interact with the currently selected project item.
Event Log shows relevant messages about user performed actions and the status of executions.
Console allows Spine Toolbox to execute Tools written in Python, Julia or GAMS and provides an interface to interact with the aforementioned programming languages. Also shows a list of parallel executions available in the project.
In addition to the Design View and the dock widgets, the main window contains a Toolbar split into two sections. The Items section contains the project items that you can drag-and-drop onto the Design View while the Execute section has buttons related to executing the project.
Tip
You can drag-and-drop the dock widgets around the screen, customizing the interface at your will. Also, you can select which ones are shown/hidden using either the View -> Dock Widgets menu, or the main menu Toolbar’s context menu. Spine Toolbox remembers your configuration between sessions. Selecting Restore Dock Widgets from the View -> Dock Widgets menu restores the widgets back to their default location.
Tip
Most elements in the Spine Toolbox’s interface are equipped with tool tips. Leave your mouse cursor over an element (button, checkbox, list, etc.) for a moment to make the tool tip appear.
Creating a Project
To create a new project, please do one of the following:
From the application main menu, select File -> New project…
Press Ctrl+N.
The Select project directory (New project…) dialog will show up. Browse to a folder of your choice and create a new directory called ‘hello world’ there. Then select the ‘hello world’ directory and click Select Folder. Spine Toolbox will populate the selected directory with some files and directories it needs to store the project’s data.
Congratulations, you have created your first Spine Toolbox project.
Creating a Tool Specification
Note
Spine Toolbox is designed to run and connect multiple tools, which are specified using Tool specifications. You may think of a Tool specification as a self-contained program specification including a list of source files, required and optional input files, and expected output files. Once a Tool specification is added to a project, it can then be associated to a Tool item for its execution as part of the project workflow.
Note
Just like the main window, the Tool specification editor consists of dock widgets that you can reorganize however you like.
In the Toolbar, click on the icon next to the Tool icon
, to reveal the Tool
specification list. Since there are none in the project yet, click on the
button to open the
Tool specification editor. Follow the instructions below to create a minimal Tool specification:
Type ‘hello_world’ into the Name: field.
Select ‘Python’ from the Tool type dropdown list,
Click on the
button next to the Main program file text in the Program files dock widget. A Create new main program file file browser dialog opens. Name the file
hello_world.py
and save it e.g. directly to the ‘hello world’ project directory or to a folder of your choice.
We have just created a hello_world.py
Python script file, but at the moment the file is empty. Spine Toolbox provides
an mini IDE where you can view and edit the contents of Tool specification files. Let’s try it out.
Select hello_world.py
below the Main Program File. Click on the (black) editor dock widget with the title
‘hello_world.py’.
Type in the following:
print("Hello, world!")
Now, whenever hello_world.py
is executed, the sentence ‘Hello, World!’ will be printed to the standard output.
The Tool specification editor should be looking similar to this now:

Note that the program file (hello_world.py
) and the Tool specification (hello world) now have unsaved changes.
This is indicated by the star (*) character next to hello_world.py* and the Tool specification name in the tab bar
(hello_world*).
Save changes to both by either pressing Ctrl+S or by mouse clicking on Save in the hamburger menu in the upper right hand corner.
Close Tool specification editor by pressing Alt+F4 or by clicking on ‘X’ in the top right hand corner of the window.
Your main window should look similar to this now.

Tool specifications are saved by default in JSON format into a dedicated directory under the project directory. If you
want, you can open the newly created hello_world.json
file by clicking on the file path in the Event log message.
The file will open in an external editor provided that you have selected a default program for files with the .json
extension (e.g in Windows 10 you can do this in Windows Settings -> Apps -> Default apps). In general, you don’t need
to worry about the contents of the JSON Tool specification files. Editing these is done under the hood by the app.
If you want to save hello_world.json
somewhere else, you can do this by clicking the white [change] link
after the path in the Event Log.
Tip
Saving the Tool specification into a file allows you to add and use the same Tool specification in
another project. To do this, you just need to click the From file… button
() in the Toolbar and select the Tool specification file (.json) from your system.
Congratulations, you have just created your first Tool specification.
Adding a Tool Item to the Project
Note
The Tool project item is used to run Tool specifications.
Let’s add a Tool item to our project, so that we’re able to run the Tool specification we created above.
To add a Tool item drag-and-drop the Tool icon from the Toolbar onto the Design View.
The Add Tool form will popup. Change name of the Tool to ‘say hello world’, and select ‘hello_world’ from the dropdown list just below, and click Ok. Now you should see the newly added Tool item as an icon in the Design View. It should look similar to this:

Another way to do the same thing is to drag the with the ‘hello world’ text from the Toolbar onto
the Design View. Similarly, the Add Tool form will popup but the ‘hello world’ tool specification is already
selected from the dropdown list.
Note
The Tool specification is now saved to disk but the project itself is not. Remember to save the project every once in a while when you are working. You can do this by selecting File -> Save project from the main window or by pressing Ctrl+S when the main window is active. If the project is in such a state that it has unsaved changes, an asterisk * is visible after the project name and path in the upper left corner of the main window.
Executing a Tool
Select the ‘say hello world’ Tool on Design View, and you will see its Properties in the dedicated dock widget. It looks similar to this:

Press execute project button on the Toolbar. This will execute the ‘say hello world’ Tool project item
which now has the ‘hello world’ Tool specification associated to it. In actuality, this will run the main program
file
hello_world.py
in a dedicated process.
Once the execution is finished, you can see the details about the item execution as well as the whole execution in Event Log. The Console contains the output of the executed program file.

Note
For more information about setting up Consoles in Spine Toolbox, please see Setting up Consoles and External Tools for help.
Congratulations, you just executed your first Spine Toolbox project.
Editing a Tool Specification
To make things more interesting, we will now specify an input file for our ‘hello_world’ Tool specification.
Note
Input files specified in the Tool specification can be used by the program source files, to obtain input data for the Tool’s execution. When executed, a Tool item looks for input files in Data Connection, Data Store, Exporter, and Data Transformer project items connected to its input.
Open the Tool specification editor for the ‘hello world’ Tool spec. You can do this for example, by double-clicking
the ‘say hello world’ Tool in Design View, or from the Tool Properties by clicking the
Tool specification options button () next to the specification and selecting Edit specification.
In Input & Output files dock widget, click the button next to the Input Files text. A dialog appears,
that lets you enter a name for an input file. Type ‘input.txt’ and press Enter.
So far so good. Now let’s use this input file in our program. Still in the Tool specification editor, replace the
text in the main program file (hello_world.py
), with the following:
with open("input.txt") as input_file:
print(input_file.read())
Now, whenever hello_world.py
is executed, it will look for a file called input.txt
in the current directory, and print its content to the standard output.
The editor should now look like this:

Save the specification and close the editor by pressing Ctrl+S and then Alt+F4.
Note
See Tool Specification Editor for more information on editing Tool specifications.
Back in the main window, note the exclamation mark on the Tool icon in Design View, if you hover the mouse over
this mark, you will see a tooltip telling you in detail what is wrong. If you want you can try and execute the
Tool anyway by pressing in the Toolbar. The execution will fail because the file
input.txt
is not
made available for the Tool:

Adding a Data Connection Item to the Project
Note
The Data Connection item is used to hold generic data files, so that other items, notably Importer and Tool, can make use of that data.
Let’s add a Data Connection item to our project, so that we’re able to pass the file input.txt
to
‘say hello world’. To add a Data Connection item, drag-and-drop the Data Connection icon () from the Toolbar
onto the Design View.
The Add Data Connection form will show up. Type ‘pass input txt’ in the name field and click Ok. The newly added Data Connection item is now in the Design View.
Adding Data Files to a Data Connection
Select the ‘pass input txt’ Data Connection item to view its properties in the Properties dock widget. It should look similar to this:

Right click anywhere within the Data box and select New file… from the context menu. When prompted to enter a name for the new file, type ‘input.txt’ and click Ok.
There’s now a new file in the Data list:

Double click this file to open it in your default text editor. Then enter the following into the file’s content:
Hello again, World!
Save the file.
Connecting Project Items
As mentioned above, a Tool item looks for input files in Data Connections or other items connected to its input. Thus you now need to create a connection from ‘pass input txt’ to ‘say hello world’. To do this, click on one of the connector slots at the edges of ‘pass input txt’ in the Design view, and then on a similar slot in ‘say hello world’. This will create an arrow pointing from one to another, as seen below:

Press once again. The project will be executed successfully this time:

That’s all for now. I hope you’ve enjoyed following this guide as much as I enjoyed writing it. See you next time.
Where to next: If you need help on how to set up and run SpineOpt.jl using Spine Toolbox, see chapter How to Set up SpineOpt.jl. After setting up SpineOpt, there are three tutorials over on SpineOpt.jl’s documentation that will help you get started on using SpineOpt in Spine Toolbox: Simple system, Two hydro plants, and Case study A5.
How to Set up SpineOpt.jl
Install Julia (v1.6 or later) from https://julialang.org/downloads/ if you don’t have one. See latest SpineOpt.jl Julia compatibility information here.
Start Spine Toolbox
Create a new project (File -> New project…)
Select File -> Settings from the main menu and open the Tools page.
Set a path to a Julia executable to the appropriate line edit (e.g. C:/Julia-1.9.0/bin/julia.exe). Your selections should look similar to this now.
[Optional] If you want to install and run SpineOpt in a specific Julia project environment (the place for Project.toml and Manifest.toml), you can set the path to the environment folder to the line edit just below the Julia executable (the one that says Using Julia default project).
Next, you need to install SpineOpt.jl package for the Julia you just selected for Spine Toolbox. You can do this manually by following the instructions or you can install SpineOpt.jl by clicking the Add/Update SpineOpt button. After clicking the button, an install/upgrade SpineOpt wizard appears. Click Next twice and finally Install SpineOpt. Wait until the process has finished and you are greeted with this screen.
Close the wizard.
Click Ok to close the Settings window
Back in the main window, select Plugins -> Install plugin… from the menu
Select SpineOpt and click Ok. After a short while, a red SpineOpt Plugin Toolbar will appear in the main window.
Spine Toolbox and Julia are now correctly set up for running SpineOpt.jl. Next step is to Create a project workflow using SpineOpt.jl (takes you to SpineOpt documentation). See also Tutorials in SpineOpt documentation for more advanced use cases. For more information on how to select a specific Python or Julia version, see Setting up Consoles and External Tools.
Note
The SpineOpt Plugin Toolbar contains an exporter specification as well as three predefined Tools that make use of SpineOpt.jl. The SpineOpt Plugin is not a requirement to run SpineOpt.jl, they are provided just for convenience and as examples to get you started quickly.
Setting up Consoles and External Tools
This section describes the options for executing different Python, Julia, Gams, and Executable Tools and how to set them up. To get started with SpineOpt.jl, see How to Set up SpineOpt.jl. See also Executing Projects.
Python and Julia Tools can be executed either in an embedded Basic Console or in a Jupyter Console. GAMS Tools are executed in a sub-process. Executable Tools (external programs) are executed in a shell or by running the executable file directly. You can also make a Tool that executes a shell command by creating an Executable Tool Spec in Tool Specification Editor, entering the shell command to the Command line edit and then selecting the Shell for this Tool.
Basic Consoles
Basic Console appears to the Console dock widget in the main window when you execute () a project
containing either a Python or a Julia Tool with Basic Console selected.
Python
Executing a Python Tool in the Basic Console requires no set up. Simply create a Python Tool Spec in
Tool Specification Editor and select the Basic Console radio button. The default Python interpreter used
in launching the Console is the same Python that was used in launching Spine Toolbox. You can also select another
Python by changing the Python interpreter line edit. Remember to save the new Tool Spec when closing the Tool
Spec. Editor. Then drag the Python Tool Spec into the Design View, and press to execute it.
Note
The Python settings on the Tools page in File -> Settings are the default settings for Python Tool Specs. You can select a different Python executable for each Python Tool Spec separately using the Tool Specification Editor.
Julia
To execute Julia Tools in the Basic Console, first install Julia (v1.6 or later recommended) from here and add <julia install path>/bin to your PATH environment variable (if not done automatically by the installer). Then go to the Tools page in File -> Settings and make sure that the Basic Console radio button is selected in the Julia group. If Julia is in your PATH, the Julia executable line edit should show the path as (grey) placeholder text. If you want to use another Julia on your system, you can change the path in the line edit. You can also set a Julia Project/Environment below the Julia executable line edit.
Note
The Julia settings on the Tools page in File -> Settings are the default settings for Julia Tool Specs. You can select a different Julia executable & project for each Julia Tool Spec separately using the Tool Specification Editor.
Jupyter Consoles
Jupyter Console appears to the Console dock widget in the main window when you execute () a project
containing either a Python or a Julia Tool with the Jupyter Console selected. The Jupyter Console
requires a Jupyter kernel to be installed on your system. Kernels are programming language specific processes
that run independently and interact with the Jupyter Applications and their user interfaces.
Python
Select Jupyter Console radio button in File -> Settings. You also need to select the Python kernel you wish to use from the Select Python kernel… combo box. If this list is empty, you need to install the kernel specs on your system. You can either do this manually or click the Make Python Kernel button. Clicking the button opens a Python Kernel Specification Creator window, that first installs the ipykernel package (if missing) for the Python that is currently selected in the Python interpreter line edit (the kernel specs will be created for C:/Python310/python.exe in the picture below). You can make kernel specs for other Pythons and virtual environments (venv) by changing the Python interpreter line edit path to point to another Python. Please see specific instructions for creating kernel specs for Conda environments below.

Once the ipykernel package is installed, the wizard runs the ipykernel install command, which creates the kernel specs directory on your system. Once the process finishes, click Close, and the newly created kernel spec (python310 in this case) should be selected automatically. For convenience, there is a context-menu (mouse right-click menu) in the Select Python Kernel… combo box that opens the the kernel spec directory in your file browser. Click Ok to close the Settings widget and to save your selections.

If something went wrong, or if you want to remake the kernel specs, you can remove the kernel spec directory from your system, try the Make Python Kernel button again, or install the kernel specs manually.
If you want to install the Python kernel specs manually, these are the commands that you need to run.
To install ipykernel and it’s dependencies, run:
python -m pip install ipykernel
And to install the kernel specs run:
python -m ipykernel install --user --name python310 --display-name python310_spinetoolbox
Make sure to use the --user
argument in order to make the kernel specs discoverable by Spine Toolbox.
Important
If you want to have access to spinedb_api, you need to install it manually for the Python you select here.
Note
Clicking Make Python Kernel button when the kernel specs have already been installed, does NOT open the Python Kernel Specification Creator, but simply selects the Python kernel automatically.
Note
Executing Python Tools using the Jupyter Console supports Python versions from 2.7 all the way to latest one. This means, that if you still have some old Python 2.7 scripts lying around, you can incorporate those into a Spine Toolbox project workflow and execute them without modifications.
Julia
To use the Jupyter Console with Julia Tools, go to the Tools page in File -> Settings and select the Jupyter Console radio button like in the picture below.

Like with Python, you need to select an existing Julia kernel for the Julia Jupyter Console, or create one either manually, or by clicking the Make Julia Kernel button.

Clicking the button opens Julia Kernel Specification Creator window, that first installs the IJulia package (if missing) for the Julia and Julia project that are currently selected in the Julia executable and Julia Project line edits (the kernel specs will be created for the default project of C:/Julia-1.9.0/bin/julia.exe in the picture above).
If something went wrong, or if you want to remake the kernel specs, you can remove the kernel spec directory from your system, try the Make Julia Kernel button again, or install the kernel specs manually.
If you want to install the Julia kernel specs manually, these are the commands that you need to run.
To install IJulia and it’s dependencies, open Julia REPL with the project you want and run:
using Pkg
Pkg.add("IJulia")
Rebuild IJulia:
Pkg.build("IJulia")
And to install the kernel specs run:
using IJulia
installkernel("julia", --project="my_project")
Note
Clicking Make Julia Kernel button when the kernel specs have already been installed, does NOT open the Julia Kernel Specification Creator, but simply selects a Julia kernel that matches the selected Julia executable and Julia Project. If a kernel spec matching the Julia executable is found but the Julia project is different, a warning window appears, saying that Julia kernel spec may be overwritten if you continue.
Conda
You also have the option of running Python Tools in a Conda environment. All you need to do is the following.
Open Anaconda Prompt and make a new Conda environment:
conda create -n test python=3.10
Activate the environment:
conda activate test
Install ipykernel:
pip install ipykernel
Back in Spine Toolbox, add path to Conda executable on the Tools page in File -> Settings.
That’s it! Now, in Spine Toolbox main window, open the Consoles -> Start Jupyter Console menu, wait a second, and the new kernel should appear in the list. In this case, the new kernel name is conda-env-.conda-test-py. This autogenerated name will most likely change to something more readable in the future. You can use Conda Python kernels just like regular Python kernels, i.e. select one of them as the default kernel in the File -> Settings widget or select them for individual Python Tool Specs in Tool Specification Editor directly.
Detached Consoles
You can open ‘detached’ Jupyter Consoles from the main window menu Consoles -> Start Jupyter Console. The menu is populated dynamically with every Jupyter kernel that Spine Toolbox is able to find on your system. ‘Detached’ here means that the Consoles are not bound to any Tool. These Consoles are mostly useful e.g. for checking that the kernel has access to the correct packages, debugging, small coding, testing, etc. These may be especially useful for checking that everything works before running a full workflow that may take hours to finish.
Officially, Spine Toolbox only supports Python and Julia Jupyter kernels but it’s possible that other kernels can be accessed in a Detached Console as well. For example, if you install a javascript kernel on your system, you can open a Detached Console for it, but this does not mean that Spine Toolbox projects should support Javascript. However, if there’s interest and legitimate use cases for other kernels, we may build support for them in future releases.

If interested, you can read more on Jupyter kernels . There you can also find a list of available kernels.
GAMS
Executing Gams Tools or needing to use the GDX file format requires an installation of Gams on your system. You can download Gams from https://www.gams.com/download/.
Note
You do not need to own a Gams license as the demo version works just as well.
Important
The bitness (32 or 64bit) of Gams has to match the bitness of the Python interpreter.
The default Gams is the Gams defined under gams.location
in Windows registry or in your PATH environment
variable. You can see the one that is currently in use from the Tools page in File -> Settings. The
placeholder text shows the default Gams if found. You can also override the default Gams by setting some other
gams executable path to the line edit.
Executable
Executable Tool Spec types can be used to execute virtually any program as part of a Spine Toolbox workflow. They also provide the possibility to run Shell commands as part the workflow. To run an executable with a shell you need to select a shell out of the three available options that is appropriate for your operating system. Then you can write a command that runs the executable with the arguments that it needs into the Command line edit just like you would on a normal shell.
To run an executable file without a shell you can either select the executable file as the main program file of the Tool and write the possible arguments into Command line arguments or select no shell and write the filepath of the executable file followed by it’s arguments into the Command textbox. Either way the file is executed independent of a shell and with the provided arguments.
To run a Shell command, just type the command into the command line edit and select the appropriate Shell from the list. Picture below depicts an Executable Tool Spec that runs dir in in cmd.exe.

Main Window
This section describes the different components in the application main window.
The first time you start the application you will see the main window like this.

The application main window contains four dock widgets (Design View, Properties, Event Log, Console), a Toolbar, and a menu bar with File, Edit, View, Plugins, Consoles, Server and Help menus. The Properties dock widget shows the properties of the selected project item. Event Log shows messages based on user actions and item executions. It shows messages from processes that are spawned by the application, i.e. it shows the stdout and stderr streams of executable programs. In addition, it displays messages related to item’s execution.
Console provides Julia and Python consoles that can be interacted with. What kind of console is shown depends on the Tool type of the specific Tool. Only an item that is currently executing or has already executed shows something in this dock widget. To view an item’s console, the item must be selected. When executing Python/Julia tools, the Tool’s Python/Julia code will be included into the console and executed there.
Tip
You can configure the Julia and Python versions you want to use in File -> Settings.
The menu bar in the top of the application contains File, Edit, View, Plugins, Consoles, Server and Help menus. In the File menu you can create a new project, open an existing project, save the project or open the application Settings among other things. Spine Toolbox is project based, which means that you need to create a new project or open an existing one before you can do anything. You can create a new project by selecting File -> New project… from the menu bar. In the Edit menu you can for example copy, paste and duplicate items as well as undo and redo actions. In the Plugins menu you can install and manage plugins. Consoles menu provides a way to start detached consoles. In the Server menu you can retrieve projects from a server. Help contains a link to this documentation as well as various tidbits about Spine Toolbox.
The Items section of the Toolbar contains the available
project item types.
The Execute section contains icons that control the execution of the items in the Design view. The
button executes all workflows in the project in parallel. The
button
executes the selected project items only. The
button terminates the execution (if running).
You can add a new project item to your project by pointing your mouse cursor on any of the draggable items in the Toolbar, then click-and-drag the item on to the Design view. After this you will be presented a dialog, which asks you to fill in basic information about the new project item (name, description, etc.).
The main window is very customizable so you can e.g. close the dock widgets that you do not need, rearrange the order of the dock widgets by dragging them around and/or resize the views to fit your needs and display size or resolution. You can find more ways to customize the visual elements of Spine Toolbox in the settings.
Note
If you want to restore all dock widgets to their default place use the menu item View -> Dock Widgets -> Restore Dock Widgets. This will show all hidden dock widgets and restore them to the main window.
Project Items
Project items in the Design view and the connections between them make up the graph (Directed Acyclic
Graph, DAG) that is executed when the or
buttons are pressed.
See Executing Projects for more information on how a DAG is processed by Spine Toolbox. Those interested in looking under the hood can check the Project Item Development section.
Project Item Properties
Each project item has its own set of properties. You can view and edit them by selecting a project
item in the Design View. The properties are displayed in the Properties dock widget on the main
window. Project item properties are saved into the project save file (project.json
), which can be
found in <proj_dir>/.spinetoolbox/
directory, where <proj_dir>
is your current project
directory.
In addition, each project item has its own directory in the <proj_dir>/.spinetoolbox/items/
directory. You can quickly open the project item directory in a file explorer by clicking the
button located in the upper right corner of each Properties form.
Project Item Descriptions
The following items are currently available:
Data Connection
A Data connection item provides access to data files. The item has two categories of files: references connect to files anywhere on the file system or on remote (non-Spine) databases while data files reside in the item’s own data directory.
Data Store
A Data store item represents a connection to a (Spine) database. Currently, the item supports sqlite and mysql dialects. The database can be accessed and modified in Spine db editor available by double-clicking a Data store on the Design view, from the item’s properties, or from a right-click context menu.
Data Transformer
Data transformers set up database manipulators for successor items in a DAG. They do not transform data themselves; rather, Spine Database API does the transformations configured by Data transformers when the database is accessed. Currently supported transformations include entity class and parameter renaming as well as value transformations.
Exporter
Exporter outputs database data into tabulated file formats that can be consumed by Tool or be used by external software for analysis. See Importing and Exporting Data for more information.
Importer
This item provides the user a chance to define a mapping from tabulated data such as comma separated values or Excel to the Spine data model. See Importing and Exporting Data for more information.
Merger
A Merger item transfers data between Data Stores. When connected to a single source database, it simply copies data from the source to all output Data Stores. Data from more than one source gets merged to outputs.
Tool
Tool is the heart of a DAG. It is usually the actual model to be executed in Spine Toolbox but can be an arbitrary script, executable or system command as well. A Tool is specified by its specification.
Links
Links are the things that connect project items to each other. If Tool is the heart of a DAG, then links are the veins that connect the heart to other vital organs.
Creating a new link between items is simple. First you need to select any of the connector slots on the item where you want the link to originate form. Then select any connector slot on the item that you want to connect to. There are no limitations for how many links one connector slot can have. Like items, links can also have properties, depending on the types of items that they are connecting. When a link is selected, these properties can be modified in the Properties dock widget.
The small bubble icons in a link represent the state of the link’s properties. When an icon is blue, the corresponding selection is active in the Properties dock widget.
Data Store as Source
Below is an example of what the Properties dock widget can look like when a link originating from a Data Store is selected:

DB resource filters is divided into Scenario and Tool filters. With the scenario filters, you can select which scenarios to include in the execution. The Tool filter lets you choose which tools specified in the database are active. The Check new filters automatically option allows you to choose whether new Scenario and Tool filters added to the database should be automatically selected in this specific link. Filter validation allows you to force that at least one Scenario and/or Tool filter is selected at all times in that specific link.
Data Store as Destination
In the image below, the selected link ends in a Data Store. Because of this, the available selections in Properties differ from the previous image.

Now the link has no filters, but the write index and other various database related options become available.
Write index controls which items write to the database first. Smaller indices take precedence over larger ones while items with the same index write in an undefined order.
Purge before writing option purges the target Data Store before write operations. Click on Settings… to set up which items to purge.
Warning
This purge has no undo available.
Using Memory Databases
Use memory DB for Tool execution allows using a temporary in-memory database while executing a Tool which may speed up execution if the Tool accesses the database a lot.
Packing CSV files into datapackage
When the source item may provide output files, the Pack CSV files (as datapackage.json) option becomes enabled. This option may be handy when an item provides a lot of CSV files that e.g. need to imported into a Data Store. Checking this options does two things:
A
datapackage.json
file is created in the common parent directory of all CSV files the source item provides. This file defines a datapackage that consists of the CSV files.The destination item receives only the
datapackage.json
file instead of any CSV files from the source item.
See the datapackage specification for more information on datapackages.
Tool Specification Editor
This section describes how to make a new Tool specification and how to edit existing Tool specifications.
General
To execute a Julia, Python, GAMS, or an executable script in Spine Toolbox, you must first create a Tool specification for your project. You can open the Tool specification editor in several ways. One way is to press the arrow next to the Tool icon in the toolbar to expand the Tool specifications, and then press the New… button.

When you press New… the following form pops up;

Start by giving the Tool specification a name. Then select the type of the Tool. You have four options (Julia,
Python, GAMS or Executable). You can give the Tool specification a description,
describing what the Tool specification does. Main program file is the main file of your tool, i.e. a
script that can be passed to Julia, Python, GAMS, or the system shell.
You can create a blank file by pressing the button,
or you can browse to find an existing main program file by pressing the
button.
Command line arguments can be appended to the actual command that
Spine Toolbox executes in the background. For example, you may have a Windows batch file called do_things.bat
,
which accepts command line arguments a and b.
Writing a b on the command line arguments field in the tool specification editor is the equivalent
of running the batch file in command prompt with the command do_things.bat a b
.
Tip
Another way to pass arguments to a Tool is to write them into the Tool arguments drop-down list in the Properties dock widget. There it is possible to also rearrange existing arguments or to select available resources that are provided by other project items as arguments.
Unlike the arguments set in Tool Specification Editor, the arguments in Properties are Tool specific.
Additional source files is a list of files that the main program requires in order to run. You can add
individual files the same way as with the main program file or whole directories at once by pressing the
button.
Input files is a list of input data files that the program requires in order to execute. You can also add directories and subdirectories. Wildcards are not supported (see Optional input files).
Examples:
data.csv -> File is copied to the same work directory as the main program
input/data.csv -> Creates directory input/ to the work directory and copies file data.csv there
output/ -> Creates an empty directory output/ into the work directory
Optional input files are files that may be utilized by your program if they are found. Unix-style wildcards
?
and *
are supported.
Examples:
data.csv -> If found, file is copied to the same work directory as the main program
*.csv -> All found .csv files are copied to the same work directory as the main program
input/data_?.dat -> All found files matching the pattern data_?.dat are copied into input/ directory in the work directory.
Output files are files that will be archived into a timestamped result directory inside Tool’s data directory
after the Tool specification has finished execution. Unix-style wildcards ?
and *
are supported.
Examples:
results.csv -> File is copied from work directory into results directory
*.csv -> All .csv files from work directory are copied into results directory
output/*.gdx -> All GDX files from the work directory’s output/ subdirectory will be copied into output/ subdirectory in the results directory.
When you are happy with your Tool specification, press Ctrl+S to save it. You will see a message in the Event log (back in the main Spine Toolbox window), specifying the path of the saved specification file. The Tool specification file is a text file in JSON format and has an extension .json You can change the location by pressing [change]. Also, you need to save your project for the specification to stick.
Tip
Only name, type, and either main program file or command fields are required to make a Tool specification. The other fields are optional.
Here is a minimal Tool specification for a Julia script script.jl

Note
Under the hood, the contents of the Tool specification are saved to a Tool specification file in JSON format. Users do not need to worry about the contents of these files since reading and writing them is managed by the app. For the interested, here are the contents of the Tool specification file that we just created.:
{
"name": "Example Tool specification",
"tooltype": "julia",
"includes": [
"script.jl"
],
"description": "",
"inputfiles": [],
"inputfiles_opt": [],
"outputfiles": [],
"cmdline_args": [],
"includes_main_path": "../../.."
}
After you have saved the specification, the new Tool specification has been added to the project.

To edit this Tool specification, just right-click on the Tool specification name and select Edit specification from the context-menu.
You are now ready to execute the Tool specification in Spine Toolbox. You just need to select a Tool item in the
Design view, set the specification Example Tool specification for it, and click or
button.
Input & Output Files in Practice
The file names can be either hard coded or not. For example, you could have a script that requires (hard coded in the script) a file input.dat and optionally works with a bunch of files that are expected to have the .csv extension. In that case you would define
input.dat as an Input file
*.csv as Optional input files
The Output files work similarly; you can hard code the entire file name or use wildcards for Optional output files.
When specifying the Input and Output files in the Specification editor, Toolbox will copy the files to the Tool’s work directory when the Tool is executed, so they are available for the script in a known location. Note, that you can specify subdirectories for the files as well. These will be relative to the work directory.
These options expect some level of hard-coding: file names, or at least file extensions as well as relative locations to the work directory need to be known when writing the Tool Spec script.
There is another, more general way to provide Input files to the script that does not require any kind of hard coding: command line arguments. You can set them up in Tool’s Properties tab. For example, in the project below, a Data connection provides Input files for the workflow. The files are visible in the Available resources list in Tool’s Properties and they have been dragged and dropped into the the Tool arguments list.

Now, the Python script can access the files using something like:
import sys
file_path1 = sys.argv[1]
file_path2 = sys.argv[2]
Of course, more serious scripts would use the argparse module.
Executing Projects
This section describes how executing a project works and what resources are passed between project
items at execution time. The buttons used to control executions are located in the Toolbar’s Execute -section.
Execution happens by either pressing the Execute Project button () to execute the
whole project, or by pressing the Execute Selected button (
) to only execute selected items.
Next to these buttons is the Stop button (
), which can be used to stop an ongoing execution.
A project consists of project items and connections (yellow arrows) that are visualized on the Design View.
You use the project items and the connections to build a Directed Acyclic Graph (DAG), with the project
items as nodes and the connections as edges. The DAG is traversed using the breadth-first-search algorithm.
Rules of DAGs:
A single project item with no connections is a DAG.
All project items that are connected, are considered as a single DAG (no matter, which direction the arrows go). If there is a path between two items, they are considered as belonging to the same DAG.
Loops are not allowed (this is what acyclic means).
You can connect the nodes in the Design View how ever you want but you cannot execute the resulting DAGs if they break the rules above. Here is an example project with three DAGs.

DAG 1: items: a, b, c, d. connections: a-b, a-c, b-d, c-d
DAG 2: items: e, f. connections: e-f
DAG 3: items: g. connections: None
The numbers on the upper left corners of the icons show the item’s execution ranks which roughly tell the order of execution within a DAG. Execution order of DAG 1 is a->b->c->d or a->c->b->d because b and c are siblings which is also indicated by their equal execution rank. DAG 2 execution order is e->f and DAG 3 is just g. All three DAGs are executed in a row though which DAG gets executed first is undefined. Therefore all DAGs have their execution ranks starting from 1.
We use the words predecessor and successor to refer to project items that are upstream or downstream from a project item. Direct predecessor is a project item that is the immediate predecessor while Direct Successor is a project item that is the immediate successor. For example, in the DAG 1 presented before, the successors of a are project items b, c and d. The direct successor of b is d. The predecessor of b is a, which is also its direct predecessor.
After you press the button, you can follow the progress
and the current executed item in the Event Log.
Design view also animates the execution.
Items in a DAG that breaks the rules above are marked by X as their rank. Such DAGs are skipped during execution. The image below shows such a DAG where the items form a loop.

You can also execute only the selected parts of a project by multi-selecting the items you want to
execute and pressing the button in the tool bar. For example, to execute only items
b, d and f, select the items in Design View
button.
Tip
You can select multiple project items by holding the Ctrl key down and clicking on desired items or by drawing a rectangle on the Design view.
Example DAG
When you have created at least one Tool specification, you can execute a Tool as part of the DAG. The Tool specification defines the process that is executed by the Tool project item. As an example, below we have two project items; Data Files Data Connection and Julia model Tool connected to each other.

In ths example, Data Files has a single file reference data.csv
.
Data Connections make their files visible to direct successors
and thus the connection between Data Files and Julia model provides data.csv
to the latter.
Selecting the Julia model shows its properties in the Properties dock widget.

In the top of the Tool Properties, there is Specification drop-down menu.
From this drop-down menu, you can select the Tool specification for this particular Tool item.
The Julia Model Specification tool specification has been selected for Julia model.
Below the drop-down menu, you can choose a precompiled sysimage
and edit Tool’s command line arguments.
Note that the command line argument editor already ‘sees’ the data.csv
file provided by Data Files.
The Execute in radio buttons control, whether this Tool is first copied to a work directory and executed
there, or if the execution should happen in the source directory where the main program file is located.
In Group id, an execution group identifier can be given. Below that, there is a checkbox with the choice
to kill consoles after execution.
Results… button opens the Tool’s result archive directory in system’s file browser
(all Tools have their own result directory).
When you click on the button, the execution starts from the Data Files Data Connection
as indicated by the execution rank numbers.
When executed, Data Connection items advertise their files and references
to project items that are their direct successors.
In this particular example,
data.csv
contained in Data Files
is also a required input file in Julia model Specification.
When it is the Julia model tool’s turn to be executed, it checks if it finds the data.csv
from
its direct predecessor items that have already been executed.
Once the input file has been found the Tool starts processing the main program file script.jl.
Note that if the connection would be the other way around (from Julia Model to Data Files)
execution would start from the Julia model and it would fail because it cannot find the required data.csv
.
The same thing happens if there is no connection between the two project items.
In this case the project items would be in separate DAGs.
Since the Tool specification type was set as Julia and the main program is a Julia script, Spine Toolbox starts the execution in the Julia Console (if you have selected this in the application Settings, See Settings section).
Settings
You can open Spine Toolbox settings from the main window menu File -> Settings…, or by pressing Ctrl+,. Settings are categorized into five tabs; General, Tools, Db editor, Spec. editors and Engine. In addition to application settings, each project item has user adjustable properties (See Project Items). See also Setting up Consoles and External Tools for more information on how to set up Consoles and external Tools.
General Settings

The General tab contains the general application settings.
Settings in the Main group:
Custom open project dialog If checked, the application uses a special-purpose dialog when opening a project. If left unchecked, the operating system’s default dialog is used.
Delete data when project item is removed from project Check this box to delete project item’s data when a project item is removed from project. This means that the project item directory and its contents will be deleted from your hard drive. You can find the project item directories from the <proj_dir>/.spinetoolbox/items/ directory, where <proj_dir> is your current project directory.
Open previous project at startup If checked, application opens the project at startup that was open the last time the application was shut down. If left unchecked, application starts without a project open.
Always confirm exit If checked, confirm exit prompt is shown always. If unchecked, application exits without prompt when there are no unsaved changes.
When there are unsaved changes at exit The combo box chooses what to do with unsaved changes when the application exits.
Work directory Directory where processing Tools takes place. Default place (if left empty) is shown as placeholder text. Make sure to clean up the directory every now and then.
Settings in the UI group:
Color toolbar icons Check this box to give some color to the otherwise black toolbar icons.
Color properties widgets Check this box to make the background of Project item properties more colorful.
Curved links Controls the look of the arrows on Design View.
Drag to draw links When checked, the mouse button needs to be pressed while drawing links between project items. If unchecked, single clicks at link source and destination connector slots suffices.
Prevent items from overlapping When checked, other project items can be pushed away when moving an item around the Design view. If left unchecked, items can be piled on top of each other.
Rounded items Check this box to round the corners of otherwise rectangular project items.
Show date and time in Event Log messages If checked, every Event Log message is prepended with a date and time ‘tag’.
Smooth zoom Controls the way zooming (by using the mouse wheel) behaves in Design View and in Spine DB Editor. Controls if the zoom in/out is continuous or discrete. On older computers, smooth zoom is not recommended because it may be slower.
Background Has some pattern options for the background of the Design View. Clicking on the square next to ‘Color’ lets you choose the pattern’s color.
Link flash speed This slider controls the speed of the link animation on Design View when execution is ongoing.
Tools Settings
The Tools tab contains settings for external tools.

Settings in the GAMS group:
GAMS executable Set the path to GAMS executable you want to use when executing GAMS tools. If you have GAMS in your PATH environment variable, it will be automatically used. You can also choose another GAMS by clicking the
button.
Settings in the Julia group:
Choose the settings on how Julia Tools are executed.
Basic Console When selected, Julia Tools will be executed in a custom interactive Julia REPL.
Julia executable Set the path to a Julia Executable used in launching the Basic Console. If Julia is in PATH this will be autofilled, but you can also choose another Julia executable.
Julia project Set the Julia project you want to activate in the Basic Console.
Jupyter Console Choosing this option runs Julia Tools in a custom Jupyter QtConsole embedded into Spine Toolbox.
Select Julia kernel… drop-down menu Select the kernel you want to launch in Jupyter Console.
Note
The Julia settings above are the default settings for new Julia Tool Specs. You can select a specific Julia executable & project or Julia kernel for each Tool Spec separately using the Tool Specification Editor.
Make Julia Kernel Clicking this button makes a new kernel based on the selected Julia executable, and Julia project. The progress of the operation is shown in another dialog. Installing a Julia kernel requires the IJulia package which will be installed to the selected Julia project. After IJulia has been installed, the kernel is installed. This process can take a couple of minutes to finish.
This button sets all Julia Tools execution settings in the current project to defaults. This operation is irreversible because the project will be saved afterwards.
Install Julia Installs the latest Julia on your system using the jill package.
Add/Update SpineOpt Installs the latest compatible SpineOpt to the selected Julia project. If the selected Julia project already has SpineOpt, it is upgraded if there is a new version available.
Settings in the Python group:
Choose the settings on how Python Tools are executed.
Basic Console When selected, Python Tools will be executed in a custom interactive Python REPL.
Python executable Set the path to a Python Executable used in launching the Basic Console. The default option (if the line edit is blank) is the Python executable that was used in launching Spine Toolbox.
Jupyter Console Choosing this option runs Python Tools in a custom Jupyter QtConsole embedded into Spine Toolbox.
Select Python kernel… drop-down menu Select the kernel you want to launch in Jupyter Console.
Note
The Python settings above are the default settings for new Python Tool Specs. You can select a specific Python executable or Python kernel for each Python Tool Spec separately using the Tool Specification Editor.
Make Python Kernel clicking this button makes a new kernel based on the selected Python executable. The progress of the operation is shown in another dialog. Installing a Python kernel (actually IPython kernel) requires the ipykernel package which will be installed to the selected Python executables. After ipykernel has been installed, the kernel is installed. This process can take a couple of minutes to finish.
This button sets all Python Tools execution settings in the current project to defaults. This operation is irreversible because the project will be saved afterwards.
Settings in the Conda group:
Miniconda executable If you want to run Python Tools in a Conda environment, you can set the path to your Conda executable here.
See Setting up Consoles and External Tools for more information and examples.
Db editor Settings

This tab contains settings for the Spine Database editor. The same settings can be accessed directly from the Database editor itself.
Settings in the General group:
Commit session before closing This checkbox controls what happens when you close a database editor which has uncommitted changes. When this is unchecked, all changes are discarded without notice. When this is partially checked (default), a message box warning you about uncommitted changes is shown. When this is checked, a commit message box is shown immediately without first showing the message box.
Show undo notifications Checking this will show undo notification boxes in the editor every time something undoable happens. Unchecking hides the notifications.
Settings in the Entity tree group:
Sticky selection in entity trees Controls how selecting items in Spine database editor’s Entity Tree using the left mouse button works. If checked, multiple selection is enabled and pressing Ctrl enables single selection. If unchecked, single selection is enabled and pressing Ctrl enables multiple selection.
Settings in the Entity graph group:
Auto-expand entities This checkbox controls which N-D entities are automatically shown on the Graph view. If checked, all N-D entities that are related to the selection are included automatically. If unchecked, only N-D entities that have all the elements visible in the graph are shown automatically.
Merge databases If checked, Graph view will combine all databases that are open on the same table into a single graph if they contains common entity nodes. If unchecked, a separate graph will be drawn for each database.
Snap entities to grid Makes it so that the placement of the entities can’t be arbitrary anymore but instead they can only lay on a grid.
Smooth zoom Checking this enables smooth zoom on the Graph view.
Smooth rotation Checking this enables smooth rotation on the Graph view.
Max. entity dimension count Defines a cutoff for the number of dimensions an entity can have and still be drawn.
Number of build iterations Defines the maximum numbers of iterations the layout generation algorithm can make.
Minimum distance between nodes (%) Used for setting the ideal distance between entities in the graph.
Decay rate of attraction with distance The higher this number, the lesser the attraction between distant vertices when drawing the graph.
Spec. editor Settings

The Spec. editor tab contains common settings for all specification editors.
Save specification before closing If checked, specification editors will save the specification automatically at exit. If partially checked, the editors will prompt what to do explicitly. If unchecked, no prompts will be shown and all changes will be lost at exit.
Show undo notifications Checking this will show undo notification boxes in the editor every time something undoable happens. Unchecking hides the notifications.
Engine settings

The Engine settings tab contains settings for Spine Engine.
Maximum number of concurrent processes This sets a limit on how many concurrent processes the Engine can launch. Unlimited means that there is no upper limit. With no limits to concurrent processes the execution never stalls waiting for processes to finish. It may, however, consume all system’s resources. Limit to available CPU cores sets the upper limit to the number of cores on the system. Finally, exact upper limit can be set by the User defined limit spin box.
Maximum number of open consoles This sets a limit on how many concurrent Python or Julia consoles (Basic and Jupyter) there can be running at the same time. Note, that this is a separate limit from the number of concurrent processes above. Unlimited means that there is no upper limit. With no limits to open consoles the execution never stalls waiting for console to become free. It may, however, consume all system’s resources. Limit to available CPU cores sets the upper limit to the number of cores on the system. Finally, exact upper limit can be set by the User defined limit spin box.
Remote execution This group is for executing workflows on a remote Spine engine. You can find instructions on how to set it up in Spine Engine Server
Application preferences
Spine Toolbox remembers the size, location, and placement of most of the application windows from the previous session (i.e. when closing and restarting the app).
Where are the application settings stored?
Application settings and preferences (see above) are saved to a location that depends on your
operating system. On Windows, they are stored into registry key
HKEY_CURRENT_USER\Software\SpineProject\Spine Toolbox
. It is safe to delete this key if you
want to reset Spine Toolbox to factory defaults.
Welcome to Spine Database Editor’s User Guide!
Spine database editor is a dedicated component of Spine Toolbox, that you can use to visualize and edit data in one or more Spine databases.
Getting started
This section gives a short outline on how to get started using the editor and how to navigate the ui. Information about the settings for the editor can be found in Db editor Settings.
Launching the editor
From Spine Toolbox
There are two different ways to open a single database in Spine database editor from Spine Toolbox:
Using a Data Store project item:
Create a Data Store project item.
Select the Data Store.
Enter the url of the database in Data Store Properties.
Press the Open editor… button in Data Store Properties or double-click the Data Store project item.
Without a Data Store:
From the main window select File -> New DB Editor.
Open the menu by clicking on the hamburger menu icon (☰) or by pressing ALT+F or ALT+E.
Select Open… to open an existing database, New.. to create a new one or paste a database URL into the URL bar.
From the command line
To open a single database in Spine database editor, use the spine-db-editor
application which comes with Spine Toolbox. After the virtual environment is activated
the editor can be opened with the following command:
spine-db-editor "...url of the database..."
Note that for e.g. an SQLite database, the url should start with sqlite:///
followed by the path.
Adding multiple databases to one editor
It is possible to open multiple databases in the same editor. This allows one to view and modify the data of the open databases in one editor.
To open multiple SQLite databases in the same Spine database editor by file browser:
Open a database Database editor using any of the ways explained before.
Select Add… from the editor’s hamburger menu (☰).
Browse to the directory of the SQLite file and open it.
By using the database URL:
Open a database Database editor using any of the ways explained before.
In the URL bar, after the already open database’s URL add a semicolon
;
and after that the URL of the other database to be opened in the same editor.
Knowing the UI
When you open an empty database for the first time in a Spine Database Editor, it should look something like this:

The dock widgets can be scaled by dragging them from the sides and moved around by dragging them from their darker colored headers. Like with other widgets, Toolbox remembers the customizations and the editor will open in the same configuration when it is opened the next time. The dock configurations are URL specific. the configurations for the URL can be restored back to default from the hamburger menu View->Docks…->Reset docks.
Tab bar
The uppermost UI element is the tab bar. One editor window can have multiple tabs. New tabs can be added by pressing the plus-sign (+) in the tab bar. In the newly created tab, databases can be opened once again with the instructions given above. Tabs can be deleted from the editor by pressing the cross (X) inside a tab. The tabs can be dragged from the tab bar to create new editor windows. Tabs from different windows can also be dragged into others, fusing them into the same editor window.
Filter
The filter can be used to select which items are allowed to be shown in the editor. The filter is based on scenarios. By pressing the filter image in the right end of the URL bar, the filter selector widget opens up. There the desired scenario can be selected. When a selection is made and the Update filters button is pressed, the changes will be applied to the editor. Now all entities, parameters etc. will be filtered out if they don’t belong to the scenario specified in the filter.
Tip
Note that after applying the filter, the URL gets updated with some additional information about the filters. It is therefore possible to make changes to the filtering just by modifying the URL from the URL bar.
Undo and redo
Whenever changes are made to the data in the Spine Database Editor, the changes get stored into memory. This allows undoing and redoing the operations made in the editor. Buttons for these operations can be found in the hamburger menu and the usual shortcuts Ctrl+Z and Ctrl+Y work also. However if the changes are committed, the memory for the changes gets cleared meaning that the changes before the commit can’t be undone anymore.
Views and trees
Spine Database Editor has the following main UI components:
Entity tree: they present the structure of entities in all databases in the shape of a tree.
Table views (Parameter value, Parameter definition, Entity alternative): they present entity data in the form of stacked tables.
Pivot table and Frozen table: they present data in the form of a pivot table, optionally with frozen dimensions.
Graph view: it presents the structure of classes and entities in the shape of a graph.
Parameter value list: it presents parameter value lists available in the databases.
Alternative: it presents alternatives defined in the databases in the shape of a tree.
Scenario tree: it presents scenarios defined in the databases in the shape of a tree.
Metadata: presents metadata defined in the databases.
Item metadata: shows metadata associated with the currently selected entities or parameter values.
Tip
You can customize the UI from the View section in the hamburger ☰ menu. There the Docks… menu can be used to enable and disable the different UI components listed above.
Items from the trees can be selected by clicking them with the left mouse button and the views will react to the changes. By default, multiple items can be selected at the same time across the trees by holding down Ctrl while making the selections. This behavior can be flipped from the editor settings (Ctrl+,) by toggling the Sticky selection -setting.
In the next section you will learn more about the different UI components and views available in the editor
Viewing data
This section describes the available tools to view data.
Viewing entities and entity classes
Using the Entity Tree
The Entity Tree presents the structure of entity classes and entities in all databases in the shape of a tree:

To view all entity classes from all databases, expand the root item (automatically expanded when loading the form).
To view all entities of a class, expand the corresponding entity class item.
To view all multidimensional entities where a specific entity is an member, expand that entity.
Tip
To extend the selection in Entity Tree, press and hold the Ctrl key while clicking on the items.
Right clicking items in the Entity Tree will open up a context menu. Depending on what kind of item the menu was opened from (root, entity class, entity, N-D entity) all of the options might not be available. Unavailable options are still visible but they are greyed out:

Copy as text copies the data from the selection so that it can be pasted elsewhere.
Add entity classes opens up a dialog to add new entity classes.
Add entities opens up a dialog to add new entities.
Add entity group opens up a dialog to create entity groups.
Manage elements opens up a dialog where new entities can be created or existing ones deleted for a multidimensional entity.
Manage members opens up a dialog to delete or add new members in an entity group.
Select superclass opens up a dialog to set the superclass for a given entity class
Find next occurrence goes to the next occurrence of the N-D entity in the Entity Tree and selects it. This can also be done by double-clicking the item.
Edit… opens up a dialog where the name, description, icon and active by default -setting of an entity can be changed.
Remove… removes the selection.
Duplicate entity duplicates the whole entity.
Export creates a new Spine Database in an .sqlite file with all of the relevant data to the selection.
Fully expand expands the selection and all its children.
Fully collapse collapses the selection and all its children.
Hide empty classes whether to show empty classes in the tree or not.
Tip
To expand an item in Entity Tree, you can also double-click on the item or press the right arrow. This will only expand the next layer and leave the children expanded or collapsed depending on their previous state. Items in gray don’t have any children, thus they cannot be expanded. To collapse an expanded item, double-click on it again or press the left arrow.
Tip
Entity Tree also supports Sticky selection, which allows one to extend the selection by clicking on items without pressing Ctrl. To enable Sticky selection, select Settings from the hamburger menu, and check the corresponding box.
Using the Graph View
Graph View presents the structure of entities from one database in the shape of a graph:

Building the graph
To build the graph, select any number of items in the Entity Tree. What is included in the graph depends on the specific selection you make in the Entity Tree:
To include all entities from the database, select the root item.
To include all entities of an entity class, select the corresponding class item.
To include specific entities, select them by holding down Ctrl.
Note
In Graph View, a small unnamed vertex represents a multidimensional entity with multiple elements, whereas a bigger named vertex represents a zero dimensional entity. An arc between entities indicates that the 0-D entity is an element of that N-D entity.
The graph automatically includes N-D entities whenever all the elements of that entity are included (even if these entities are not selected in Entity Tree). You can change this behavior to automatically include N-D entities whenever any of the member elements are included. To do this, enable Auto-expand entities via the Graph View’s context menu.
Manipulating the graph
You can move items in the graph by dragging them with your mouse. By default, each items moves individually. Like in the Design view, multiple items can be moved at once by selecting them first.
To display Graph View’s context menu, just right-click on an empty space in the graph. The context menu has the following options:
Add entities… opens up the add entities dialog, from where new entities can be added.
Search highlights the specified entities with color so that they are easier to visualize.
Hide classes can be used to disable all of the entities from an entity class from showing in the graph. Show can then be used to bring back the hidden classes one by one or Show all to bring them all back.
Prune classes works like Hide classes but it also hides all the classes that have the specified class as an element. Once again these can be brought back one by one with Restore or all at once with Restore all.
Zoom has three options: zoom out, zoom in and reset zoom. Using the scroll wheel of the mouse on the Graph View also works.
Arc-length has two buttons: one for making the arcs between the entities longer and one for making them shorter.
Rotate rotates the whole graph by 15° per step. Also can be done by holding down SHIFT while scrolling with the mouse wheel.
Auto-expand entities If enabled, the graph will also include entities where the selections are members besides just the selections. if disabled, the graph will only show the selected entities.
Merge databases Whether to merge the databases or not.
Snap entities to grid makes it so that the placement of the entities can’t be arbitrary anymore but instead they can only lay on a grid.
Max. entity dimension count defines a cutoff for the number of dimensions an entity can have and still be drawn.
Number of build iterations defines the maximum numbers of iterations the layout generation algorithm can make.
Minimum distance between nodes (%) is used for setting the ideal distance between entities in the graph.
Decay rate of attraction with distance The higher this number, the lesser the attraction between distant vertices when drawing the graph.
Select graph parameters is where different aspects of the graph can be mapped to for example parameter values.
Select background image can be used to set any .svg image as the background for the graph.
Save positions Saves the positions of the items into the database. To clear the saved position select Clear saved positions.
Save state… saves the drawn graph. Selecting a specific state from Load state… will load that state into the Graph View. Saved states can be deleted from Remove state.
Export as image… can be used to export the image of the graph in either .svg or .pdf formats
Export as video… can be used to export the video of the graph.
Rebuild to rebuild the whole graph.
Note
Graph View supports extended selection and rubber-band selection. To extend a selection, press and hold Ctrl while clicking on the items. To perform rubber-band selection, drag your mouse around the items you want to select.
Note
Pruned items are remembered across graph builds.
To display an entity item’s context menu, just right-click on it. The context menu has a few different options:
To expand or collapse N-D entities, on an entities context menu hover Expand or Collapse and select the entity class from the popup menu.
Connect entities allows the creation of new N-D entities straight from the Graph View. When hovering over the option, the list of relevant multi dimensional entity classes where the selected entity could possibly be a member are shown. After selecting one of the items in the list, the entities that you want to make up the new new entity in the selected entity class can be selected by clicking them in the graph. Once the selections are made, a popup showing the to be added entities is shown. By default every permutation of the selections is staged to be added but individual items can be also deselected.
Edit, Remove and Duplicate work as they do in the Entity Tree.
Viewing parameter definitions and values as well as entity alternatives
Using Table Views
Table View’s: Parameter value, Parameter definition and Entity alternative present entity data from all databases in the form of tables:

To filter a Table View by any entities and/or classes, select the corresponding items in either Entity Tree or Graph View. To remove all these filters, select the root item in Entity Tree.
A Table View can also be filtered by selecting alternatives or scenarios from Alternative and Scenario tree. This filter is orthogonal to the entity/class filter and can be used together with it. To remove all these filters, simply select the root item in Entity Tree or deselect all items from Alternative and Scenario tree.
All the filters described above can be cleared with the Clear all filters item available in the right-click context menu of the Table View.
To apply a custom filter on a Table View, click on any horizontal header. A menu will pop up listing the items in the corresponding column:

Uncheck the items you don’t want to see in the table and press Ok. Additionally, you can type in the search bar at the top of the menu to filter the list of items. To remove the current filter, select Remove filters.
To filter a Table View according to a selection of items in the table itself, right-click on the selection to show the context menu, and then select Filter by or Filter excluding. To remove these filters, select Remove filters from the header menus of the filtered columns.
Tip
You can rearrange columns in Table Views by dragging the headers with your mouse. The ordering will be remembered the next time you open Spine DB editor.
Entity alternative
Entity alternative provides a way to set which entities are active and which are not in each alternative:

Viewing parameter values and multidimensional entities
Using Pivot View and Frozen Table
Pivot View and Frozen Table present data for an individual class from one database in the form of a pivot table, optionally with frozen dimensions:

To populate the tables with data for a certain class, just select the corresponding class item in Entity Tree.
Selecting the input type
Pivot View and Frozen Table support four different input types:
Value (the default): it shows entities, parameter definitions, alternatives, and databases in the headers, and corresponding parameter values in the table body.
Index: Similar to the above, but it also shows parameter indexes in the headers. Indexes are extracted from special parameter values, such as time-series.
Element: it shows entities, and databases in the headers, and corresponding multidimensional entities in the table body. It only works when a N-D entity is selected in the Entity Tree.
Scenario: it shows scenarios, alternatives, and databases in the header, and corresponding rank in the table body.
You can select the input type from the Pivot section in the hamburger menu.
Note
In Pivot View, header blocks in the top-left area indicate what is shown in each horizontal and vertical header. For example, in Value input type, by default, the horizontal header has two rows, listing alternative and parameter names, respectively; whereas the vertical header has one or more columns listing entity names.
Pivoting and freezing
To pivot the data, drag a header block across the top-left area of the table. You can turn a horizontal header into a vertical header and vice versa, as well as rearrange headers vertically or horizontally.
To freeze a dimension, drag the corresponding header block from Pivot View into Frozen table. To unfreeze a frozen dimension, just do the opposite.
Note
Your pivoting and freezing selections for any class will be remembered when switching to another class.
Tip
If you are not seeing the data you think you should be seeing, it might be because there is some selection active in the Frozen Table that is filtering those values out of the Pivot View.
Filtering
To apply a custom filter on Pivot View, click on the arrow next to the name of any header block. A menu will pop up listing the items in the corresponding row or column:

Uncheck the items you don’t want to see in the table and press Ok. Additionally, you can type in the search bar at the top of the menu to filter the list of items. To remove the current filter, select Remove filters.
To filter the Pivot View by an individual vector across the frozen dimensions, select the corresponding row in Frozen Table.
Viewing alternatives and scenarios
You can find alternatives from all databases under Alternative:

To view the alternatives from each database, expand the root item for that database.
Viewing scenarios
You can find scenarios from all databases under Scenario tree:

To view the scenarios from each database, expand the root item for that database. To view the alternatives for a particular scenario, expand the corresponding scenario item.
Viewing parameter value lists
You can find parameter value lists from all databases under Parameter value list:

To view the parameter value lists from each database, expand the root item for that database. To view the values for each list, expand the corresponding list item.
Viewing metadata
You can find metadata from all databases under Metadata:

See also Spine Metadata Description.
Viewing item metadata
You can find metadata for currently selected entities or parameter values under Item metadata:

Adding data
This section describes the available tools to add new data. Note that after adding data to a Spine Database, it still needs to be committed in order for the changes to take effect beyond just the current session in the Spine Database Editor. More information about this in the chapter Committing and History.
Adding entity classes
From Entity Tree
Right-click on the root item in Entity Tree to display the context menu, and select Add entity classes.
The Add entity classes dialog will pop up:

Select the number of dimensions using the spinbox at the top. The amount of dimensions determines the number of dimension names that need to be selected. With 0-dimensional classes, like in the image above, only the name of the created entity class is required. The class’s name is to be entered below the header entity class name. In other cases like in the image below, in addition to the created classes name, also the classes making up the new class need to be selected:

They need to be filled under the headers dimension name (1) through dimension name (N) where N is the selected dimension. Note that because of this, there needs to be at least N entity classes already defined in the database when creating an N dimensional entity class. To display a list of available classes, start typing or double click on the cell below the header. Optionally, you can enter a description for each class under the description header. Double clicking the cell under the header display icon will open up the icon editor where the visual representation of the class can be modified:

This editor can also be opened by right clicking on the corresponding cell and selecting Open display icon editor. From the right click context menu, the display icon id can also be copied. This might be useful if there is a need to have multiple classes use the same icon, since the value can just be pasted into the cells.
The boolean value of active by default will determine whether the entities created under the created class will have the value under entity alternative set as true or false by default. Finally, select the databases where you want to add the entity classes under databases.
Multiple additions can be at once. When some information is inserted into the preceding row, a new empty row will appear in the dialog where a new class with the same dimensions can be defined. Delete entire rows from the dialog with Remove selected rows. When you’re ready, press Ok to make the additions.
Tip
All the Add… dialogs support pasting tabular (spreadsheet) data from the clipboard. Just select any cell in the table and press Ctrl+V. If needed, the table will grow to accommodate the exceeding data. To paste data on multiple cells, select all the cells you want to paste on and press Ctrl+V.
Adding entities
From Entity Tree or Graph View
Right-click on the root item in Entity Tree and select Add entities, or click on an empty space in the Graph View and select Add entities… from the context menu.
This will open up the Add entities dialog:

Select the class where you want to add the entities from Entity class. It will list all of the entity classes. To narrow down the list, instead of opening the dialog from the root item, open it from a specific entity class item in the Entity Tree. This way the class will be preselected from the list and the list will overall only contain other classes that are relevant to the selected class.
Enter the names of the entities under entity name. Finally, select the databases where you want to add the entities under databases. When you’re ready, press Ok. Rows can once again be deleted with the Remove selected rows -button.
With N-D entity classes, the elements need to be specified. After defining the elements the entity’s name can be modified:

New entities for an existing N-D entity class can also be created easily from the Graph view. Make sure all the entities you want as members in the new entity are in the graph. To start the new N-D entity, either double click on one of the entity items in the graph, or right click on it to display the context menu, and choose the class from Connect entities. After selecting the class the mouse cursor will adopt a cross-hairs shape.
When hovering over a entity item, the cursor will aid by indicating an entity that can’t be a member by turning into a red restriction -sign. When nearly all of the selections made and only the last member needs to be selected, the cursor will turn into a green checkmark when hovering over an appropriate entity. Click on each of the remaining member entities one by one to add them to the new entity. Once you’ve added enough members for the entity class, a dialog will pop up. In the dialog, all of the possible permutations of the selected members are presented. Check the boxes next to the entities you want to add, and press OK.
From Pivot View
To add an entity to a specific 0-D entity class, bring the class to Pivot View using either Value or Index (see Using Pivot View and Frozen Table). There under the class name just type a new name and the new entity will be added under the class. Note that is only possible to add 0-D entities this way even if you have selected an N-D class from the Entity Tree.
To enter a new entity to an N-D class, select the Element -view from the hamburger menu. This view contains all of the possible combinations of elements in the selected class. The entities can be added by checking the boxes and removed by unchecking them.
Duplicating entities
To duplicate an existing entity with all its parameter values and other associated data, right-click over the corresponding entity item in Entity Tree to display the context menu, and select Duplicate entity. The new entity will have the same name with an added (1) to indicate that it is a copy of the original entity. It can be renamed to be something else afterwards.
Adding entity groups
Right-click on an entity class item in Entity Tree, and select Add entity group from the context menu.
The Add entity group dialog will pop up:

Enter the name of the group, and select the database where you want the group to be created.
Select the members under Non members, and press (>>) to add the members and (
<<) to remove them.
Multiple selection is supported with Ctrl and Shift. Finally press OK to create the group.
When you’re happy with your selections, press OK to add the group to the database.
Adding parameter definitions
From Table View
To add new parameter definitions for an entity class, just fill the last empty row of Parameter definition. Only two of the fields are required when creating a new parameter definition: entity_class_name and parameter_name. Enter the name of the class under entity_class_name. To display a list of available entity classes, start typing in the empty cell or double click it. For the name of the parameter choose something that isn’t already defined for the specified entity class. Optionally, you can also specify a parameter value list, a default value and a description.
In the column value_list_name a name for a parameter value list can be selected. Leaving this field empty means that later on when creating parameter values with this definition, the values are arbitrary. Meaning that the value could for example be a string or an integer. When the parameter value list is defined in the parameter definition, only the values in the list will be allowed to be chosen. For the creation of parameter value lists, see Adding parameter value lists.
In the default_value field, the default value can be set. The default value can be used in cases where the value is not specified. The usage of default_value is really tool dependent, meaning that the Spine Database Editor doesn’t use the information of the default value anywhere, but it is instead left to the tool creators on how to utilize the default value. A short description for the parameter can be written in the description column.
The parameter is added when the background of the cells under entity_class_name and database become gray.
From Pivot View
To add a new parameter definition for a class, bring the corresponding class to Pivot View using the Value input type (see Using Pivot View and Frozen Table). The parameter header of Pivot View will be populated with existing parameter definitions for the class. Enter a name for the new parameter in the last cell of that header.
Adding parameter values
From Table View
To add new parameter values for an entity, just fill the last empty row of the Parameter value -table. Enter the name of the class under entity_class_name, the name of the entity under entity_byname, the name of the parameter under parameter_name, and the name of the alternative under alternative_name. Optionally, you can also specify the parameter value right away under the value column. The database where the value will be added to is displayed in the last column of the table. To display a list of available entity classes, entities, parameters, or alternatives, just start typing or double click under the appropriate column. The parameter value is added when the background of the cells under entity_class_name and database become gray.
Note
To add parameter values for a 0-D entity, the entity has to exist beforehand. However, when adding parameter values for an N-D entity, you can specify any valid combination of elements by double clicking the cell under entity_byname, which opens up the Select elements -dialog. The specified N-D entity will be created if it doesn’t yet exist.
From Pivot View
To add parameter value for any entity, bring the corresponding class to Pivot View using the Value input type (see Using Pivot View and Frozen Table). Then, enter the parameter value in the corresponding cell in the table body.
Tip
All Tables Views and Pivot Views support pasting tabular (e.g., spreadsheet) data from the clipboard. Just select any cell in the table and press Ctrl+V. If needed, Table Views will grow to accommodate the exceeding data. To paste data on multiple cells, select all the cells you want to paste on and press Ctrl+V.
Adding entity alternatives
To add an entity alternative, open the Entity Alternative -Table View. There under entity_class_name select the class. Under entity_byname select the specific entity from that class and from alternative_name select the alternative. Then set the value of the active -column to either true or false by double clicking it. The background of the cells under entity_class_name and database should become gray, indicating that the entity alternative has been added.
Adding alternatives
From Alternative
To add a new alternative, just select the last item under the appropriate database, and enter the name of the new alternative.
You can also copy and paste alternatives between different databases.
From Pivot View
Select the Scenario input type (see Using Pivot View and Frozen Table). To add a new alternative, enter a name in the last cell of the alternative header.
Adding scenarios
From Scenario Tree
To add a new scenario, just select the last item under the appropriate database, and enter the name of the scenario.
To add an alternative for a particular scenario, drag the alternative item from Alternative and drop it under the corresponding scenario. The position where you drop it determines the alternative’s rank within the scenario. Alternatives can also be copied from Alternative and pasted at the appropriate position in Scenario Tree.
If it is desirable to base a scenario on an existing one, scenarios can be duplicated using the Duplicate item in the right-click context menu. It is also possible to copy and paste scenarios between databases.
Note
Alternatives with higher rank have priority when determining the parameter value for a certain scenario. If the parameter value is specified for two alternatives, and both of them happen to coexist in a same scenario, the value from the alternative with the higher rank takes precedence.
Note
As noted in the tooltip, scenario names longer than 20 characters may become shortened in generated files. This can happen for example when exporting the scenarios using the Exporter -project item. This can lead to confusion later on if the first 20 characters of the scenario names are identical. Therefore it is recommended to have a unique identifier for each scenario in the first 20 characters of its name.
From Pivot View
Select the Scenario input type (see Using Pivot View and Frozen Table). To add a new scenario, enter a name in the last cell of the scenario header.
From Generate scenarios
Scenarios can be added also by automatically generating them from existing alternatives. Select the alternatives in Alternative (using Ctrl and Shift while clicking the items), then right click to open a context menu. Select Generate scenarios…

Give the scenario names a prefix. An index will be appended to the prefix automatically: prefix01, prefix02,… Select appropriate operation from the Operation combo box. Checking the Use base alternative check box will add the selected alternative to all generated scenarios as the lowest rank alternative. The Alternative by rank list allows reordering the ranks of the alternatives.
Adding parameter value lists
To add a new parameter value list, go to Parameter Value List and select the last item under the appropriate database, and enter the name of the list.
To add new values for the list, expand the list with the right-arrow and select the last empty item under the corresponding list item, and enter the value. To enter a complex value, right-click on the empty item and select Edit… from the context menu to open the value editor.
Note
To be actually added to the database, a parameter value list must have at least one value.
Adding metadata and item metadata
To add new metadata go to Metadata and add a new name and value to the last row.
To add a new link metadata for an item, select an entity from one of the entity trees or a parameter value from one of the parameter value tables. Then go to Item metadata and select the appropriate metadata name and value on the last row.
Updating data
This section describes the available tools to update existing data.
Updating entities and classes
From Entity Tree or Graph View
Select any number of entity and/or class items in Entity Tree, or any number of entity items in Graph View. Then, right-click on the selection and choose Edit… from the context menu.
Depending on the selections, at least one Edit… dialog will pop up, and the tables will be filled with the current data of selected items. E.g.:

Modify the field(s) you want under the corresponding column(s). Specify the databases where you want to update each item under the databases column. When you’re ready, press OK.
From Pivot View
To rename an entity of a specific class, bring the class to Pivot View using any input type (see Using Pivot View and Frozen Table). Then, just edit the appropriate cell in the corresponding class header.
Updating parameter definitions and values
From Table Views
To update parameter data, just go to the appropriate Table View and edit the corresponding row.
From Pivot View
To rename parameter definitions for a class, bring the corresponding class to Pivot View using the Value input type (see Using Pivot View and Frozen Table). Then, just edit the appropriate cell in the parameter header.
To modify parameter values for an entity, bring the corresponding class to Pivot View using the Value input type (see Using Pivot View and Frozen Table). Then, just edit the appropriate cell in the table body.
Updating entity alternatives
To update an entity alternative, edit the corresponding row from Entity Alternative in Table View.
Updating alternatives
From Pivot View
Select the Scenario input type (see Using Pivot View and Frozen Table). To rename an alternative, just edit the proper cell in the alternative header.
From Alternative
To rename an alternative, just edit the appropriate item in Alternative.
Updating scenarios
From Pivot View
Select the Scenario input type (see Using Pivot View and Frozen Table). To rename a scenario, just edit the proper cell in the scenario header.
To change the alternatives of a scenario as well as their ranks, check or uncheck the boxes on the pivot table. The number in the checkbox signifies the alternative’s rank.
From Scenario Tree
To rename a scenario, just edit the appropriate item in Scenario Tree.
To change scenario alternative ranks, just drag and drop the items under the corresponding scenario.
Updating parameter value lists
To rename a parameter value list or change any of its values, just edit the appropriate item in Parameter value list.
Removing data
This section describes the available tools to remove data.
Purging items
To remove all items of specific types, select Edit -> Purge… () from the hamburger menu.
The Purge items dialog will pop up:

The databases that are opened in the Editor are listed under Databases. From there you can select the databases where the mass removal will take place. The Select all -option will check all of the boxes and Deselect all will in turn uncheck every box.
The type of items that are to be deleted, need to be specified under Items. There are a couple of useful buttons in addition to the same Select all and Deselect all: Select entity and value items and Select scenario items. The former will select the entity, entity_group, parameter_value, entity_metadata and parameter_value_metadata items in the list. The latter will select the alternative, scenario and scenario_alternative items. When you are happy with your choices, press Purge to perform the mass removal.
Note
The purge dialog can also be opened from the Properties -dock widget of a Data Store.
Tip
Purging can also be an automated part of the workflow. See Links for more information about purging a database automatically.
Removing entities and classes
From Entity Tree or Graph View
Select the items in Entity Tree or Graph View, corresponding to the entities and classes you want to remove. Then, right-click on the selection and choose Remove from the context menu.
The Remove items dialog will popup:

Specify the databases from where you want to remove each item under the databases column, and press OK.
From Pivot View
To remove entities from a specific class, bring the class to Pivot View using the Value input type (see Using Pivot View and Frozen Table), and select the cells in the table headers corresponding to the entities you want to remove. Then, right-click on the selection and choose the Remove entities option from the context menu. This will remove the selected rows.
Alternatively, to remove N-D entities of a specific class, bring the class to Pivot View using the Element input type (see Using Pivot View and Frozen Table). The Pivot View headers will be populated with all possible combinations of entities across the member classes. Locate the member entities you want to remove, and uncheck the corresponding box in the table body.
Removing parameter definitions and values
From Table View
To remove parameter definitions or values, go to the relevant Table View and select any cell in the row corresponding to the items you want to remove. Then, right-click on the selection and select the Remove row(s) option from the context menu. Multiple selection is supported and the removal can also be performed by pressing Ctrl+Del.
From Pivot View
To remove parameter definitions and/or values for a certain class, bring the corresponding class to Pivot View using the Value input type (see Using Pivot View and Frozen Table). Then:
Select the cells in the parameter header corresponding to the parameter definitions you want to remove, right-click on the selection and choose Remove parameter definitions from the context menu
Select the cells in the table body corresponding to the parameter values you want to remove, right-click on the selection and choose Remove parameter values from the context menu.
Removing alternatives
From Pivot View
Select the Scenario input type (see Using Pivot View and Frozen Table). To remove alternatives, select the to be removed items in the alternative header, right-click on the selection and choose Remove alternatives from the context menu.
From Alternative
To remove an alternative, just select the corresponding items in Alternative, right-click on the selection and choose Remove from the context menu.
Removing scenarios
From Pivot View
Select the Scenario input type (see Using Pivot View and Frozen Table). To remove scenarios, just select the proper cells in the scenario header, right-click on the selection and choose Remove scenarios from the context menu.
From Scenario Tree
To remove a scenario, just select the corresponding items in Scenario Tree, right-click on the selection and choose Remove from the context menu.
To remove a scenario alternative from a scenario, select the corresponding alternative items in Scenario Tree, right-click on the selection and choose Remove from the context menu.
Removing parameter value lists
To remove a parameter value list or any of its values, just select the corresponding items in Parameter value list, right-click on the selection and choose Remove from the context menu.
Removing metadata
Select the corresponding items in Metadata, right-click on the selection and choose Remove row(s) from the context menu.
Removing item metadata
Select the corresponding items in Item metadata, right-click on the selection and choose Remove row(s) from the context menu.
Managing data
This section describes the available tools to manage data, i.e., adding, updating or removing data at the same time.
Managing entity groups
To modify entity groups, expand the corresponding entity class item in Entity Tree to display the group item, right-click on it and select Manage members from the context menu. The Manage members dialog will pop up:

To add new member entities, select them under Non members, and press the (>>) button in the middle.
To remove current members, select them under Members, and press the (
<<) button in the middle.
Multiple selection works in both lists.
When you’re happy with the members, press OK.
Note
Changes made using the Manage members dialog are not applied to the database until you press OK.
Managing N-D entities
Right click the root item, or an N-D entity item in Entity Tree and from the context menu select Manage elements. The Manage elements dialog will pop up:

To get started, select an entity class and a database from the combo boxes at the top.
To add entities, select the elements for each class under Available elements
and press the add button (>>) in the middle of the form.
The entities will appear at the top of the table under Existing entities.
To add multiple entities at the same time, select multiple elements for one or more of the classes. All possible permutations of the selected elements will be added to Existing entities.
Tip
To extend the selection of entities for a class, press and hold the Ctrl key while clicking on more items. Holding down Shift allows to select an area of items by clicking the start and end of the selection.
To remove entities, select the appropriate rows under Existing entities
and press the remove button () on the right.
When you’re happy with your changes, press OK.
Note
Changes made using the Manage elements dialog are not applied to the database until you press OK.
Importing and exporting data
This section describes the available tools to import and export data.
Overview
Spine Database Editor supports importing and exporting data in three different formats: SQLite, JSON, and Excel. The SQLite import/export uses the Spine Database format. The JSON and Excel import/export use a specific format described in Format specifications.
Importing
To import a file, select File –> Import from the hamburger menu. The Import file dialog will pop up. Select the file type (SQLite, JSON, or Excel), enter the path of the file to import, and accept the dialog.
Tip
You can undo import operations using Edit -> Undo.
Exporting
Mass export
To export items in mass, select File –> Export from the hamburger menu. The Export items dialog will pop up:

Select the databases you want to export under Databases, and the type of items under Items, then press Ok. The Export file dialog will pop up now. Select the file type (SQLite, JSON, or Excel), enter the path of the file to export, and accept the dialog.
Selective export
To export a specific subset of items, select the corresponding items in the Entity Tree, right click on the selection to bring the context menu, and select Export.
The Export file dialog will pop up. Select the file type (SQLite, JSON, or Excel), enter the path of the file to export, and accept the dialog.
Session export
To export only uncommitted changes made in the current session, select File –> Export session from the hamburger menu.
The Export file dialog will pop up. Select the file type (SQLite, JSON, or Excel), enter the path of the file to export, and accept the dialog.
Note
Export operations include all uncommitted changes.
Accessing/using exported files
Whenever you successfully export a file, a button with the file name is created in the Exports bar at the bottom of the form. Pressing that button will open the JSON or Excel file with the default program that your system associates with that filetype. Exports of SQLite file type will be opened in a new tab of the Spine Database Editor. To open the folder containing the export, click on the arrow next to the file name and select Open containing folder from the popup menu.
Format specifications
Tip
To create a template file with the JSON or Excel format you can simply export an existing Spine database into one of those formats.
Excel format
Note
Excel exports are not comprehensive. Even though every type of item is selectable in the exporting selection, sheets will be generated only for some of the selections. Things like metadata and parameter value lists don’t currently have export support with excel. The JSON export on the other hand is comprehensive and will export every detail about the database.
When parameter values are exported, the generated Excel will have every entity class on its own sheet. If the entity has indexed values (time-series, map etc.) as well as single values (floats, strings etc.) the entity will have more than one sheet, one containing the single values and others that unpack the indexed values:
scalar parameter data:
indexed parameter data:
JSON format
The JSON export is complete since it contains all of the data from the database.
The JSON format consists of a single JSON object with the following OPTIONAL
keys:
entity_classes: the value of this key
MUST
be a JSON array, representing a list of entity classes. Each element in this arrayMUST
be itself a JSON array andMUST
have three elements:The first element
MUST
be a JSON string, indicating the entity class name.The second element
MUST
be a JSON array, indicating the member entity classes. Each element in this arrayMUST
be a JSON string, indicating the entity class name. In case of 0-D entity class, the array is empty.The third element
MUST
be either a JSON string, indicating the entity class description, or null.The fourth element
MUST
be either a JSON integer, indicating the entity class icon code, or null.The fourth element
MUST
be a JSON boolean, indicating the state of active by default.
superclass_subclasses: the value of this key
MUST
be a JSON array, representing a list of superclasses. Each element in this arrayMUST
be itself a JSON array andMUST
have two elements:The first element
MUST
be a JSON string, indicating the superclass name.The second element
MUST
be a JSON string, indicating the subclass name.
entities: the value of this key
MUST
be a JSON array, representing a list of entities. Each element in this arrayMUST
be itself a JSON array andMUST
have three elements:The first element
MUST
be a JSON string, indicating the entity class name.The second element
MUST
be a JSON array, if the entity is N-dimensional. In this case each element in the arrayMUST
be a JSON string itself, each being an element of the entity. If the entity class is 0-D, this elementMUST
be a JSON string, indicating the entity name.The third element
MUST
be either a JSON string, indicating the entity description, or null.
Entity alternatives: the value of this key
MUST
be a JSON array, representing a list of entity alternatives. Each element in this arrayMUST
be itself a JSON array andMUST
have four elements:The first element
MUST
be a JSON string, indicating the entity class name.The second element
MUST
be either a JSON array or a JSON string. In the case of a N-dimensional entity the arrayMUST
itself contain JSON strings representing the element name list of the entity. If the entity is 0-D, a JSON string of the name of the entity is enough, but also a JSON array of one element is supported.
entity_groups: the value of this key
MUST
be a JSON array, representing a list of entity groups. Each element in this arrayMUST
be itself a JSON array andMUST
have three elements:The first element
MUST
be a JSON string, indicating the entity class.The second element
MUST
be a JSON string, indicating the entity group name.The third element
MUST
be a JSON string, indicating the member entity’s name.
parameter_value_lists: the value of this key
MUST
be a JSON array, representing a list of parameter value lists. Each element in this arrayMUST
be itself a JSON array andMUST
have two elements:The first element
MUST
be a JSON string, indicating the parameter value list name.The second element
MUST
be either a JSON object, string, number, or null, indicating the value.
parameter_definitions: the value of this key
MUST
be a JSON array, representing a list of parameter definitions. Each element in this arrayMUST
be itself a JSON array andMUST
have five elements:The first element
MUST
be a JSON string, indicating the entity class name.The second element
MUST
be a JSON string, indicating the parameter name.The third element
MUST
be either a JSON object, string, number, or null, indicating the parameter default value.The fourth element
MUST
be a JSON string, indicating the associated parameter value list, or null.The fifth element
MUST
be either a JSON string, indicating the parameter description, or null.
parameter_values: the value of this key
MUST
be a JSON array, representing a list of entity parameter values. Each element in this arrayMUST
be itself a JSON array andMUST
have four elements:The first element
MUST
be a JSON string, indicating the entity class name.The second element
MUST
be a JSON array, if the entity is N-dimensional. In this case each element in the arrayMUST
be a JSON string itself, each being an element of the entity. If the entity class is 0-D, this elementMUST
be a JSON string, indicating the entity name.The third element
MUST
be a JSON string, indicating the parameter name.The fourth element
MUST
be either a JSON object, string, number, or null, indicating the parameter value.
There is one
OPTIONAL
element:The fifth element
MUST
either be a JSON string indicating the alternative, or null. If this element is not present, an alternative named Base will be created if it doesn’t exist and the values will be set in that alternative.
alternatives: the value of this key
MUST
be a JSON array, representing a list of alternatives. Each element in this arrayMUST
be itself a JSON array andMUST
have two elements:The first element
MUST
be a JSON string, indicating the alternative nameThe second element
MUST
be either a JSON string, indicating the alternative description, or null.
scenarios: the value of this key
MUST
be a JSON array, representing a list of alternatives. Each element in this arrayMUST
be itself a JSON array andMUST
have two elements:The first element
MUST
be a JSON string, indicating the scenario name.The second element
MUST
be a JSON boolean, indicating the scenario alternative active state.The third element
MUST
be either a JSON string, indicating the scenario description, or null.
scenario alternatives: the value of this key
MUST
be a JSON array, representing a list of alternatives. Each element in this arrayMUST
be itself a JSON array andMUST
have three elements:The first element
MUST
be a JSON string, indicating the scenario name.The second element
MUST
be a JSON string, indicating the alternative name aowfiuhwaofiajw.
Example:
{
"entity_classes": [
["connection",[],"A transfer of commodities between nodes. E.g. electricity line,gas pipeline...",280378317271233,true],
["node",[],"A universal aggregator of commodify flows over units and connections,with storage capabilities.",280740554077951,true],
["unit",[],"A conversion of one/many comodities between nodes.",281470681805429,true],
["unit__from_node",["unit","node"],"Defines the `nodes` the `unit` can take input from,and holds most `unit_flow` variable specific parameters.",281470681805657,true],
["unit__to_node",["unit","node"],"Defines the `nodes` the `unit` can output to,and holds most `unit_flow` variable specific parameters.",281470681805658,true],
["connection__node__node",["connection","node","node"],"Holds parameters spanning multiple `connection_flow` variables to and from multiple `nodes`.",null,true]
],
"entities": [
["connection","Bastusel_to_Grytfors_disch",null],
["node","Bastusel_lower",null],
["node","Bastusel_upper",null],
["node","Grytfors_upper",null],
["unit","Bastusel_pwr_plant",null],
["unit__from_node",["Bastusel_pwr_plant","Bastusel_upper"],null],
["unit__to_node",["Bastusel_pwr_plant","Bastusel_lower"],null],
["connection__node__node",["Bastusel_to_Grytfors_disch","Grytfors_upper","Bastusel_lower"],null]
],
"parameter_value_lists": [
["balance_type_list","balance_type_group"],
["balance_type_list","balance_type_node"],
["balance_type_list","balance_type_none"]
],
"parameter_definitions": [
["connection","connection_availability_factor",1,null,"Availability of the `connection`,acting as a multiplier on its `connection_capacity`. Typically between 0-1."],
["connection__node__node","connection_flow_delay",{"type": "duration","data": "0h"},null,"Delays the `connection_flows` associated with the latter `node` in respect to the `connection_flows` associated with the first `node`."],
["node","balance_type","balance_type_node","balance_type_list","A selector for how the `:nodal_balance` constraint should be handled."],
["node","demand",0,null,"Demand for the `commodity` of a `node`. Energy gains can be represented using negative `demand`."],
["node","fix_node_state",null,null,"Fixes the corresponding `node_state` variable to the provided value. Can be used for e.g. fixing boundary conditions."],
["node","has_state",null,null,"A boolean flag for whether a `node` has a `node_state` variable."],
["unit__from_node","unit_capacity",null,null,"Maximum `unit_flow` capacity of a single 'sub_unit' of the `unit`."],
["unit__to_node","unit_capacity",null,null,"Maximum `unit_flow` capacity of a single 'sub_unit' of the `unit`."]
],
"parameter_values": [
["connection__node__node",["Bastusel_to_Grytfors_disch","Grytfors_upper","Bastusel_lower"],"connection_flow_delay",{"type": "duration","data": "1h"},"Base"],
["node","Bastusel_upper","demand",-0.2579768519,"Base"],
["node","Bastusel_upper","fix_node_state",{"type": "time_series","data": {"2019-01-01T00:00:00": 5581.44,"2019-01-01T01:00:00": -1,"2019-01-07T23:00:00": 5417.28}},"Base"],
["node","Bastusel_upper","has_state",null,"Base"],
["unit__from_node",["Bastusel_pwr_plant","Bastusel_upper"],"unit_capacity",170,"Base"]
],
"alternatives": [
["Base","Base alternative"]
]
}
Committing and History
Committing
Note
Changes are not immediately saved to the database(s). They need to be committed separately.
An asterisk (*) in a tab of Spine Database Editor indicates that the session has uncommitted changes:

If the database is opened from a Data Store, the corresponding project item will also have a notification in its upper right corner indicating that the database has uncommitted changes.
To commit your changes, select Session -> Commit from the hamburger menu or press Ctrl+Enter while the Spine Database Editor -window is active to open the commit dialog:

There is a default text “Updated” readily filled in. It is however good practise to write a short message that clearly describes what changes have been made to the database. Once the commit message is to you liking, press Commit. Any changes made in the current session will be saved into the database.
If you try to close a tab with uncommitted changes the following dialog will open:

There are a few different options: Commit and close will do exactly what it says, Discard changes and close will automatically rollback the changes to the last commit and then close the editor tab. Cancel just closes the dialog and allows you to work on the database again. If you check the box Do not ask me again and select any of the other options beside Cancel, the selection you made will be automatically presumed whenever you close a tab with uncommitted changes. This means that you will not see this dialog again but the changes will be automatically committed or not depending on the selection you made previously.
Rollback
To undo all changes since the last commit, select Session -> Rollback from the hamburger menu or press Ctrl+Backspace while the Spine Database Editor -window is active. A dialog confirming the rollback action will open. From there, select Rollback to proceed.
Tip
To undo/redo individual changes, use the Edit -> Undo and Edit -> Redo actions from the hamburger menu.
Note
After rolling back to the last commit, the changes made in the session will no longer be available through undo/redo.
History
To examine the commit history of the database, select Session -> History… from the hamburger menu. The commit viewer will pop up:

All the commits made in the database will show here, each includes the timestamp. author and commit message. By selecting individual commits, the affected items can be inspected in the box on the right.
Vacuum
Vacuuming is available for Spine Databases in the SQLite format. Basically it tries to free up some unnecessary
memory from the .sqlite
-file. If you have very large databases, it might be beneficial to vacuum it once in a while.
More detailed explanation on what vacuuming does to the SQLite database can be found
here.
To vacuum a database, either press the Vacuum -button from the Data Store Properties -panel, or
straight from the Spine Database Editors hamburger menu Edit->Vacuum.
After the vacuum is finished, a message informing the amount of bytes freed from the database is shown.
Plotting
Basic data visualization is available in the Spine database editors. Currently, it is possible to plot scalar values as well as time series, arrays and one dimensional maps with some limitations.
To plot a column, select the values from a table and then Plot from the right click popup menu.


Selecting data in multiple columns plots the selection in a single window.
To add a plot to an existing window select the target plot window from the Plot in window submenu. There are some restrictions for what kinds of plots can be shown on the same window. In the example below two different maps have been plotted on the same graph.


If a plot is clicked with the right mouse button, options to copy or show the plot data are presented. When the data is copied it is saved to the clipboard in csv format with tab as the delimiter. If Show plot data… is clicked a new window opens that contains a table of the data used in the plot.


X column in pivot table
It is possible to plot a column of scalar values against a designated X column in the pivot table.
To set a column as the X column right click the top empty area above the column header and select Use as X from the popup menu. (X) in the topmost cell indicates that the column is designated as the X axis.

When selecting and plotting other columns in the same table the data will be plotted against the values in the X column instead of row numbers.
Parameter Value Editor
Parameter value editor is used to edit entity parameter values such as time series, time patterns or durations. It can also convert between different value types, e.g. from a time series to a time pattern.
The editor can be opened by right clicking on the value field that you want to edit in a Spine database editor and selecting Edit… from the popup menu. In most cases the editor can be opened again by double clicking an existing value. With plain values like strings and floats this will not work since double clicking starts the text editor in that field.
Choosing value type
The combo box at the top of the editor window allows changing the type of the current value.

Plain values
The simplest parameter values are of the Plain value type. The editor window lets you to write a number or string directly to the input field or set it to true, false or null as needed.

Numbers and strings can also be inserted without going through the value editor by double clicking on a value field. If the users input is a number like 3.14, the value type will be interpreted as number or string. If the input is a string like “ok”, the value type will automatically be set to string.
Maps
Maps are versatile nested data structures designed to contain complex data including one and multi dimensional indexed arrays. In Parameter value editor a map is shown as a table where the last non-empty cell on each row contains the value while the preceding cells contain the value’s indexes.

The extra gray column on the right allows expanding the map with a new dimension. You can append a value to the map by editing the bottom gray row. The reddish cells are merely a guide for the eye to indicate that the map has different nesting depths.
A Right click popup menu gives options to open a value editor for individual cells, plot individual and multiple cells, insert/remove rows or columns (effectively changing map’s dimensions), trim empty columns from the right hand side and to copy and paste data. Copying and pasting data works between cells and external programs and can be also done using the usual Ctrl+C and Ctrl+V keyboard shortcuts.
The default name for new columns is x. Index names can however be modified. If a column holds both indices and data, the column header can also be modified. The last column of a map has to always contain values and therefore the header can’t be modified from the default name Value.
Convert leaves to time series ‘compacts’ the map by converting the last dimension into time series. This works only if the last dimension’s type is datetime. For example the following map contains two time dimensions. Since the indexes are datetimes, the ‘inner’ dimension can be converted to time series.

After clicking Convert leaves to time series the map looks like this:

Time series
There are two types of time series: variable and fixed resolution. Variable resolution means that the time stamps can be arbitrary while in fixed resolution series the time steps between consecutive stamps are fixed.


The editor window is split into two in both cases. The left side holds all the options and a table with all the data while the right side shows a plot of the series. The plot is not editable and is for visualization purposes only.
In the table rows can be added or removed from a popup menu available by a right click. Editing the last gray row appends a new value to the series. Data can be copied and pasted by Ctrl+C and Ctrl+V. Copying from/to an external spreadsheet program is supported.
The time steps of a fixed resolution series are edited by the Start time and Resolution fields. The format for the start time is ISO8601. The Resolution field takes a single time step or a comma separated list of steps. If a list of resolution steps is provided then the steps are repeated so as to fit the data in the table.
The Ignore year option available for both variable and fixed resolution time series allows the time series to be used independent of the year. Only the month, day and time information is used by the model.
The Repeat option means that the time series is cycled, i.e. it starts from the beginning once the time steps run out.
Time patterns
The time pattern editor holds a single table which shows the time period on the right column and the corresponding values on the left. Inserting/removing rows and copy-pasting works as in the time series editor.

Time periods consist of the following elements:
An interval of time in a given time-unit. The format is
Ua-b
, whereU
is eitherY
(for year),M
(for month),D
(for day),WD
(for weekday),h
(for hour),m
(for minute), ors
(for second); anda
andb
are two integers corresponding to the lower and upper bound, respectively.An intersection of intervals. The format is
s1;s2;...
, wheres1
,s2
, …, are intervals as described above.A union of ranges. The format is
r1,r2,...
, wherer1
,r2
, …, are either intervals or intersections of intervals as described above.
Arrays
Arrays are lists of values of a single type. Their editor is split into two: the left side holds the actual array while the right side contains a plot of the array values versus the values’ positions within the array. Note that not all value types can be plotted. The type can be selected from the Value type combobox. Inserting/removing rows and copy-pasting works as in the time series editor.

Datetimes
The datetime value should be entered in ISO8601 format. Clicking small arrow on right end of the input field opens up a calendar that can be used to select a date.

Durations
A single value or a comma separated list of time durations can be entered to the Duration field.

Spine Metadata Description
This is the metadata description for Spine, edited from https://frictionlessdata.io/specs/data-package/.
Required properties
title
One sentence description for the data sources.
sources
The raw sources of the data. Each source must have a
title
property and optionally apath
property. Example:"sources": [{ "title": "World Bank and OECD", "path": "http://data.worldbank.org/indicator/NY.GDP.MKTP.CD" }]
contributors
The people or organisations who contributed to the data. Must include
title
and may includepath
,email
,role
andorganization
. Example:"contributors": [{ "title": "Joe Bloggs", "email": "joe@bloggs.com", "path": "http://www.bloggs.com", "role": "author" }]
Role is one of
author
,publisher
,maintainer
,wrangler
, orcontributor
.created
The date this data was created or put together, in ISO8601 format (YYYY-MM-DDTHH:MM)
Optional properties
description
A description of the data. Describe here how the data was collected, how it was processed etc.
The description MUST be markdown formatted – this also allows for simple plain text as plain text is itself valid markdown. The first paragraph (up to the first double line break) should be usable as summary information for the package.
spine_results_metadata
Key contains results metadata (described in a separate document).
keywords
An array of keywords
homepage
A URL for the home on the web that is related to this data package.
name
Name of the data package, url-usable, all-lowercase string.
id
Globally unique id, such as UUID or DOI
licenses
Licences that apply to the data. Each item must have a
name
property (Open Definition license ID) or apath
property and may containtitle
. Example:"licenses": [{ "name": "ODC-PDDL-1.0", "path": "http://opendatacommons.org/licenses/pddl/", "title": "Open Data Commons Public Domain Dedication and License v1.0" }]
temporal
Temporal properties of the data (if applicable). Example using DCMI Period Encoding Scheme:
"temporal": { "start": "2000-01-01", "end": "2000-12-31", "name": "The first year of the 21st century" }
spatial
Spatial properties of the data (if applicable). Example using DCMI Point Encoding Scheme:
"spatial": { "east": 23.766667, "north": 61.5, "projection": "geographic coordinates (WGS 84)", "name": "Tampere, Finland" }
unitOfMeasurement
Unit of measurement. Can also be embedded in
description
.
Importing and Exporting Data
This section explains the different ways of importing and exporting data to and from a Spine database.
Importing data with Importer
Data importing is handled by the Importer project item which can import tabulated and to some degree tree-structured data into a Spine database from various formats. The same functionality is also available in Spine database editor from File->Import but using an Importer item is preferred because then the process is documented and repeatable.
Tip
A Tool item can also be connected to Importer to import tool’s output files to a database.
The heart of Importer is the Importer Specification Editor window in which the mappings from source data
to Spine database entities are set up. The editor window can be accessed
by the button in Importer’s Properties dock where existing specifications can also be selected
or by double-clicking the item on the Design View.

In the Properties tab there is also the option to cancel the import if an non-fatal error occurs during execution and also three options for how to handle if some of the values that you are trying to import already exist in the target Data Store. The three choices are:
- Keep existing
When this is selected, data that is already in the target Data Store will be kept and the new data the Importer tried to import is forgotten.
- Replace
This option means the imported data replaces old data in the target Data Store.
- Merge indexes
This option works mostly like the Replace option, but for indexed values like maps, time series and arrays the behavior is a little different. With these value types the old index-value pairs in the target Data Store will be kept and the new value pairs will be appended to it. If an index that is going to get imported already exist, the new imported value will overwrite the old value.
When the specification editor is opened for an Importer without a specification, a list of the supported connectors (file formats or other data sources) is presented. If the Importer is already connected to some data, it may have already selected the proper connector and is only waiting confirmation

When creating a Importer specification, it is usually helpful to have the data already connected to the Importer in question so it is easier to visualize how the importer is handling the data.
Importer specification editor
In the upper part of the specification editor, the name and description for the specification can be set. Underneath, the filepath is shown and it is modifiable. Next to the filepath the used connector type is shown. On the left side, the different tables the file has or that user has set up are shown. Next to that there are the connector specific options and underneath that a preview of the selected table is shown. The items in the table are highlighted according to the selected mapping. The mappings are listed on the right side of the editor. Underneath, the to be imported item types can be specified and other options set. Below that you can select the specific places in the source data where the entity names, values etc. will be taken from.

All tables available in the file selected in File path are listed in the leftmost dock widget. If the file does not have tables or the file type does not support them (e.g. CSV), all of the file’s data will be in a single table called ‘data’. The tables can be selected and deselected using the check boxes and only the selected ones will be imported. The option Select All is useful for selecting or deselecting all tables. If the Importer is opened in anonymous mode, there is also the option to add tables. The tables are imported in the order show on the list. The order can be changed by dragging and dropping the table names.
Tip
Multiple CSV files can be bundled into a datapackage which uses its own connector in Importer. Specifically, each CSV file in the datapackage shows up as a separate table in Source tables. See Packing CSV files into datapackage for more information on how to pack CSVs into a datapackage automatically within your workflow.
Next to the table dock widget, there is a small dock widget that allows to “format” the incoming data. The available options can differ depending on the selected connector. The above picture shows the available options for Excel files. Max rows specifies the amount of rows from the input data that are considered by the Importer. The option Has header converts the first row into headers. Skip rows and Skip columns skip the first N specified rows or columns from the table. If the table has empty rows or columns and some other data after that that you don’t want to use, Read until empty row/column on first column/row options can be used to “crop” the imported data to the first relevant block of information. Other possible options for different connector types include Encoding, Delimiter, Custom Delimiter, Quotechar and Maximum Depth. Load default mapping sets all of the selections in the spec editor to their default values. Be careful not to press this button unless you want to wipe the whole specification clean.
Note
If you are working on a specification and accidentally press the load default mapping button you can undo previous changes for the specification from the hamburger menu or by pressing Ctrl+Z. To redo actions, or press Crl+Y.
When a table is selected, it’s data and a preview of how the selected mapping will import the data will be presented under the options dock widget. An important aspect of data import is whether each item in the input data should be read as a string, a number, a time stamp or something else. By default all input data is read as strings. However, more often than not things like parameter values are actually numbers. Though types are usually casted automatically, it is possible to manually control what type of data each column (and sometimes each row) contains from the preview table. Clicking the data type indicator button on column or row headers pops up a menu with a selection of available data types. Right clicking the column/row header also gives the opportunity to change the data type of all columns/rows at once.

Under Mappings you can manage mappings by adding new ones, removing or duplicating existing ones and reordering by dragging and dropping. Each table has it’s own mappings and every mapping has its own options. In Mappings you can select the mapping that you want to start modifying. Having multiple mappings for a single table allows to for example import multiple item types at the same time from a single table in a file.
Underneath Mappings there are options that help the importer get a feel for what kind of data it will be importing. The available item type options are Entity class, Entity group, Alternative, Scenario, Scenario alternative and Parameter value list. The other available options are dependent on the Item type. Import entities allows to import entities alongside or entity groups. Parameter type is used to specify what type of parameters, if any, the sheet contains. It has options Value, Definition and None. If Value or Definition is selected the value or respectively the default value type can be set from the drop-down list. Use before alternative is only available for Scenario alternative -item type. Read data from row lets you specify the row where the importer starts to read the data. Ignore columns allow you to select individual columns that you want to exclude from the whole importing process. Number of dimensions sets the amount of dimensions the entity to be imported has. Repeat time series sets the repeat flag to true when importing time series. Map dimensions sets the number of map indexes when importing map values. Use before alternative maps scenario before alternatives when importing scenario alternatives. Compress Maps can be used to compress value maps.
Once everything in the before mentioned options is in order, the next step is to set the mapping specification. Below the options there is the part where the decisions are made on how the input data is interpreted: which row or column contains the entity class names, parameter values, time stamps and so on. The dock widget contains all of the targets that the selected mapping options specify. Each target has a Source reference and a Source type. Source type specifies if the data for the target is coming in the form of a column, row, table name etc. In the Source ref. section you can pinpoint to the exact row, column etc. to use as the data. The Filter section can be used to further specify which values to include using regular expressions. More on regular expressions in section Basic regular expressions for filtering.
It might be helpful to fill in the Source type and Source ref. using the preview table in the Sources data. Right clicking on the table cells shows a popup menu that lets one to configure where the selected row/column/header is mapped to. It can also be used to simultaneously map all headers to one target.

Anonymous mode
The importer specification editor can be opened in a mode where there is no input data available. This might be useful when creating or modifying a generalized specifications. Anonymous mode entered when opening the specification of an Importer without incoming files or when opening the spec editor from Toolbox Main Toolbar.

In anonymous mode new tables can be created by double clicking <rename this to add table> and writing in a name for the new table. The preview will show an infinite grid of cells on which you can create different mappings.
Note
You can exit the Anonymous mode by browsing to and selecting an existing file using the controls in File path.
Exporting data with Exporter
Exporter writes database data into regular files that can be used by Tools and external software that do not read the Spine database format. Various tabulated file formats are supported some of which require specific export settings; see below for more details.
At its heart Exporter maps database items such as entity class or entity names to an output table. Each item has a user given output position on the table, for example a column number. By default data is mapped to columns but it is also possible to create pivot tables.
Exporter also uses specifications so the same configurations
can be reused by other exporters even in other projects.
The specification can be edited in Exporter specification editor
which is accessible by the button in the item’s Properties dock
or by double clicking Exporter’s icon on the Design View.
A specification that is not associated with any specific Exporter project item can be created
and edited from the Main toolbar.
Properties dock
Exporter’s Properties dock controls project item specific settings that are not part of the item’s specification.

Specification used by the active Exporter item can be selected from the Specification combobox.
The button opens Exporter specification editor
where it is possible to edit the specification.
Data Stores that are connected to the exporter and are available for export are listed below
the Specification combobox. An output label is required for each database and one Exporter
can’t have the same output label for two different Data Stores at the same time. Two different
Exporters can have the same output label names since they are located in a different directories.
The default label for the output files is of the format <name of input Data Store>_exported@<name of Exporter>
.
Checking the Time stamp output directories box adds a time stamp to the item’s output directories preventing output files from being overwritten. This may be useful for debugging purposes.
The Cancel export on error checkbox controls whether execution bails out on errors that may be otherwise non-fatal.
Exporter’s data directory can be opened in system’s file browser by the button.
The output files are written in data directory’s
output
subdirectory.
Exporter specification editor
Specification editor is used to create mappings that define how data is exported to the output file. Mappings define one or more tables and their contents but are otherwise output format agnostic. Some output formats, e.g. SQL and gdx, interpret the tables in specific ways, however. Other formats which inherently cannot write multiple tables into a single file, such as CSV, may end up exporting multiple files. See the sections below for format specific intricacies.
When opened for the first time Specification editor looks like in the image below. The window is tabbed allowing multiple specifications to be edited at the same time. Each tab consists of dock widgets which can be reorganized to suit the user’s needs. The ‘hamburger’ menu on the top right corner gives access to some important actions such as Save and Close. Undo and redo can be found from the menu as well. There is also a Duplicate option which creates a new tab in the spec editor that is otherwise the same but has no name and is missing the database url under Preview controls. This is handy if you want to create a new Exporter specification using an existing template instead of always starting form the beginning.

The only requirement for a specification is a name. This can be given on the Name field field on the top bar. The Description field allows for an additional explanatory text. The current output format can be changed by the Format combobox on Export options dock.
Specification’s mappings are listed in the Mappings dock widget shown below. The Add button adds a new mapping while the Remove button removes selected mappings. Mappings can be renamed by double clicking their names on the list. The checkbox in front of mapping’s name shows if the mapping is currently enabled. Only enabled mappings are exported when the Exporter is executed. Use the Toggle enabled button to toggle the enabled state of all mappings at once.

The tables defined by the mappings are written in the order shown on the mapping list’s Write order column. This may be important if the tables need to be in certain order in the output file or when multiple mappings output to a single table. Mappings can be sorted by their write order by clicking the header of the Write order column. The Write earlier and Write later buttons move the currently selected mapping up and down the list.

A preview of what will be written to the output is available in the preview dock widgets. To enable it, check the Live preview checkbox. A database connection is needed to generate the preview. The Preview controls dock provides widgets to choose an existing database or to load one from a file. Once a database is available and the preview is enabled the mappings and the tables they would output are listed on the Preview tables dock. Selecting a table from the list shows the table’s contents on the Preview contents dock.
Note
The preview is oblivious of any filters possibly set up in the workflow. Therefore, it may show entries, e.g. parameter values, that would be filtered out during execution.
Mapping options
The currently selected mapping is edited using the controls in Mapping options and Mapping specification docks. The Mapping options dock contains controls that apply to the mapping as a whole, e.g. what data the output tables contain. It is important to choose Item type correctly since it determines what database items the mapping outputs and also dictates the mapping types that will be visible in the Mapping specification dock widget. It has options Entity class, Entity class with dimension parameter, Entity group, Alternative, Scenario, Scenario alternative and Parameter value list. The rest of the options besides Group function are item type specific and may not be available for all selections.

Checking the Always export header checkbox outputs a table that has fixed headers even if the table is otherwise empty. If Item type is Entity class, the Entity dimensions spinbox can be used to specify the maximum number of entity’s dimensions that the mapping is able to handle. Selected dimensions option is only available for the Entity class with dimension parameter item type and it is used to specify the entity dimension where the entity parameters are selected from. Parameters can be outputted by choosing their value type using the Parameter type combobox. The Value choice adds rows to Mapping specification for parameter values associated with individual entities while Default value allows outputting parameters’ default values. The maximum number of value dimensions in case of indexed values (time series, maps, time patterns, arrays) the mapping can handle is controlled by the Parameter dimensions spinbox. The Fixed table name checkbox enables giving a user defined table name to the mapping’s output table. In case the mapping is pivoted and Mapping specification contains items that are hidden, it is possible that a number of data elements end up in the same output table cell. The Group function combobox offers some basic functions to aggregate such data into the cells.
Mapping specification

Mapping specification contains a table which defines the structure of the mapping’s output tables. Like mentioned before, the contents of the table depends on choices on Mapping options, e.g. the item type, parameter type or dimensions. Each row corresponds to an item in the database: entity class names, entity names, parameter values etc. The item’s name is given in the Mapping type column. The colors help to identify the corresponding elements in the preview.
The Map to column defines the position of the item, that is, where the item is written or otherwise used when the output tables are generated. By default, a plain integral number in this column means that the item is written to that column in the output table. From the other choices, hidden means that the item will not show on the output. Table name, on the other hand, uses the item as output table names. For example, outputting entity classes as table names will generate one new table for every entity class in the database, each named after the class. Each table in turn will contain the parameters and entities of the table’s entity class. If multiple mappings generate a table with a common name then each mapping appends to the same table in the order specified by the Write order column on Mappings dock.
The column header position makes the item a column header for a buddy item. Buddy items have some kind of logical relationship with their column header, for instance the buddy of an entity class is its entities; setting the entity class to column header will write the name of the class as the entity’s column header.
Note
Currently, buddies are fixed and defined only for a small set database items. Therefore, column header will not always produce sensible results.
Changing the column and pivot header row positions leaves sometimes gaps in the output table. If such gaps are not desirable the Compact button reorders the positions by removing the gaps. This may be useful when the output format requires such gapless tables.
The checkboxes in Pivoted column on the Mapping specification dock toggle the mapping into pivoted mode. One or more items on the table can be set as pivoted. They then act as a pivot header for the data item which is the last non-hidden item on the list. Once checked as pivoted, an item’s position column defines a pivot header row instead of output column.
By default a row ends up in the output table only when all mapping items yield some data. For example, when exporting entity classes and entities, only classes that have entities get written to output. However, sometimes it is useful to export ‘empty’ entity classes as well. For this purpose a mapping can be set as nullable in the Nullable column. Continuing the example, checking the Nullable checkbox for Entities would produce an output table with all entity classes including ones without entities. The position where entities would normally be outputted are left empty for those classes.
Besides the column header position it is possible to give fixed column headers to items using the Header column in Mapping specification dock. Note that checking the Always export header option in the Mapping options dock outputs the fixed headers even if there is no other data in a table.
The Mapping specification dock’s Filter column provides refined control on which database items the mapping outputs. The column uses regular expressions (see section Basic regular expressions for filtering) to filter what gets outputted.
CSV and multiple tables
CSV files are flat text files and therefore do not directly support multiple tables. Instead, multiple tables are handled as separate output files.
Only mappings that output an anonymous table
actually write to the file/label specified on the Exporter’s properties dock.
Named tables get written to files named after the table plus the .csv
extension.
For example, a table named node
would result in a file called node.csv
.
SQL export
To set up export to a remote database, first an Exporter specification with SQL selected as the format needs to be saved. The Exporter needs to also be connected to some input Data Store. From the Exporters Properties dock widget an output database can be specified for each input Data Store respectively by clicking the Set URL… button. A small new window opens with a few settings to set up the output database. Currently only mysql and sqlite are supported, even though mssql, postgresql and oracle are also listed as options for the dialect. Once a URL is set it can be removed by pressing the Clear URL button on the Properties tab.

The SQL backend writes the tables to the target database in a relatively straightforward way:
Tables are named after the table name provided by the mappings. Anonymous tables are not supported.
The first row of each table is used as column names in the database. Thus, each column in a mapping should have a fixed header or a header produced by an item set to column header position.
Column data types are sniffed from the second row. Empty values or a missing row result in string type.
There must be an item assigned to each column. Empty columns confuse the SQL backend.
Pivot tables do not generally make sense with the SQL backend unless the resulting table somehow follows the above rules.
GAMS gdx export
Note
You need to have GAMS installed to use this functionality. However, you do not need to own a GAMS license as the demo version works just as well. See Setting up Consoles and External Tools for more information.
The gdx backend turns the output tables to GAMS sets, parameters and scalars following the rules below:
Table names correspond the names of sets, parameters and scalars. Thus, anonymous tables are not supported.
There must be an item assigned to each column. Empty columns confuse the gdx backend.
Pivot tables do not generally make sense with the gdx backend unless the resulting table somehow follows the rules listed here.
Sets:
Everything that is not identified as parameter or scalar is considered a GAMS set.
Each column corresponds to a dimension.
The first row is used to name the dimension’s domain. Thus, each column in a mapping should have a fixed header or a header produced by an item set to column header position. Note that
*
is a valid fixed header and means that the dimension has no specific domain.
Parameters:
A table that contains no header in the last (rightmost) column is considered a GAMS parameter.
The last column should contain the parameter’s values while the other columns contain the values’ dimension.
Dimensions’ domains are taken from the header row, see Sets above. Note, that the value column must not have a header.
Scalars:
A table that contains a numerical value in the top left cell is considered a GAMS scalar. Everything else (except the table name) is ignored.
The data in the top left cell is the scalar’s value.
Basic regular expressions for filtering
See regular expressions on wikipedia and on Python’s documentation. Both the Exporter and Importer have applications for regular expressions in their respective Mapping specifications dock widgets. Below are examples on how to create some basic filters for these applications.
- Single item
Writing the item’s name to the field filters out all other items. For example, to output the entity class called ‘node’ only, write
node
to the Filter field.- OR operator
The vertical bar
|
serves as the OR operator.node|unit
as a filter for entity classes would output classes named ‘node’ and ‘unit’.- Excluding an item
While perhaps not the most suitable task for regular expressions it is still possible to ‘negate’ a filter. As an example,
^(?!node)
excludes all item names that start with ‘node’.
Spine Engine Server
Notes
Here is a list of items that you should be aware of when running projects on Spine Engine Server.
Projects must be self-contained. The project directory must contain all input and output files, file/db references, Specification files and scripts.
Work or Source directory execution mode setting is ignored. Tools are always executed in ‘source’ directory, i.e. in the directory where the Tool Spec main script resides.
Python Basic Console. Interpreter setting in Tool Specification Editor is ignored. Basic Console runs the same Python that was used in starting the Server.
Python Jupyter Console. Kernel spec setting in Tool Specification Editor is ignored. Jupyter Console is launched using the python3 kernel spec. This must be installed before the server is started. See instructions below.
Julia Basic Console. Julia executable setting in Tool Specification Editor is ignored. Basic Console runs the Julia that is found in the server machine’s PATH. See installation instructions below.
Julia Jupyter Console. Kernel spec setting in Tool Specification Editor is ignored. Jupyter Console is launched using the julia-1.8 kernel spec. This must be installed before the server is started. See instructions below.
Setting up Spine Engine Server
You can either install the entire Spine Toolbox or just the required parts to run the Spine Engine Server.
Minimal Installation
Spine Engine server does not need the entire Spine Toolbox installation. Only spine-engine, spinedb-api and spine-items. Note that the dependencies of spine-items are not needed. Here are the step-by-step instructions for a minimal installation:
1.1 Make a miniconda environment & activate it
1.2. Clone spine-engine
1.3. cd to spine-engine repo root, run:
pip install -e .
1.4. Clone spine-items
1.5. cd to spine-items repo root
1.6. Install spine-items without dependencies by running:
pip install --no-deps -e .
Full Installation
Install Spine Toolbox regularly
1.1. Make a miniconda environment & activate
1.2. Clone Spine Toolbox
1.3. Follow the installation instructions in README.md
Finalize Setting Up and Start Server
Create security credentials (optional)
cd to <spine_engine_repo_root>/spine_engine/server/
Create security certificates by running:
python certificate_creator.py
The certificates are created into <spine_engine_repo_root>/spine_engine/server/certs/ directory.
Configure allowed endpoints by creating file <spine_engine_repo_root>/spine_engine/server/connectivity/certs/allowEndpoints.txt
Add IP addresses of the remote end points to the file
Install IPython kernel spec (python3) to enable Jupyter Console execution of Python Tools
Run:
python -m pip install ipykernel
Install Julia 1.8
Download from https://julialang.org/downloads/ or run apt-get install julia on Ubuntu
Install IJulia kernel spec (julia-1.8) to enable Jupyter Console execution of Julia tools
Open Julia REPL and press ] to enter pkg mode. Run:
add IJulia
This installs julia-1.8 kernel spec to ~/.local/share/jupyter/kernels on Ubuntu or to %APPDATA%jupyterkernels on Windows
Start Spine Engine Server
cd to <spine_engine_repo_root>/spine_engine/server/
Without security, run:
python start_server.py 50001
where 50001 is the server port number.
With Stonehouse security, run:
python start_server.py 50001 StoneHouse ./certs
where 50001 is an example server port number, StoneHouse is the security model, and the path is the folder containing the security credentials.
Note
Valid port range is 49152-65535.
Setting up Spine Toolbox (client)
(Optional) If server is started using StoneHouse security, copy security credentials from the server to some directory. Server’s secret key does not need to be copied.
Start Spine Toolbox and open a project
Open the Engine page in Spine Toolbox Settings (File -> Settings…)
Enable remote execution from the checkbox (Enabled)
Set up the Spine Engine Server settings (host, port, security model, and security folder). Host is 127.0.0.1 when the Server runs on the same computer as the client
Click Ok, to close and save the new Settings
Terminology
Here is a list of definitions related to Spine project, SpineOpt.jl, and Spine Toolbox.
Arc Graph theory term. See Connection.
Case study Spine project has 13 case studies that help to improve, validate and deploy different aspects of the SpineOpt.jl and Spine Toolbox.
Connection (aka Arrow) an arrow on Spine Toolbox Design View that is used to connect project items to each other to form a DAG.
Data Connection is a project item used to store a collection of data files that may or may not be in Spine data format. It facilitates data transfer from original data sources e.g. spreadsheet files to Spine Toolbox. The original data source file does not need to conform to the format that Spine Toolbox is capable of reading, since there we can use an interpreting layer (Importer) between the raw data and the Spine format database (Data Store).
Data Package is a data container format consisting of a metadata descriptor file (
datapackage.json
) and resources such as data files.Data sources are all the original, unaltered, sources of data that are used to generate necessary input data for Spine Toolbox tools.
Data Store is a project item. It’s a Spine Toolbox internal data container which follows the Spine data model. A data store is implemented using a database, it may be, for example, an SQL database.
Design View A sub-window on Spine Toolbox main window, where project items and connections are visualized.
Direct predecessor Immediate predecessor. E.g. in DAG x->y->z, direct predecessor of node z is node y. See also predecessor.
Direct successor Immediate successor. E.g. in DAG x->y->z, direct successor of node x is node y. See also successor.
Directed Acyclic Graph (DAG) Finite directed graph with no directed cycles. It consists of vertices and edges. In Spine Toolbox, we use project items as vertices and connections as edges to build a DAG that represents a data processing chain (workflow).
Edge Graph theory term. See Connection
Element is what the entities making up a multi dimensional entity are called. See also multidimensional entity.
Importer is a project item that can be used to import data from e.g. an Excel file, transform it to Spine data structure, and into a Data Store.
Loop (aka jump) is a special sort of connection which only connects the two attached project items if the user defined loop condition is met.
Multidimensional entity/entity class (aka N-D entity/class) An entity/entity class that consists of multiple other entities that are as it’s members. Acts just like any other entity/entity class.
Node Graph theory term. See Project item.
Predecessor Graph theory term that is also used in Spine Toolbox. Preceding project items of a certain project item in a DAG. For example, in DAG x->y->z, nodes x and y are the predecessors of node z.
Project in Spine Toolbox consists of project items and connections, which are used to build a data processing chain for solving a particular problem. Data processing chains are built and executed using the rules of Directed Acyclic Graphs. There can be any number of project items in a project.
Project item Spine Toolbox projects consist of project items. Project items together with connections are used to build Directed Acyclic Graphs (DAG). Project items act as nodes and connections act as edges in the DAG. See Project Items for an up-to-date list on project items available in Spine Toolbox.
Scenario A scenario is a meaningful data set for the target tool.
Spine data structure Spine data structure defines the format for storing and moving data within Spine Toolbox. A generic data structure allows representation of many different modelling entities. Data structures have a class defining the type of entity they represent, can have properties and can be related to other data structures. Spine data structures can be manipulated and visualized within Spine Toolbox while SpineOpt.jl will be able to directly utilize as well as output them.
SpineOpt.jl An interpreter, which formulates a solver-ready mixed-integer optimization problem based on the input data and the equations defined in the SpineOpt.jl. Outputs the solver results.
Source directory In context of Tool specifications, a source directory is the directory where the main program file of the Tool specification is located. This is also the recommended place for saving the Tool specification file (.json).
Successor Graph theory term that is also used in Spine Toolbox. Following project items of a certain project item in a DAG. For example, in DAG x->y->z, nodes y and z are the successors of node x.
Tool is a project item that is used to execute Python, Julia, GAMS, executable scripts, or simulation models. This is done by creating a Tool specification defining the script or program the user wants to execute in Spine Toolbox. Then you need to attach the Tool specification to a Tool project item. Tools can be used to execute a computational process or a simulation model, or it can also be a process that converts data or calculates a new variable. In general, Tools may take some data as input and produce an output.
Tool specification is a JSON structure that contains metadata required by Spine Toolbox to execute a computational process or a simulation model. The metadata contains; type of the program (Python, Julia, GAMS, executable), main program file (which can be e.g. a Windows batch (.bat) file or for Python scripts this would be the .py file where the __main__() method is located), All additional required program files, any optional input files (e.g. data), and output files. Also any command line arguments can be defined in a Tool specification. SpineOpt.jl is a Tool specification from Spine Toolbox’s point-of-view.
Use case Potential way to use Spine Toolbox. Use cases together are used to test the functionality and stability of Spine Toolbox and SpineOpt.jl under different potential circumstances.
Vertex Graph theory term. See Project item.
View A project item that can be used for visualizing project data.
Work directory Tool specifications can be executed in Source directory or in work directory. When a Tool specification is executed in a work directory, Spine Toolbox creates a new work directory, copies all required and optional files needed for running the Tool specification to this directory and executes it there. After execution has finished, output or result files can be copied into a timestamped (archive) directory from the work directory.
Contribution Guide
All are welcome to contribute! This guide is based on a set of best practices for open source projects [JF18].
Reporting Bugs
Due Diligence
Before submitting a bug report, please do the following:
Perform basic troubleshooting steps.
Make sure you’re on the latest version. If you’re not on the most recent version, your problem may have been solved already! Upgrading is always the best first step.
Try older versions. If you’re already on the latest release, try rolling back a few minor versions (e.g. if on 1.7, try 1.5 or 1.6) and see if the problem goes away. This will help the devs narrow down when the problem first arose in the commit log.
Try switching up dependency versions. If you think the problem may be due to a problem with a dependency (other libraries, etc.). Try upgrading/downgrading those as well.
Search the project’s bug/issue tracker to make sure it’s not a known issue. If you don’t find a pre-existing issue, consider checking with the maintainers in case the problem is non-bug-related. Spine Toolbox issue tracker is here.
What to Put in Your Bug Report
Make sure your report gets the attention it deserves: bug reports with missing information may be ignored or punted back to you, delaying a fix. The below constitutes a bare minimum; more info is almost always better:
What version of the Python interpreter are you using? E.g. Python 2.7.3, Python 3.6?
What operating system are you on? Windows? (Vista, 7, 8, 8.1, 10). 32-bit or 64-bit? Mac OS X? (e.g. 10.7.4, 10.9.0) Linux (Which distro? Which version of that distro? 32 or 64 bits?) Again, more detail is better.
Which version or versions of the software are you using? If you have forked the project from Git, which branch and which commit? Otherwise, supply the application version number (Help->About menu). Also, ideally you followed the advice above and have ruled out (or verified that the problem exists in) a few different versions.
How can the developers recreate the bug? What were the steps used to invoke it. A screenshot demonstrating the bug is usually the most helpful thing you can report (if applicable) Relevant output from the Event Log or debug messages from the console of your run, should also be included.
Feature Requests
The developers of Spine Toolbox are happy to hear new ideas for features or improvements to existing functionality. The format for requesting new features is free. Just fill out the required fields on the issue tracker and give a description of the new feature. A picture accompanying the description is a good way to get your idea into development faster. But before you make a new issue, check that there isn’t a related idea already open in the issue tracker. If you have an idea on how to improve an existing idea, just join the conversation.
Submitting features/bugfixes
If you feel like you can fix a bug that’s been bothering you or you want to add a new feature to the application but the devs seem to be too busy with something else, please follow the instructions in the following sections on how to contribute code.
Coding Style
Follow the style you see used in the repository! Consistency with the rest of the project always trumps other considerations. It doesn’t matter if you have your own style or if the rest of the code breaks with the greater community - just follow along.
Spine Toolbox coding style follows PEP-8 style guide for Python code with the following variations:
Maximum line length is 120 characters. Longer lines are acceptable for a good reason.
Google style docstrings with the title and input parameters are required for all classes, functions, and methods. For small functions or methods only the summary is necessary. Return types are highly recommended but not required if it is obvious what the function or method returns.
Use double-quoted strings instead of single-quoted strings (e.g.
"hello"
).Other deviations from PEP-8 can be discussed.
Commit messages
The commit message should tell what was changed and why. Details on how it was done can usually be left out, if the code itself is self-explanatory (remember source comments too!). Separate the subject line from the body with a blank line. The subject line (max. 50 chars) should explain in condensed form what happened using imperative mood, i.e. using verbs like ‘change’, ‘fix’ or ‘add’. Start the subject line with a capital letter. Do not use the issue number on the subject line, as it does not tell much to a person who’s not aware of that particular issue. For more info see Chris Beams’ ‘Seven rules of of a great Git commit message’ [CB14].
A good example (inspired by [CB14])
Fix bugs when updating parameters in foo and bar
Body of the commit message starts after a blank line. Explain here in more
detail the reasons why you made the change, how things worked before and how they work now.
Also explain why
You can use hyphens to make bulleted lists:
- Foo was added because of bar
- Baz was not used so it was deleted
Add references to issue tracker (if any) at the end.
Solves: #123
See also: #456, #789
Contributing to the User Guide
Spine Toolbox uses Sphinx to create HTML pages from restructured text (.rst) files. The .rst files are
plain text files that are formatted in a way that Sphinx understands and is able to turn them into HTML.
Please see this brief introduction for more on reStructured text.
You can modify the existing or create new .rst files into docs/source
directory. When you are done editing, run
bin/build_doc.bat
on Windows or bin/build_doc.py
on other systems to build the HTML pages to check the result
before making a commit. The created pages are found in docs/build/html
directory. After a commit, the User Guide is
built automatically by readthedocs.org. The latest User Guide is available in
https://spine-toolbox.readthedocs.io/en/latest/.
Contributing to the Spine Toolbox Graphical User Interface
If you want to change or add new widgets into the application, you need to use the bin\build_ui.bat
(Windows) or
bin/build_ui.py
(other systems) scripts. The main design of the widgets should be done with Qt Designer
(designer.exe
or designer
) that is included with PySide2. The files produced by Qt Designer are XML files (.ui).
You can also embed graphics (e.g. icons, logos, etc.) into the application by using Qt Designer. When you are done
modifying widgets in the designer, you need to run the build_ui
script for the changes to take effect.
This script uses tools provided in the PySide2 package to turn .ui files into Python files, in essence
rebuilding the whole Spine Toolbox user interface.
Styling the widgets should be done with Qt Style Sheets in code. Please avoid using style sheets in Qt Designer.
Version Control Branching
Always make a new branch for your work, no matter how small. This makes it easy for others to take just that one set of changes from your repository, in case you have multiple unrelated changes floating around. A corollary: don’t submit unrelated changes in the same branch/pull request! The maintainer shouldn’t have to reject your awesome bugfix because the feature you put in with it needs more review.
Name your new branch descriptively, e.g. issue#XXX-fixing-a-serious-bug
or issue#ZZZ-cool-new-feature
.
New branches should in general be based on the latest master
branch.
In case you want to include a new feature still in development, you can also start working from its branch.
The developers will backport any relevant bug-fixes to previous or upcoming releases under preparation.
If you need to use code from an upstream branch, please use
git-rebase if you have not shared your work with
others yet. For example: You started working on an issue, but now the upstream branch (master
) has some
new commits you would like to have in your branch too. If you have not yet pushed your branch, you can now
rebase your changes on top of the upstream branch:
$ git pull origin master:master
$ git checkout my_branch
$ git rebase master
Avoid merging the upstream branch to your issue branch if it’s not necessary. This will lead to a more linear and cleaner history.
Finally, make a pull request from your branch so that the developers can review your changes. You might be asked to make additional changes or clarifications or add tests to prove the new feature works as intended.
Test-driven development is your friend
Any bug fix that does not include a test proving the existence of the bug being fixed, may be suspect. Ditto for new features that can’t prove they actually work.
It is recommended to use test-first development as it really helps make features better designed and identifies potential edge cases earlier instead of later. Writing tests before the implementation is strongly encouraged.
See Unit Testing Guidelines for more information.
Full example
Here’s an example workflow. Your username is yourname
and you’re submitting a basic bugfix.
Preparing your Fork
Click ‘Fork’ on Github, creating e.g.
yourname/Spine-Toolbox
Clone your project:
git clone git@github.com:yourname/Spine-Toolbox
cd Spine-Toolbox
Create a virtual environment and install requirements
Create a branch:
git checkout -b foo-the-bars master
Making your Changes
Add an entry to
CHANGELOG.md
.Write tests expecting the correct/fixed functionality; make sure they fail.
Hack, hack, hack.
Run tests again, making sure they pass.
Commit your changes:
git commit -m "Foo the bars"
Creating Pull Requests
Push your commit to get it back up to your fork:
git push origin HEAD
Visit Github, click handy ‘Pull request‘ button that it will make upon noticing your new branch.
In the description field, write down issue number (if submitting code fixing an existing issue) or describe the issue + your fix (if submitting a wholly new bugfix).
Hit ‘submit’! And please be patient - the maintainers will get to you when they can.
References
- CB14(1,2)
Chris Beams. 2014. ‘How to Write a Git Commit Message.’ https://chris.beams.io/posts/git-commit/
- JF18
Jeff Forcier. 2018. ‘Contributing to Open Source Projects.’ https://contribution-guide-org.readthedocs.io/
Developer Documentation
Here you can find developer specific documentation on Spine Toolbox.
UI Guidelines
Keyboard shortcuts
Qt has a list of ‘standard’ keyboard shortcuts which can be used for inspiration.
F2: edit current value in-place
Alt+F2: open separate editor (e.g. Parameter value editor)
F3: search
Alt+F4: quit, close without saving changes
Esc: close, exit without saving changes
Ctrl+Enter: accept dialog
Action names
Edit… should open an external editor, e.g. Parameter value editor in Database editor.
Unit Testing Guidelines
Test modules, directories
Spine project uses Python standard unittest framework for testing.
The tests are organized into Python modules starting with the prefix test_
under <project root>/tests/
.
The structure of tests/
mirrors that of the package being tested.
Note that all subdirectories containing test modules under tests/
must have an (empty) __init__.py
which makes them part of the project’s test package.
While there are no strict rules on how to name the individual test modules except for the test_
prefix,
test_<module_name>.py
is preferred.
Running the tests
Tests are run as a GitHub action whenever a branch is pushed to GitHub.
This process is configured by <project root>/.github/workflows/unittest_runner.yml
To execute the tests manually, run python -munittest discover
in project’s root.
Helpers
mock_helpers
module in Toolbox’s test package contains some helpful functions.
Especially the methods to create mock ToolboxUI
and SpineToolboxProject
objects come very handy.
When instantiation of QWidget
(this includes all GUI testing) is needed,
Qt’s main loop must be running during testing.
This can be achieved by e.g. the setUpClass
method below:
@classmethod
def setUpClass(cls):
if not QApplication.instance():
QApplication()
Sometimes an in-memory database can be handy because it does not require a temporary files or directories
and it may be faster than an .sqlite
file.
To create an in-memory database, use sqlite://
as the URL:
db_map = DiffDatabaseMapping("sqlite://", create=True)
Unfortunately, it is not possible to refer to the created database with the same URL prohibiting multiple database maps the access to the same in-memory database.
Execution Tests
Toolbox contains execution tests that test entire workflows in the headless mode.
The tests can be found in <toolbox repository root>/execution_tests/
.
Execution tests are otherwise normal Toolbox projects
except that the project root directories contain __init__.py
and execution_test.py
files.
__init__.py
makes the directory part of the execution test suite
while execution_test.py
contains actual test code.
The tests utilize Python’s unittest
package
so the test code is practically identical to any unit tests in Toolbox.
Executing the tests
Tests are run as a GitHub action whenever a branch is pushed to GitHub.
This process is configured by <project root>/.github/workflows/executiontest_runner.yml
To execute the tests manually, run python -munittest discover --pattern execution_test.py
in project’s root.
Project Item Development
This document discusses the basics of project item development: what is required make one, how items interact with the Toolbox GUI and how they are executed.
The core of every project item consists of two classes: a static project item class which is responsible for integrating the item with the Toolbox GUI and an executable class which does the item’s ‘thing’ and exists only during execution in Spine Engine. Some additional classes are needed for Toolbox to be able to instantiate project items and to communicate with the user via the Toolbox GUI.
Specifications are a way to make the settings of an item portable across projects. In a sense a specification is a template that can specialize an item for a specific purpose such as a Tool that runs certain model with known inputs an outputs. Items that support specifications need to implement some additional methods and classes.
Getting started
Probably the most convenient way to start developing a new project item is to work with a copy of some simple project item. For example, View provides a good starting point.
Project items are mostly self-contained Python packages.
It is customary to structure the project item packages like the Toolbox itself: mvcmodels
submodule for Qt’s
models, ui
module for automatically generated UI forms and widgets
for widgets’ business logic.
However, the only actual requirement is that Toolbox expects to find the item’s factory and item info
classes in the package’s root modules as well as an executable_item
module.
Item info
A subclass of spine_engine.project_item.project_item_info.ProjectItemInfo
must be found
in one of the root modules of an item’s package.
It is used by Toolbox to query the type and category of an item.
Type identifies the project item while category is used by the Toolbox GUI to group project items with similar function.
Categories are currently fixed and can be checked from spine_items.category
.
Item Factory
The details of constructing a project item and related objects have been abstracted away from Toolbox
by a factory that must be provided by every project item in a root module of the item’s package.
The factory is a subclass of spinetoolbox.project_item.project_item_factory.ProjectItemFactory
.
Note that methods in the factory
that deal with specifications need to be implemented only by items that support them.
Executable item
A project item must have a root module called executable_item
that contains a class
named ExecutableItem
which is a subclass of
spine_engine.project_item.executable_item_base.ExecutableItemBase
ExecutableItem
acts as an access point to Spine Engine and contains the item’s execution logic.
Toolbox side project item
A project item must subclass spinetoolbox.project_item.project_item.ProjectItem
and return the subclass in its factory’s item_class()
method.
Also make_item()
must return an instance of this class.
This class forms the core of integrating the item with Toolbox.
Specifications
Items that support specifications need to subclass
spine_engine.project_item.project_item_specification_factory.ProjectItemSpecificationFactory
which provides an access point to Toolbox and Spine Engine to generate specifications.
The factory must be called SpecificationFactory
and be placed in specification_factory
module under item package’s root.
The specification itself should be a subclass of
spine_engine.project_item.project_item_specification.ProjectItemSpecification
.
Toolbox GUI integration
ProjectItemFactory.icon()
returns a URL to the item’s icon resource.
This is the item’s ‘symbol’ shown e.g. on the main toolbar of Toolbox.
It should not be confused with the actual icon on Design view
which in turn is a subclass of spinetoolbox.project_item.project_item_icon.ProjectItemIcon
and is returned by ProjectItemFactory.make_icon()
.
When creating a new item on the Design view Toolbox shows the Add item dialog it gets from
ProjectItemFactory.make_add_item_widget()
.
Toolbox provides spinetoolbox.widgets.add_project_item_widget.AddProjectItemWidget
which is a general purpose widget for this purpose
though project items are free to implement their own widgets as needed.
Once the item is on the Design view, the main interaction with it goes through the properties widget which is created
by ProjectItemFactory.make_properties_widget()
.
The properties widget should have all controls needed to set up the item.
Saving and restoring project items
Project items are saved in JSON format as part of the project.json
file.
Item saving is handled by ProjectItem.item_dict()
which should return a JSON compatible dict
and
contain at least the information returned by the base class method.
File system paths are handled specifically during saving: all paths outside the project directory should be absolute
while the paths in the project directory should be relative. This is to enable self-contained projects which include
all needed files and can be easily transferred from system to system. As such, paths are saved as special dictionaries.
spine_engine.utils.serialization.serialize_path()
, spine_engine.utils.serialization.serialize_url()
and
spine_engine.utils.serialization.deserialize_path()
help with dealing with the paths.
ProjectItem.from_dict()
is responsible for restoring a saved project item
from the dictionary. ProjectItem.parse_item_dict()
can help to deserialize
the basic data needed by the base class.
Passing data between items: resources
Project items share data by files or via databases. One item writes a file which is then read by another item. Project item resources are used to communicate the URLs of these files and databases.
Resources are instances of the spine.engine.project_item.project_item_resource.ProjectItemResource
class.
Both static items and their executable counterparts pass resources. The major difference is that static item’s may pass resource promises such as files that are generated during the execution. The full path to the promised files or even their final names may not be known until the items are executed.
During execution resources are propagated only to item’s direct predecessors and successors. Static items offer their resources to direct successors only. Resources that are communicated to successor items are basically output files that the successor items can use for input. Currently, the only resource that is propagated to predecessor items is database URLs by Data Store project items. As Data Stores leave the responsibility of writing to the database to other items it has to tell these items where to write their output data.
The table below lists the resources each project item type provides during execution.
Item |
Notes |
Provides to predecessor |
Provides to successor |
---|---|---|---|
Data Connection |
n/a |
File URLs |
|
Data Store |
Database URL |
Database URL |
|
Data Transformer |
n/a |
Database URL |
|
Exporter |
n/a |
File URLs |
|
Importer |
n/a |
n/a |
|
Merger |
n/a |
n/a |
|
Tool |
n/a |
File URLs |
|
View |
n/a |
n/a |
- 1
Data connection provides paths to local files.
- 2
Data Store provides a database URL to direct successors and predecessors. Note, that this is the only project item that provides resources to it’s predecessors.
- 3
Data Transformer provides its predecessors’ database URLs modified by transformation configuration embedded in the URL.
- 4
Tool’s output files are specified by a Tool specification.
The table below lists the resources that might be used by each item type during execution.
Item |
Notes |
Accepts from predecessor |
Accepts from successor |
---|---|---|---|
Data Connection |
n/a |
n/a |
|
Data Store |
n/a |
n/a |
|
Data Transformer |
Database URL |
n/a |
|
Exporter |
Database URL |
n/a |
|
Importer |
File URLs |
Database URL |
|
Merger |
Database URL |
Database URL |
|
Tool |
File URLs, database URLs |
Database URLs |
|
View |
Database URLs |
n/a |
- 5
Importer requires a database URL from its successor for writing the mapped data. This can be provided by a Data Store.
- 6
Tool specification specifies tool’s optional and required input files. Database URLs can be passed to the tool program via command line arguments but are otherwise ignored by the Tool project item. Currently, there is no mechanism to know if a URL is actually required by a tool program. For more information, see Tool Specification Editor.
Execution
Spine Engine instantiates the executable items in a DAG before the execution starts.
Then, Engine declares forward and backward resources for each item
using ExecutableItemBase.output_resources()
.
During execution, ExecutableItemBase.execute()
is invoked with lists of available resources
if an item is selected for execution.
Otherwise, ExecutableItemBase.exclude_execution()
is called.
Publishing to PyPI
This document describes the prerequisites and workflow to publish Spine Toolbox to The Python Package Index (PyPI).
Versioning of Spine Toolbox packages
Spine Toolbox packages use the latest Git tag to dynamically generate
the version number. During the build process Git tags of the form
X.Y.Z
are sorted and the latest is used to generate the package
version. If the tip of the current branch (HEAD
) is at a tag, the
version number is the tag. However, if there have been commits since
the latest tag, the next version is guessed and a dev??-*
component is included (e.g. '0.7.0.dev77+gf9538fee.d20230816'
).
Note that the dev*
component also includes an indication of the
number of commits since the last tag.
Under this scheme, the release process is simply to create a new Git
tag, and publish it. However since the different Spine packages
depend on each other, you need to update the different version number
requirements in their respective pyproject.toml
files. This can
be done conveniently by using the CLI tools available in the
spine-conductor repo.
Creating Git tags and publishing to PyPI
Check out the spine-conductor repo, and install it, either in a virtual environment or using
pipx
.You can create a TOML configuration file as mentioned in the README of the repo; say
release.toml
. Something like the sample below should work.release.toml[tool.conductor] packagename_regex = "spine(toolbox|(db){0,1}[_-][a-z]+)" # package name on PyPI [tool.conductor.dependency_graph] spinetoolbox = ["spine_items", "spine_engine", "spinedb_api"] spine_items = ["spinetoolbox", "spine_engine", "spinedb_api"] spine_engine = ["spinedb_api"] spinedb_api = [] [tool.conductor.repos] spinetoolbox = "." spine_items = "venv/src/spine-items" spine_engine = "venv/src/spine-engine" spinedb_api = "venv/src/spinedb-api" # # default # [tool.conductor.branches] # spinetoolbox = "master" # spine_items = "master" # spine_engine = "master" # spinedb_api = "master"
Now you can create a release by calling the
conduct release -c release.toml
command with the TOML file as config. This starts a guided session where the spine-conductor CLI tool deduces the next version numbers from existing Git tags, updates the correspondingpyproject.toml
files in all the repos to reflect the new package versions, and finally prompts you to add any edited files, and create the new Git tag. A typical session would like this:A typical release session; note the JSON summary in the end.$ cd /path/to/repo/Spine-Toolbox $ conduct release --bump patch -c release.toml # or include in pyproject.toml Repository: /path/to/repo/Spine-Toolbox ## master...origin/master M pyproject.toml (1) Select the files to add (comma/space separated list): 1 Creating tag: 0.6.19 @ 034fb4b Repository: /path/to/repo/venv/src/spine-items ## master...origin/master M pyproject.toml (1) Select the files to add (comma/space separated list): 1 Creating tag: 0.20.1 @ 5848e25 Repository: /path/to/repo/venv/src/spine-engine ## master...origin/master M pyproject.toml (1) Select the files to add (comma/space separated list): 1 Creating tag: 0.22.1 @ e312db2 Repository: /path/to/repo/venv/src/spinedb-api ## master...origin/master Select the files to add (comma/space separated list): Creating tag: 0.29.1 @ d9ed86e Package Tags summary 💾 ➡ 'pkgtags.json': { "Spine-Toolbox": "0.6.19", "spine-items": "0.20.1", "spine-engine": "0.22.1", "Spine-Database-API": "0.29.1" }
If the session completes successfully, you will see a session summary with the newest Git tags that were created for each package.
Push the newly created tags to GitHub. On sh-like shells like: bash, zsh, or git-bash (Windows):
for repo in . venv/src/{spinedb-api,spine-{items,engine}}; do pushd $repo; git push origin master --tags; popd done
With Powershell on Windows, something like this should work:
"." , "venv/src/spinedb-api", "venv/src/spine-items", "venv/src/spine-engine" | % { pushd $_; git push origin master --tags; popd; }
Now you can trigger the workflow to publish the packages to PyPI either by using GitHub CLI, or from the workflow dispatch menu in the spine-conductor repo.
cat pkgtags.json | gh workflow run --repo spine-tools/spine-conductor test-n-publish.yml --json
If you are using the workflow dispatch menu, make sure you input the exact same package versions as shown in the summary.
Done! Note: Soon, (4) & (5) will be wrapped in a separate command
provided by spine-conductor
.
The release.toml
file
The config file is a standard TOML file conformant with
pyproject.toml
, meaning all configuration goes under the section
tool.conductor
. The configuration is split into 4 sections: a
regex to identify our packages, dependency graph between our packages,
path to the repos to be used for the release, and the branches to be
used (optional).
You can specify a regular expression that will be used to identify “our” packages. Something like the following should work:
Spine package name regular expression[tool.conductor] packagename_regex = "spine(toolbox|(db){0,1}[_-][a-z]+)" # package name on PyPI
Note that PyPI treats
-
(hyphen) and_
(underscore) as equivalent in package names; i.e.spinedb_api
andspinedb-api
are equivalent, the regex should accomodate that.The dependency graph between our packages should be specified under the
dependency_graph
section:Spine package dependency graph[tool.conductor.dependency_graph] spinetoolbox = ["spine_items", "spine_engine", "spinedb_api"] spine_items = ["spinetoolbox", "spine_engine", "spinedb_api"] spine_engine = ["spinedb_api"] spinedb_api = []
Essentially it is a mapping of the “primary” package, and a list of its Spine dependencies.
Point to the repository directories relative to your current working directory. The following example would be valid if you are preparing the release from the Toolbox repo, and the other Spine package repos are in the virtual environment.
Repository paths[tool.conductor.repos] spinetoolbox = "." spine_items = "venv/src/spine-items" spine_engine = "venv/src/spine-engine" spinedb_api = "venv/src/spinedb-api"
You can also specify the branches for each repository that should be used for the release. This section is optional, and if left unspecified, the branch name is assumed to be
master
.Release branches on Spine repositories# default: master [tool.conductor.branches] spinetoolbox = "release" spine_items = "release" spine_engine = "release" spinedb_api = "release"
Manual release (in case of emergency)
This section documents what the spine-conductor CLI tool does under the hood. It is here in case of an emergency (e.g. there’s a bug), and the release has to be done manually.
As mentioned earlier, the package version is now derived from Git tags. However, because of the internal dependency between the Spine packages, the versions of the dependencies have to synchronised with the new version. The steps are as follows:
Determine the next version for each Spine package. This can be done manually with Git, or you can use
setuptools_scm
in a Python REPL.You can run
git describe --tags
in the repo. This will print out the latest tag followed by a trailer with metadata on distance from the tag; something like this:0.6.18-100-g411c13e1
. If you want to make a patch release, the next version would be0.6.19
and a minor release would be0.7.0
. Repeat this process for all 4 Spine repos.If using a Python REPL, you can do the following for a minor release:
>>> from setuptools_scm import get_version >>> get_version(".", version_scheme="release-branch-semver") '0.7.0.dev100+g411c13e1.d20230823'
For a patch release, do the following:
>>> get_version(".", version_scheme="guess-next-dev") '0.6.19.dev100+g411c13e1.d20230823'
Note the first argument to
get_version
is the path to the repository. The above examples assume the repository is your current directory. If it’s not, you can provide the path as the first argument.
Once the new package versions are determined, you need to edit the
pyproject.toml
files in all 4 repositories with the correct version numbers. For example, in theSpine-Toolbox
repo if you were to do a minor release, i.e.0.6.18
→0.7.0
, the following change would be sufficient:Example edit topyproject.toml
for Spine-Toolboxdiff --git a/pyproject.toml b/pyproject.toml index bd38a2b7..dd9c228e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,8 +20,8 @@ dependencies = [ "jupyter-client >=6.0", "qtconsole >=5.1", "sqlalchemy >=1.3", - "spinedb_api >=0.29.0", - "spine_engine >=0.22.0", + "spinedb_api >=0.30.0", + "spine_engine >=0.23.0", "numpy >=1.20.2", "matplotlib >= 3.5", "scipy >=1.7.1", @@ -30,7 +30,7 @@ dependencies = [ "pygments >=2.8", "jill >=0.9.2", "pyzmq >=21.0", - "spine-items >= 0.20.0", + "spine-items >= 0.21.0", ] [project.urls]
After updating the
pyproject.toml
file for all 4 Spine repos as above, add and commit the changes in all repos:git commit -i pyproject.toml -m "Release 0.7.0"
Create a Git tag on the latest commit:
git tag 0.7.0 HEAD
Push the tags to GitHub. On sh-like shells like: bash, zsh, or git-bash (Windows):
Recipe to push Git tags to GitHub onsh
-like shells (bash, zsh, git-bash)for repo in . venv/src/{spinedb-api,spine-{items,engine}}; do pushd $repo; git push origin master --tags; popd done
With Powershell on Windows:
Recipe to push Git tags to GitHub on Powershell"." , "venv/src/spinedb-api", "venv/src/spine-items", "venv/src/spine-engine" | % { pushd $_; git push origin master --tags; popd; }
Now you can trigger the workflow to publish the packages to PyPI from the workflow dispatch menu in the spine-conductor repo. Ensure you input the exact same package versions as in the tags.
In case the workflow above also fails, you have to build the source distribution archive and wheels locally and upload to PyPI manually.
To build, ensure you have
build
installed. Thebuild
backend ensures build isolation, and reproducibility of the wheels given a source distribution.Build distribution archives and wheelspython -m pip install build python -m build
Once the build completes, you can find the source tarball and the wheel in
dist/
. Now you may upload these files to PyPI.It is good practise to first test using TestPyPI before uploading to PyPI, since releases on PyPI are read-only. You want to avoid mistakes.
Register an account and ask some of the owners of the Spine Toolbox package (or other relevant package) to add you as a maintainer.
Upload the distribution using
twine upload --repository testpypi dist/*
See Using TestPyPI for more information. To avoid entering your username and password every time, see Keyring support in twine documentation or generate an API key. If everything went smoothly, you are ready to upload the real index. Again, you need to register to PyPI and ask to become a maintainer of the package you want to upload to. Upload the distribution using
$ twine upload dist/*
Done! Now fix the bug that forced you to do the manual release ;)
API Reference
This page contains auto-generated API reference documentation 1.
spinetoolbox
spinetoolbox package.
Subpackages
spinetoolbox.mvcmodels
Modules in this package contain classes that represent Spine Toolbox’s models (internal data structures) in the Model-View-Controller design pattern. The model classes define an interface that is used by views and delegates to access data in the application.
Submodules
spinetoolbox.mvcmodels.array_model
Contains model for the Array editor widget.
Model for the Array parameter_value type. |
- class spinetoolbox.mvcmodels.array_model.ArrayModel(parent)[source]
Bases:
PySide6.QtCore.QAbstractTableModel
Model for the Array parameter_value type.
Even if the array is empty this model’s rowCount() will still return 1. This is to show an empty row in the table view.
- Parameters
parent (QObject) – parent object
- batch_set_data(indexes, values)[source]
Sets data at multiple indexes at once.
- Parameters
indexes (list of QModelIndex) – indexes to set
values (list of str) – values corresponding to the indexes
- _convert_to_data_type(indexes, values)[source]
Converts values from string to current data type filtering failed conversions.
- Parameters
indexes (list of QModelIndex) – indexes
values (list of str) – values to convert
- Returns
indexes and converted values
- Return type
tuple
- is_expanse_row(row)[source]
Returns True if row is the expanse row.
- Parameters
row (int) – a row
- Returns
True is row is expanse row, False otherwise
- Return type
bool
- reset(value)[source]
Resets the model to a new array.
- Parameters
value (Array) – a new array to model
- rowCount(parent=QModelIndex())[source]
Returns the length of the array.
Note: returns 1 even if the array is empty.
spinetoolbox.mvcmodels.compound_table_model
Models that vertically concatenate two or more table models.
A model that concatenates several sub table models vertically. |
|
A compound parameter table model where the last model is an empty row model. |
- class spinetoolbox.mvcmodels.compound_table_model.CompoundTableModel(parent=None, header=None)[source]
Bases:
spinetoolbox.mvcmodels.minimal_table_model.MinimalTableModel
A model that concatenates several sub table models vertically.
Initializes model.
- Parameters
parent (QObject, optional) – the parent object
header (list of str, optional) – header labels
- map_to_sub(index)[source]
Returns an equivalent submodel index.
- Parameters
index (QModelIndex) – the compound model index.
- Returns
the equivalent index in one of the submodels
- Return type
QModelIndex
- map_from_sub(sub_model, sub_index)[source]
Returns an equivalent compound model index.
- Parameters
sub_model (MinimalTableModel) – the submodel
sub_index (QModelIndex) – the submodel index.
- Returns
the equivalent index in the compound model
- Return type
QModelIndex
- sub_model_at_row(row)[source]
Returns the submodel corresponding to the given row in the compound model.
- Parameters
row (int) –
- Returns
MinimalTableModel
- sub_model_row(row)[source]
Calculates sub model row.
- Parameters
row (int) – row in compound model
- Returns
row in sub model
- Return type
int
- _append_row_map(row_map)[source]
Appends given row map to the tail of the model.
- Parameters
row_map (list) – tuples (model, row number)
- _row_map_iterator_for_model(model)[source]
Yields row map for given model. The base class implementation just yields all model rows.
- Parameters
model (MinimalTableModel) –
- Yields
tuple – (model, row number)
- _row_map_for_model(model)[source]
Returns row map for given model. The base class implementation just returns all model rows.
- Parameters
model (MinimalTableModel) –
- Returns
tuples (model, row number)
- Return type
list
- canFetchMore(parent)[source]
Returns True if any of the submodels that haven’t been fetched yet can fetch more.
- data(index, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the data stored under the given role for the item referred to by the index.
- Parameters
index (QModelIndex) – Index of item
role (int) – Data role
- Returns
Item data for given role.
- batch_set_data(indexes, data)[source]
Sets data for indexes in batch. Distributes indexes and values among the different submodels and calls batch_set_data on each of them.
- class spinetoolbox.mvcmodels.compound_table_model.CompoundWithEmptyTableModel(parent=None, header=None)[source]
Bases:
CompoundTableModel
A compound parameter table model where the last model is an empty row model.
Initializes model.
- Parameters
parent (QObject, optional) – the parent object
header (list of str, optional) – header labels
- abstract _create_empty_model()[source]
Creates and returns an empty model.
- Returns
model
- Return type
- init_model()[source]
Initializes the compound model.
Basically populates the sub_models list attribute with the result of _create_empty_model.
- _connect_single_model(model)[source]
Connects signals so changes in the submodels are acknowledged by the compound.
- _recompute_empty_row_map()[source]
Recomputes the part of the row map corresponding to the empty model.
- _handle_empty_rows_removed(parent, empty_first, empty_last)[source]
Updates row_map when rows are removed from the empty model.
spinetoolbox.mvcmodels.empty_row_model
Contains a table model with an empty last row.
A table model with a last empty row. |
- class spinetoolbox.mvcmodels.empty_row_model.EmptyRowModel(parent=None, header=None)[source]
Bases:
spinetoolbox.mvcmodels.minimal_table_model.MinimalTableModel
A table model with a last empty row.
Init class.
spinetoolbox.mvcmodels.file_list_models
Contains a generic File list model and an Item for that model.
A model for files to be shown in a file tree view. |
|
- class spinetoolbox.mvcmodels.file_list_models.FileListModel(header_label='', draggable=False)[source]
Bases:
PySide6.QtCore.QAbstractItemModel
A model for files to be shown in a file tree view.
- Parameters
header_label (str) – header label
draggable (bool) – if True, the top level items are drag and droppable
- headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]
Returns header information.
- data(index, role=Qt.ItemDataRole.DisplayRole)[source]
Returns data associated with given role at given index.
- resource(index)[source]
Returns the resource at given index.
- Parameters
index (QModelIndex) – index
- Returns
resource
- Return type
ProjectItemResource
- update(resources)[source]
Updates the model according to given list of resources.
- Parameters
resources (Iterable of ProjectItemResource) – resources
- class spinetoolbox.mvcmodels.file_list_models.CommandLineArgItem(text='', rank=None, selectable=False, editable=False, drag_enabled=False, drop_enabled=False)[source]
Bases:
PySide6.QtGui.QStandardItem
- class spinetoolbox.mvcmodels.file_list_models.NewCommandLineArgItem[source]
Bases:
CommandLineArgItem
spinetoolbox.mvcmodels.filter_checkbox_list_model
Provides FilterCheckboxListModel for FilterWidget.
|
|
Extends SimpleFilterCheckboxListModel to allow for lazy loading in synch with another model. |
|
Extends SimpleFilterCheckboxListModel to allow for translating internal data to a value for display role. |
- class spinetoolbox.mvcmodels.filter_checkbox_list_model.SimpleFilterCheckboxListModel(parent, show_empty=True)[source]
Bases:
PySide6.QtCore.QAbstractListModel
- Parameters
parent (QWidget) – parent widget
show_empty (bool) – if True, adds an empty row to the end of the list
- class spinetoolbox.mvcmodels.filter_checkbox_list_model.LazyFilterCheckboxListModel(parent, db_mngr, db_maps, fetch_parent, show_empty=True)[source]
Bases:
SimpleFilterCheckboxListModel
Extends SimpleFilterCheckboxListModel to allow for lazy loading in synch with another model.
- Parameters
parent (SpineDBEditor) – parent widget
db_mngr (SpineDBManager) – database manager
db_maps (Sequence of DatabaseMapping) – database maps
fetch_parent (FetchParent) – fetch parent
show_empty (bool) – if True, show an empty row at the end of the list
- class spinetoolbox.mvcmodels.filter_checkbox_list_model.DataToValueFilterCheckboxListModel(parent, data_to_value, show_empty=True)[source]
Bases:
SimpleFilterCheckboxListModel
Extends SimpleFilterCheckboxListModel to allow for translating internal data to a value for display role.
- Parameters
parent (SpineDBEditor) – parent widget
data_to_value (method) – a method to translate item data to a value for display role
show_empty (bool) – if True, add an empty row to the end of the list
spinetoolbox.mvcmodels.filter_execution_model
Contains FilterExecutionModel.
spinetoolbox.mvcmodels.indexed_value_table_model
A model for indexed parameter values, used by the parameter_value editors.
A base class for time pattern and time series models. |
- class spinetoolbox.mvcmodels.indexed_value_table_model.IndexedValueTableModel(value, parent)[source]
Bases:
PySide6.QtCore.QAbstractTableModel
A base class for time pattern and time series models.
- Parameters
value (IndexedValue) – a parameter_value
parent (QObject) – parent object
- headerData(section, orientation=Qt.Orientation.Horizontal, role=Qt.ItemDataRole.DisplayRole)[source]
Returns a header.
spinetoolbox.mvcmodels.map_model
A model for maps, used by the parameter_value editors.
|
Turns table into nested dictionaries. |
|
Constructs a |
|
Counts the number of non-empty elements at the beginning of row. |
|
Collects index names from Map. |
|
Applies index names to Map. |
Converts instances of |
Sentinel for empty cells. |
- class spinetoolbox.mvcmodels.map_model.MapModel(map_value, parent)[source]
Bases:
PySide6.QtCore.QAbstractTableModel
A model for Map type parameter values.
This model represents the Map as a 2D table. Each row consists of one or more index columns and a value column. The last columns of a row are padded with Nones.
Example
Map { "A": 1.0 "B": Map {"a": -1.0} "C": 3.0 }
The table corresponding to the above map:
“A”
1.0
None
“B”
“a”
-1.0
“C”
3.0
None
- Parameters
map_value (Map) – a map
parent (QObject) – parent object
- clear(indexes)[source]
Clears table cells.
- Parameters
indexes (list of QModelIndex) – indexes to clear
- data(index, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the data associated with the given role.
- headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]
Returns row numbers for vertical headers and column titles for horizontal ones.
- insertColumns(column, count, parent=QModelIndex())[source]
Inserts new columns into the map.
- Parameters
column (int) – column index where to insert
count (int) – number of new columns
parent (QModelIndex) – ignored
- Returns
True if insertion was successful, False otherwise
- Return type
bool
- insertRows(row, count, parent=QModelIndex())[source]
Inserts new rows into the map.
- Parameters
row (int) – an index where to insert the new data
count (int) – number of rows to insert
parent (QModelIndex) – an index to a parent model
- Returns
True if the operation was successful
- Return type
bool
- is_leaf_value(index)[source]
Checks if given model index contains a leaf value.
- Parameters
index (QModelIndex) – index to check
- Returns
True if index points to leaf value, False otherwise
- Return type
bool
- _is_in_expanse(row, column)[source]
Returns True, if given row and column is in the right or bottom ‘expanding’ zone.
- Parameters
row (int) – row index
column (int) – column index
- Returns
True if the cell is in the expanse, False otherwise
- Return type
bool
- is_expanse_column(column)[source]
Returns True if given column is the expanse column.
- Parameters
column (int) – column
- Returns
True if column is expanse column, False otherwise
- Return type
bool
- is_expanse_row(row)[source]
Returns True if given row is the expanse row.
- Parameters
row (int) – row
- Returns
True if row is the expanse row, False otherwise
- Return type
bool
- removeColumns(column, count, parent=QModelIndex())[source]
Removes columns from the map.
- Parameters
column (int) – first column to remove
count (int) – number of columns to remove
parent (QModelIndex) – an index to a parent model
- Returns
True if the operation was successful
- removeRows(row, count, parent=QModelIndex())[source]
Removes rows from the map.
- Parameters
row (int) – first row to remove
count (int) – number of rows to remove
parent (QModelIndex) – an index to a parent model
- Returns
True if the operation was successful
- set_box(top_left, bottom_right, data)[source]
Sets data for several indexes at once.
- Parameters
top_left (QModelIndex) – a sequence of model indexes
bottom_right (QModelIndex) – a sequence of values corresponding to the indexes
data (list of list) – box of data
- spinetoolbox.mvcmodels.map_model._rows_to_dict(rows)[source]
Turns table into nested dictionaries.
- Parameters
rows (list) – a list of row data
- Returns
a nested dictionary
- Return type
dict
- spinetoolbox.mvcmodels.map_model._reconstruct_map(tree)[source]
Constructs a
Map
from a nested dictionary.- Parameters
tree (dict) – a nested dictionary
- Returns
reconstructed Map
- Return type
Map
- spinetoolbox.mvcmodels.map_model._data_length(row)[source]
Counts the number of non-empty elements at the beginning of row.
- Parameters
row (list) – a row of data
- Returns
data length
- Return type
int
- spinetoolbox.mvcmodels.map_model._gather_index_names(map_value)[source]
Collects index names from Map.
Returns only the ‘first’ index name for nested maps at the same depth.
- Parameters
map_value (Map) – map to investigate
- Returns
index names
- Return type
list of str
spinetoolbox.mvcmodels.minimal_table_model
Contains a minimal table model.
Table model for outlining simple tabular data. |
- class spinetoolbox.mvcmodels.minimal_table_model.MinimalTableModel(parent=None, header=None, lazy=True)[source]
Bases:
PySide6.QtCore.QAbstractTableModel
Table model for outlining simple tabular data.
- Parameters
parent (QObject, optional) – the parent object
header (list of str) – header labels
lazy (boolean) – if True, fetches data lazily
- headerData(section, orientation=Qt.Orientation.Horizontal, role=Qt.ItemDataRole.DisplayRole)[source]
Returns headers.
- insert_horizontal_header_labels(section, labels)[source]
Insert horizontal header labels at the given section.
- setHeaderData(section, orientation, value, role=Qt.ItemDataRole.EditRole)[source]
Sets the data for the given role and section in the header with the specified orientation to the value supplied.
- data(index, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the data stored under the given role for the item referred to by the index.
- Parameters
index (QModelIndex) – Index of item
role (int) – Data role
- Returns
Item data for given role.
- row_data(row, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the data stored under the given role for the given row.
- Parameters
row (int) – Item row
role (int) – Data role
- Returns
Row data for given role.
- batch_set_data(indexes, data)[source]
Batch set data for indexes.
- Parameters
indexes (Iterable of QModelIndex) – model indexes
data (Iterable) – data at each index
- Returns
True if data was set successfully, False otherwise
- Return type
boolean
- insertRows(row, count, parent=QModelIndex())[source]
Inserts count rows into the model before the given row. Items in the new row will be children of the item represented by the parent model index.
- Parameters
row (int) – Row number where new rows are inserted
count (int) – Number of inserted rows
parent (QModelIndex) – Parent index
- Returns
True if rows were inserted successfully, False otherwise
- insertColumns(column, count, parent=QModelIndex())[source]
Inserts count columns into the model before the given column. Items in the new column will be children of the item represented by the parent model index.
- Parameters
column (int) – Column number where new columns are inserted
count (int) – Number of inserted columns
parent (QModelIndex) – Parent index
- Returns
True if columns were inserted successfully, False otherwise
- removeRows(row, count, parent=QModelIndex())[source]
Removes count rows starting with the given row under parent.
- Parameters
row (int) – Row number where to start removing rows
count (int) – Number of removed rows
parent (QModelIndex) – Parent index
- Returns
True if rows were removed successfully, False otherwise
- removeColumns(column, count, parent=QModelIndex())[source]
Removes count columns starting with the given column under parent.
- Parameters
column (int) – Column number where to start removing columns
count (int) – Number of removed columns
parent (QModelIndex) – Parent index
- Returns
True if columns were removed successfully, False otherwise
spinetoolbox.mvcmodels.minimal_tree_model
Models to represent items in a tree.
A tree item that can fetch its children. |
|
Base class for all tree models. |
- class spinetoolbox.mvcmodels.minimal_tree_model.TreeItem(model)[source]
A tree item that can fetch its children.
- Parameters
model (MinimalTreeModel) – The model where the item belongs.
- is_valid()[source]
Tests if item is valid.
- Returns
True if item is valid, False otherwise
- Return type
bool
- row_count()[source]
Returns the number of rows, which may be different from the number of children. This allows subclasses to hide children.
- find_children(cond=lambda child: ...)[source]
Returns children that meet condition expressed as a lambda function.
- find_child(cond=lambda child: ...)[source]
Returns first child that meet condition expressed as a lambda function or None.
- insert_children(position, children)[source]
Insert new children at given position. Returns a boolean depending on how it went.
- Parameters
position (int) – insert new items here
children (list of TreeItem) – insert items from this iterable
- Returns
True if the children were inserted successfully, False otherwise
- Return type
bool
- class spinetoolbox.mvcmodels.minimal_tree_model.MinimalTreeModel(parent)[source]
Bases:
PySide6.QtCore.QAbstractItemModel
Base class for all tree models.
- Parameters
parent (SpineDBEditor) –
- visit_all(index=QModelIndex(), view=None)[source]
Iterates all items in the model including and below the given index. Iterative implementation so we don’t need to worry about Python recursion limits.
- Parameters
index (QModelIndex) – an index to start. If not given, we start at the root
view (QTreeView) – a tree view. If given, we only yield items that are visible to that view. So for example, if a tree item is not expanded then we don’t yield its children.
- Yields
TreeItem
- item_from_index(index)[source]
Return the item corresponding to the given index.
- Parameters
index (QModelIndex) – model index
- Returns
item at index
- Return type
- index_from_item(item)[source]
Return a model index corresponding to the given item.
- Parameters
item (StandardTreeItem) – item
- Returns
item’s index
- Return type
QModelIndex
- index(row, column, parent=QModelIndex())[source]
Returns the index of the item in the model specified by the given row, column and parent index.
- data(index, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the data stored under the given role for the index.
spinetoolbox.mvcmodels.project_item_specification_models
Contains a class for storing Tool specifications.
Class to store specs that are available in a project e.g. GAMS or Julia models. |
|
- class spinetoolbox.mvcmodels.project_item_specification_models.ProjectItemSpecificationModel(icons)[source]
Bases:
PySide6.QtCore.QAbstractListModel
Class to store specs that are available in a project e.g. GAMS or Julia models.
- add_specification(name)[source]
Adds a specification to the model.
- Parameters
name (str) – specification’s name
- remove_specification(name)[source]
Removes a specification from the model
- Parameters
name (str) – specification’s name
- replace_specification(old_name, new_name)[source]
Replaces a specification.
- Parameters
old_name (str) – previous name
new_name (str) – new name
- connect_to_project(project)[source]
Connects the model to a project.
- Parameters
project (SpineToolboxProject) – project to connect to
- rowCount(parent=None)[source]
Returns the number of specs in the model.
- Parameters
parent (QModelIndex) – Not used (because this is a list)
- Returns
Number of rows (available specs) in the model
- data(index, role=None)[source]
Must be reimplemented when subclassing.
- Parameters
index (QModelIndex) – Requested index
role (int) – Data role
- Returns
Data according to requested role
- flags(index)[source]
Returns enabled flags for the given index.
- Parameters
index (QModelIndex) – Index of spec
- insertRow(spec_name, row=None, parent=QModelIndex())[source]
Insert row (specification) into model.
- Parameters
spec_name (str) – name of spec added to the model
row (int, optional) – Row to insert spec to
parent (QModelIndex) – Parent of child (not used)
- Returns
Void
- removeRow(row, parent=QModelIndex())[source]
Remove row (spec) from model.
- Parameters
row (int) – Row to remove the spec from
parent (QModelIndex) – Parent of spec on row (not used)
- Returns
Boolean variable
- specification(row)[source]
Returns spec on given row.
- Parameters
row (int) – Row of spec specification
- Returns
ProjectItemSpecification from specification list or None if given row is zero
spinetoolbox.mvcmodels.resource_filter_model
Contains ResourceFilterModel.
|
- class spinetoolbox.mvcmodels.resource_filter_model.ResourceFilterModel(connection, project, undo_stack, logger)[source]
Bases:
PySide6.QtGui.QStandardItemModel
- Parameters
connection (LoggingConnection) – connection whose resources to model
project (SpineToolboxProject) – project
undo_stack (QUndoStack) – an undo stack
logger (LoggerInterface) – a logger
- _change_filter_checked_state(index, is_on)[source]
Changes the online status of the filter item at index.
- Parameters
index (QModelIndex) – item’s index
is_on (bool) – True if filter are turned online, False otherwise
- set_online(resource, filter_type, online)[source]
Sets the given filters online or offline.
- Parameters
resource (str) – Resource label
filter_type (str) – Always SCENARIO_FILTER_TYPE, for now.
online (dict) – mapping from scenario/tool id to online flag
- _find_filter_type_item(resource, filter_type)[source]
Searches for filter type item.
- Parameters
resource (str) – resource label
filter_type (str) – filter type identifier
- Returns
filter type item or None if not found
- Return type
QStandardItem
- filter_type_items(filter_type)[source]
An iterator to filter type items.
- Parameters
filter_type (str) – filter type
- Yields
QStandardItem – filter type item
- _set_all_selected_item(resource, filter_type_item, emit_data_changed=False)[source]
Updates ‘Select All’ item’s checked state.
- Parameters
resource (str) – resource label
filter_type_item (QStandardItem) – filter type item
emit_data_changed (bool) – if True, emit dataChanged signal if the state was updated
spinetoolbox.mvcmodels.time_pattern_model
A model for time patterns, used by the parameter_value editors.
A model for time pattern type parameter values. |
- class spinetoolbox.mvcmodels.time_pattern_model.TimePatternModel(value, parent)[source]
Bases:
spinetoolbox.mvcmodels.indexed_value_table_model.IndexedValueTableModel
A model for time pattern type parameter values.
- Parameters
value (IndexedValue) – a parameter_value
parent (QObject) – parent object
- insertRows(row, count, parent=QModelIndex())[source]
Inserts new time period - value pairs into the pattern.
New time periods are initialized to empty strings and the corresponding values to zeros.
- Parameters
row (int) – an index where to insert the new data
count (int) – number of time period - value pairs to insert
parent (QModelIndex) – an index to a parent model
- Returns
True if the operation was successful
- Return type
bool
- removeRows(row, count, parent=QModelIndex())[source]
Removes time period - value pairs from the pattern.
- Parameters
row (int) – an index where to remove the data
count (int) – number of time period - value pairs to remove
parent (QModelIndex) – an index to a parent model
- Returns
True if the operation was successful
- Return type
bool
- setData(index, value, role=Qt.ItemDataRole.EditRole)[source]
Sets a time period or a value in the pattern.
Column index 0 corresponds to the time periods while 1 corresponds to the values.
- Parameters
index (QModelIndex) – an index to the model
value (str, float) – a new time period or value
role (int) – a role
- Returns
True if the operation was successful
- Return type
bool
spinetoolbox.mvcmodels.time_series_model_fixed_resolution
A model for fixed resolution time series, used by the parameter_value editors.
A model for fixed resolution time series type parameter values. |
- class spinetoolbox.mvcmodels.time_series_model_fixed_resolution.TimeSeriesModelFixedResolution(series, parent)[source]
Bases:
spinetoolbox.mvcmodels.indexed_value_table_model.IndexedValueTableModel
A model for fixed resolution time series type parameter values.
- Parameters
series (TimeSeriesFixedResolution) – a time series
parent (QObject) – parent object
- insertRows(row, count, parent=QModelIndex())[source]
Inserts new values to the series.
The new values are set to zero. Start time or resolution are left unchanged.
- Parameters
row (int) – a numeric index to the first stamp/value to insert
count (int) – number of stamps/values to insert
parent (QModelIndex) – index to a parent model
- Returns
True if the operation was successful
- removeRows(row, count, parent=QModelIndex())[source]
Removes values from the series.
- Parameters
row (int) – a numeric index to the series where to begin removing
count (int) – how many stamps/values to remove
parent (QModelIndex) – an index to the parent model
- Returns
True if the operation was successful.
- setData(index, value, role=Qt.ItemDataRole.EditRole)[source]
Sets a given value in the series.
Column index 1 refers to values. Note it does not make sense to set the time stamps in fixed resolution series.
- Parameters
index (QModelIndex) – an index to the model
value (numpy.datetime64, float) – a new stamp or value
role (int) – a role
- Returns
True if the operation was successful
spinetoolbox.mvcmodels.time_series_model_variable_resolution
A model for variable resolution time series, used by the parameter_value editors.
A model for variable resolution time series type parameter values. |
- class spinetoolbox.mvcmodels.time_series_model_variable_resolution.TimeSeriesModelVariableResolution(value, parent)[source]
Bases:
spinetoolbox.mvcmodels.indexed_value_table_model.IndexedValueTableModel
A model for variable resolution time series type parameter values.
- Parameters
value (IndexedValue) – a parameter_value
parent (QObject) – parent object
- insertRows(row, count, parent=QModelIndex())[source]
Inserts new time stamps and values to the series.
When inserting in the middle of the series the new time stamps are distributed evenly among the time span between the two time stamps around the insertion point. When inserting at the beginning or at the end of the series the duration between the new time stamps is set equal to the first/last duration in the original series.
The new values are set to zero.
- Parameters
row (int) – a numeric index to the first stamp/value to insert
count (int) – number of stamps/values to insert
parent (QModelIndex) – index to a parent model
- Returns
True if the insertion was successful
- Return type
bool
- removeRows(row, count, parent=QModelIndex())[source]
Removes time stamps/values from the series.
- Parameters
row (int) – a numeric index to the series where to begin removing
count (int) – how many stamps/values to remove
parent (QModelIndex) – an index to the parent model
- Returns
True if the operation was successful.
- Return type
bool
- setData(index, value, role=Qt.ItemDataRole.EditRole)[source]
Sets a given time stamp or value in the series.
Column index 0 refers to time stamps while index 1 to values.
- Parameters
index (QModelIndex) – an index to the model
value (numpy.datetime64, float) – a new stamp or value
role (int) – a role
- Returns
True if the operation was successful
- Return type
bool
spinetoolbox.project_item
This subpackage contains base classes for project items.
Submodules
spinetoolbox.project_item.logging_connection
Contains logging connection and jump classes.
A project item connection that is compatible with headless mode. |
|
A project item connection that is compatible with headless mode. |
|
Represents a conditional jump between two project items. |
- class spinetoolbox.project_item.logging_connection.HeadlessConnection(source_name, source_position, destination_name, destination_position, options=None, filter_settings=None, legacy_resource_filter_ids=None)[source]
Bases:
spine_engine.project_item.connection.ResourceConvertingConnection
A project item connection that is compatible with headless mode.
- Parameters
source_name (str) – source project item’s name
source_position (str) – source anchor’s position
destination_name (str) – destination project item’s name
destination_position (str) – destination anchor’s position
options (dict, optional) – any additional options
filter_settings (FilterSettings, optional) – filter settings
- set_filter_enabled(resource_label, filter_type, filter_name, enabled)[source]
Enables or disables a filter.
- Parameters
resource_label (str) – database resource name
filter_type (str) – filter type
filter_name (str) – filter name
enabled (bool) – True to enable the filter, False to disable it
- set_filter_type_enabled(filter_type, enabled)[source]
Enables or disables a filter type.
- Parameters
filter_type (str) – filter type
enabled (bool) – True to enable the filter type, False to disable it
- _convert_legacy_resource_filter_ids_to_filter_settings()[source]
Converts legacy resource filter ids to filter settings.
This method should be called once after constructing the connection from potentially legacy dict using
from_dict()
.
- class spinetoolbox.project_item.logging_connection.LoggingConnection(*args, toolbox, **kwargs)[source]
Bases:
spinetoolbox.log_mixin.LogMixin
,HeadlessConnection
A project item connection that is compatible with headless mode.
- Parameters
source_name (str) – source project item’s name
source_position (str) – source anchor’s position
destination_name (str) – destination project item’s name
destination_position (str) – destination anchor’s position
options (dict, optional) – any additional options
filter_settings (FilterSettings, optional) – filter settings
- has_filters()[source]
Returns True if connection has any filters.
- Returns
True if connection has filters, False otherwise
- Return type
bool
- _pop_unused_db_maps()[source]
Removes unused database maps and unregisters from listening the DB manager.
- may_have_filters()[source]
Returns whether this connection may have filters.
- Returns
True if it is possible for the connection to have filters, False otherwise
- Return type
bool
- may_have_write_index()[source]
Returns whether this connection may have write index.
- Returns
True if it is possible for the connection to have write index, False otherwise
- Return type
bool
- may_use_memory_db()[source]
Returns whether this connection may use memory DB.
- Returns
True if it is possible for the connection to use memory DB, False otherwise
- Return type
bool
- may_use_datapackage()[source]
Returns whether this connection may use datapackage.
- Returns
True if it is possible for the connection to use datapackage, False otherwise
- Return type
bool
- may_purge_before_writing()[source]
Returns whether this connection may purge before writing.
- Returns
True if it is possible for the connection to purge before writing, False otherwise
- Return type
bool
- online_filters(resource_label, filter_type)[source]
Returns filter online states for given resource and filter type.
- Parameters
resource_label (str) – resource label
filter_type (str) – filter type
- Returns
mapping from filter names to online states
- Return type
dict
- set_online(resource, filter_type, online)[source]
Sets the given filters online or offline.
- Parameters
resource (str) – Resource label
filter_type (str) – filter type
online (dict) – mapping from scenario name to online flag
- set_filter_default_online_status(auto_online)[source]
Sets the auto_online flag.
- Parameters
auto_online (bool) – If True, unknown filters are online by default
- refresh_resource_filter_model()[source]
Makes resource filter mode fetch filter data from database.
- set_connection_options(options)[source]
Overwrites connections options.
- Parameters
options (dict) – new options
- class spinetoolbox.project_item.logging_connection.LoggingJump(*args, toolbox=None, **kwargs)[source]
Bases:
spinetoolbox.log_mixin.LogMixin
,spine_engine.project_item.connection.Jump
Represents a conditional jump between two project items.
- Parameters
source_name (str) – source project item’s name
source_position (str) – source anchor’s position
destination_name (str) – destination project item’s name
destination_position (str) – destination anchor’s position
condition (dict) – jump condition
spinetoolbox.project_item.project_item
Contains base classes for project items and item factories.
Class for project items that are not category nor root. |
- class spinetoolbox.project_item.project_item.ProjectItem(name, description, x, y, project)[source]
Bases:
spinetoolbox.log_mixin.LogMixin
,spinetoolbox.metaobject.MetaObject
Class for project items that are not category nor root. These items can be executed, refreshed, and so on.
- x
horizontal position in the screen
- Type
float
- y
vertical position in the screen
- Type
float
- Parameters
name (str) – item name
description (str) – item description
x (float) – horizontal position on the scene
y (float) – vertical position on the scene
project (SpineToolboxProject) – project item’s project
- abstract static item_type()[source]
Item’s type identifier string.
- Returns
type string
- Return type
str
- make_signal_handler_dict()[source]
Returns a dictionary of all shared signals and their handlers. This is to enable simpler connecting and disconnecting. Must be implemented in subclasses.
- restore_selections()[source]
Restore selections into shared widgets when this project item is selected.
- save_selections()[source]
Save selections in shared widgets for this project item into instance variables.
- set_properties_ui(properties_ui)[source]
Sets the properties tab widget for the item.
Note that this method expects the widget that is generated from the .ui files and initialized with the setupUi() method rather than the entire properties tab widget.
- Parameters
properties_ui (QWidget) – item’s properties UI
- set_specification(specification)[source]
Pushes a new SetItemSpecificationCommand to the toolbox’ undo stack.
- do_set_specification(specification)[source]
Sets specification for this item. Removes specification if None given as argument.
- Parameters
specification (ProjectItemSpecification) – specification of this item. None removes the specification.
- set_icon(icon)[source]
Sets the icon for the item.
- Parameters
icon (ProjectItemIcon) – item’s icon
- handle_execution_successful(execution_direction, engine_state)[source]
Performs item dependent actions after the execution item has finished successfully.
- Parameters
execution_direction (ExecutionDirection) – ExecutionDirection.FORWARD or ExecutionDirection.BACKWARD
engine_state – engine state after item’s execution
- resources_for_direct_successors()[source]
Returns resources for direct successors.
These resources can include transient files that don’t exist yet, or filename patterns. The default implementation returns an empty list.
- Returns
a list of ProjectItemResources
- Return type
list
- resources_for_direct_predecessors()[source]
Returns resources for direct predecessors.
These resources can include transient files that don’t exist yet, or filename patterns. The default implementation returns an empty list.
- Returns
a list of ProjectItemResources
- Return type
list
- _resources_to_predecessors_changed()[source]
Notifies direct predecessors that item’s resources have changed.
- _resources_to_predecessors_replaced(old, new)[source]
Notifies direct predecessors that item’s resources have been replaced.
- Parameters
old (list of ProjectItemResource) – old resources
new (list of ProjectItemResource) – new resources
- upstream_resources_updated(resources)[source]
Notifies item that resources from direct predecessors have changed.
- Parameters
resources (list of ProjectItemResource) – new resources from upstream
- replace_resources_from_upstream(old, new)[source]
Replaces existing resources from direct predecessor by a new ones.
- Parameters
old (list of ProjectItemResource) – old resources
new (list of ProjectItemResource) – new resources
- _resources_to_successors_changed()[source]
Notifies direct successors that item’s resources have changed.
- _resources_to_successors_replaced(old, new)[source]
Notifies direct successors that one of item’s resources has been replaced.
- Parameters
old (list of ProjectItemResource) – old resources
new (list of ProjectItemResource) – new resources
- downstream_resources_updated(resources)[source]
Notifies item that resources from direct successors have changed.
- Parameters
resources (list of ProjectItemResource) – new resources from downstream
- replace_resources_from_downstream(old, new)[source]
Replaces existing resources from direct successor by a new ones.
- Parameters
old (list of ProjectItemResource) – old resources
new (list of ProjectItemResource) – new resources
- item_dict()[source]
Returns a dictionary corresponding to this item.
- Returns
serialized project item
- Return type
dict
- static item_dict_local_entries()[source]
Returns entries or ‘paths’ in item dict that should be stored in project’s local data directory.
- Returns
local data item dict entries
- Return type
list of tuple of str
- static parse_item_dict(item_dict)[source]
Reads the information needed to construct the base ProjectItem class from an item dict.
- Parameters
item_dict (dict) – an item dict
- Returns
item’s name, description as well as x and y coordinates
- Return type
tuple
- copy_local_data(item_dict)[source]
Copies local data linked to a duplicated project item.
- Parameters
item_dict (dict) – serialized item
- abstract static from_dict(name, item_dict, toolbox, project)[source]
Deserialized an item from item dict.
- Parameters
name (str) – item’s name
item_dict (dict) – serialized item
toolbox (ToolboxUI) – the main window
project (SpineToolboxProject) – a project
- Returns
deserialized item
- Return type
- rename(new_name, rename_data_dir_message)[source]
Renames this item.
If the project item needs any additional steps in renaming, override this method in subclass. See e.g. rename() method in DataStore class.
- Parameters
new_name (str) – New name
rename_data_dir_message (str) – Message to show when renaming item’s data directory
- Returns
True if item was renamed successfully, False otherwise
- Return type
bool
- tear_down()[source]
Tears down this item. Called both before closing the app and when removing the item from the project. Implement in subclasses to eg close all QMainWindows opened by this item.
- set_up()[source]
Sets up this item. Called when adding the item to the project. Implement in subclasses to eg recreate attributes destroyed by tear_down.
- update_name_label()[source]
Updates the name label on the properties widget, used when selecting an item and renaming the selected one.
- notify_destination(source_item)[source]
Informs an item that it has become the destination of a connection between two items.
The default implementation logs a warning message. Subclasses should reimplement this if they need more specific behavior.
- Parameters
source_item (ProjectItem) – connection source item
- static upgrade_v1_to_v2(item_name, item_dict)[source]
Upgrades item’s dictionary from v1 to v2.
Subclasses should reimplement this method if there are changes between version 1 and version 2.
- Parameters
item_name (str) – item’s name
item_dict (dict) – Version 1 item dictionary
- Returns
Version 2 item dictionary
- Return type
dict
- static upgrade_v2_to_v3(item_name, item_dict, project_upgrader)[source]
Upgrades item’s dictionary from v2 to v3.
Subclasses should reimplement this method if there are changes between version 2 and version 3.
- Parameters
item_name (str) – item’s name
item_dict (dict) – Version 2 item dictionary
project_upgrader (ProjectUpgrader) – Project upgrader class instance
- Returns
Version 3 item dictionary
- Return type
dict
spinetoolbox.project_item.project_item_factory
Contains base classes for project items and item factories.
Class for project item factories. |
- class spinetoolbox.project_item.project_item_factory.ProjectItemFactory[source]
Class for project item factories.
- abstract static item_class()[source]
Returns the project item’s class.
- Returns
item’s class
- Return type
type
- static is_deprecated()[source]
Queries if item is deprecated.
- Returns
True if item is deprecated, False otherwise
- Return type
bool
- abstract static icon_color()[source]
Returns the icon color.
- Returns
icon’s color
- Return type
QColor
- abstract static make_add_item_widget(toolbox, x, y, specification)[source]
Returns an appropriate Add project item widget.
- Parameters
toolbox (ToolboxUI) – the main window
x (int) – Icon coordinates
y (int) – Icon coordinates
specification (ProjectItemSpecification) – item’s specification
- Returns
QWidget
- abstract static make_icon(toolbox)[source]
Returns a ProjectItemIcon to use with given toolbox, for given project item.
- Parameters
toolbox (ToolboxUI) –
- Returns
item’s icon
- Return type
- abstract static make_item(name, item_dict, toolbox, project)[source]
Returns a project item constructed from the given
item_dict
.- Parameters
name (str) – item’s name
item_dict (dict) – serialized project item
toolbox (ToolboxUI) – Toolbox main window
project (SpineToolboxProject) – the project the item belongs to
- Returns
ProjectItem
- abstract static make_properties_widget(toolbox)[source]
Creates the item’s properties tab widget.
- Returns
item’s properties tab widget
- Return type
QWidget
Creates item specification’s context menu.
Subclasses that do not support specifications can still raise
NotImplementedError
.- Parameters
parent (QWidget) – menu’s parent widget
index (QModelIndex) – an index from specification model
- Returns
specification’s context menu
- Return type
- abstract static make_specification_editor(toolbox, specification=None, item=None, **kwargs)[source]
Creates the item’s specification widget.
Subclasses that do not support specifications can still raise
NotImplementedError
.- Parameters
toolbox (ToolboxUI) – Toolbox main window
specification (ProjectItemSpecification, optional) – a specification to show in the widget or None for a fresh start
item (ProjectItem, optional) – a project item. If the specification is accepted, it is also set for this item
**kwargs – parameters passed to the specification widget
- Returns
item’s specification widget
- Return type
QWidget
- static repair_specification(toolbox, specification)[source]
Called right after a spec is added to the project. Finds if there’s something wrong with the spec and proposes actions to fix it with help from toolbox.
- Parameters
toolbox (ToolboxUI) – Toolbox main window
specification (ProjectItemSpecification) – a specification to check
spinetoolbox.project_item.specification_editor_window
Contains SpecificationEditorWindowBase and ChangeSpecPropertyCommand
Enum where members are also (and must be) ints |
|
Command to set specification properties. |
|
Base class for spec editors. |
|
QToolBar for line edits and a hamburger menu. |
|
Prompts to save changes. |
- class spinetoolbox.project_item.specification_editor_window.CommandId[source]
Bases:
enum.IntEnum
Enum where members are also (and must be) ints
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.project_item.specification_editor_window.ChangeSpecPropertyCommand(callback, new_value, old_value, cmd_name, command_id=CommandId.NONE)[source]
Bases:
PySide6.QtGui.QUndoCommand
Command to set specification properties.
- Parameters
callback (Callable) – Function to call to set the spec property.
new_value (Any) – new value
old_value (Any) – old value
cmd_name (str) – command name
command_id (IntEnum) – command id
- class spinetoolbox.project_item.specification_editor_window.SpecificationEditorWindowBase(toolbox, specification=None, item=None)[source]
Bases:
PySide6.QtWidgets.QMainWindow
Base class for spec editors.
- Parameters
toolbox (ToolboxUI) – QMainWindow instance
specification (ProjectItemSpecification, optional) – If given, the form is pre-filled with this specification
item (ProjectItem, optional) – Sets the spec for this item if accepted
- _restore_dock_widgets()[source]
Restores dockWidgets to some default state. Called in the constructor, before restoring the ui from settings. Reimplement in subclasses if needed.
- abstract _make_new_specification(spec_name)[source]
Returns a ProjectItemSpecification from current form settings.
- Parameters
spec_name (str) – Name of the spec
- Returns
ProjectItemSpecification
- spec_toolbar()[source]
Returns spec editor window’s toolbar, which contains e.g. the hamburger menu.
- _save(exiting=None)[source]
Saves spec.
- Parameters
exiting (bool, optional) – Set as True if called when trying to exit the editor window
- Returns
True if operation was successful, False otherwise
- Return type
bool
- class spinetoolbox.project_item.specification_editor_window._SpecNameDescriptionToolbar(parent, spec, undo_stack)[source]
Bases:
PySide6.QtWidgets.QToolBar
QToolBar for line edits and a hamburger menu.
- Parameters
parent (QMainWindow) – QMainWindow instance
spec (ProjectItemSpecification) – specification that is being edited
undo_stack (QUndoStack) – an undo stack
- _update_name(name)[source]
Pushes a command to undo stack that updates the specification name.
- Parameters
name (str) – updated name
- spinetoolbox.project_item.specification_editor_window.prompt_to_save_changes(parent, settings, save_callback, exiting=None)[source]
Prompts to save changes.
- Parameters
parent (QWidget) – Spec editor widget
settings (QSettings) – Toolbox settings
save_callback (Callable) – A function to call if the user chooses Save. It must return True or False depending on the outcome of the ‘saving’.
exiting (bool, optional) – Set as True if called when trying to exit the editor window
- Returns
False if the user chooses to cancel, in which case we don’t close the form.
- Return type
bool
spinetoolbox.server
Package for handling the client part of executing projects on Spine Engine Server.
Submodules
spinetoolbox.server.engine_client
Client for exchanging messages between the toolbox and the Spine Engine Server.
Generic enumeration. |
|
|
- class spinetoolbox.server.engine_client.ClientSecurityModel[source]
Bases:
enum.Enum
Generic enumeration.
Derive from this class to define new enumerations.
- class spinetoolbox.server.engine_client.EngineClient(host, port, sec_model, sec_folder, ping=True)[source]
- Parameters
host (str) – IP address of the Spine Engine Server
port (int) – Port of the client facing (frontend) socket on Spine Engine Server
sec_model (ClientSecurityModel) – Client security scheme
sec_folder (str) – Path to security file directory
ping (bool) – Whether to check connectivity at instance creation
- connect_pull_socket(port)[source]
Connects a PULL socket for receiving engine execution events and files from server.
- Parameters
port (str) – Port of the PUSH socket on server
- rcv_next(dealer_or_pull)[source]
Polls all sockets and returns a new reply based on given socket ‘name’.
- Parameters
dealer_or_pull (str) – “dealer” to wait reply from DEALER socket, “pull” to wait reply from PULL socket
- _check_connectivity(timeout)[source]
Pings server, waits for the response, and acts accordingly.
- Parameters
timeout (int) – Time to wait for a response before giving up [ms]
- Returns
void
- Raises
RemoteEngineInitFailed if the server is not responding. –
- set_start_time()[source]
Sets a start time for an operation. Call get_elapsed_time() after an operation has finished to get the elapsed time string.
- upload_project(project_dir_name, fpath)[source]
Uploads the zipped project file to server. Project zip file must be ready and the server available before calling this method.
- Parameters
project_dir_name (str) – Project directory name
fpath (str) – Absolute path to zipped project file.
- Returns
Project execution job Id
- Return type
str
- start_execution(engine_data, job_id)[source]
Sends the start execution request along with job Id and engine (dag) data to the server. Response message data contains the push/pull socket port if execution starts successfully.
- Parameters
engine_data (str) – Input for SpineEngine as JSON str. Includes most of project.json, settings, etc.
job_id (str) – Project execution job Id on server
- Returns
Response tuple (event_type, data). Event_type is “server_init_failed”, “remote_execution_init_failed” or “remote_execution_started. data is an error message or the publish and push sockets ports concatenated with ‘:’.
- Return type
tuple
- stop_execution(job_id)[source]
Sends a request to stop executing the DAG that is managed by this client.
- Parameters
job_id (str) – Job Id on server to stop
- answer_prompt(job_id, prompter_id, answer)[source]
Sends a request to answer a prompt from the DAG that is managed by this client.
- Parameters
job_id (str) – Job Id on server to stop
prompter_id (int) –
answer –
- save_downloaded_file(b_rel_path, file_data)[source]
Saves downloaded file to project directory.
- Parameters
b_rel_path (bytes) – Relative path (to project dir) where the file should be saved
file_data (bytes) – File as bytes object
- retrieve_project(job_id)[source]
Retrieves a zipped project file from server.
- Parameters
job_id (str) – Job Id for finding the project directory on server
- Returns
Zipped project file
- Return type
bytes
- remove_project_from_server(job_id)[source]
Sends a request to remove a project directory from server.
- Parameters
job_id (str) – Job Id for finding the project directory on server
- Returns
Message from server
- Return type
str
- send_is_complete(persistent_key, cmd)[source]
Sends a request to process is_complete(cmd) in persistent manager on server and returns the response.
- send_issue_persistent_command(persistent_key, cmd)[source]
Sends a request to process given command in persistent manager identified by given key. Yields the response string(s) as they arrive from server.
- send_get_persistent_completions(persistent_key, text)[source]
Requests completions to given text from persistent execution backend.
- send_get_persistent_history_item(persistent_key, text, prefix, backwards)[source]
Requests the former or latter history item from persistent execution backend.
- send_restart_persistent(persistent_key)[source]
Sends restart persistent cmd to persistent execution manager backend on server. Yields the messages resulting from this operation to persistent console client.
- send_interrupt_persistent(persistent_key)[source]
Sends interrupt persistent cmd to persistent execution manager backend on server.
- send_kill_persistent(persistent_key)[source]
Sends kill persistent cmd to persistent execution manager backend on server.
- Parameters
persistent_key (tuple) – persistent manager identifier
- send_request_to_persistent(data)[source]
Sends given data containing persistent_key, command, cmd_to_persistent to Spine Engine Server to be processed by a persistent execution manager backend. Makes a request using REQ socket, parses the response into a ServerMessage, and returns the second part of the data field.
- send_request_to_persistent_generator(data)[source]
Pulls all messages from server, that were the result of sending given data to Spine Engine Server.
spinetoolbox.spine_db_editor
This subpackage contains GUI files for the Spine db editor.
Subpackages
spinetoolbox.spine_db_editor.mvcmodels
Modules in this package contain classes that represent Spine Toolbox’s models (internal data structures) in the Model-View-Controller design pattern. The model classes define an interface that is used by views and delegates to access data in the application.
spinetoolbox.spine_db_editor.mvcmodels.alternative_item
Classes to represent items in an alternative tree.
A root item representing a db. |
|
An alternative leaf item. |
- class spinetoolbox.spine_db_editor.mvcmodels.alternative_item.DBItem(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardDBItem
A root item representing a db.
- class spinetoolbox.spine_db_editor.mvcmodels.alternative_item.AlternativeItem(model, identifier=None)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EditableMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem
An alternative leaf item.
- Parameters
model (MinimalTreeModel) –
identifier (int, optional) – item’s database id
spinetoolbox.spine_db_editor.mvcmodels.alternative_model
Contains alternative tree model.
A model to display alternatives in a tree view. |
- class spinetoolbox.spine_db_editor.mvcmodels.alternative_model.AlternativeModel(db_editor, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_model_base.TreeModelBase
A model to display alternatives in a tree view.
- Parameters
db_editor (SpineDBEditor) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
- mimeData(indexes)[source]
Stores selected indexes into MIME data.
The MIME data structure contains two distinct data:
Text representation of the selection
A pickled dict mapping db identifier to list of alternative ids
- Parameters
indexes (Sequence of QModelIndex) – selected indexes
- Returns
MIME data
- Return type
QMimeData
- paste_alternative_mime_data(mime_data, database_item)[source]
Pastes alternatives from mime data into model.
- Parameters
mime_data (QMimeData) – mime data
database_item (alternative_item.DBItem) – target database item
spinetoolbox.spine_db_editor.mvcmodels.colors
Color constants for models.
spinetoolbox.spine_db_editor.mvcmodels.compound_models
Compound models. These models concatenate several ‘single’ models and one ‘empty’ model.
A base model for all models that show data in stacked format. |
|
Provides the interface to filter by entity and alternative. |
|
Provides the interface to edit values via ParameterValueEditor. |
|
A model that concatenates several single parameter_definition models and one empty parameter_definition model. |
|
A model that concatenates several single parameter_value models and one empty parameter_value model. |
|
Provides the interface to filter by entity and alternative. |
- class spinetoolbox.spine_db_editor.mvcmodels.compound_models.CompoundModelBase(parent, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.mvcmodels.compound_table_model.CompoundWithEmptyTableModel
A base model for all models that show data in stacked format.
- Parameters
parent (SpineDBEditor) – the parent object
db_mngr (SpineDBManager) – the database manager
*db_maps (DatabaseMapping) – the database maps included in the model
- abstract property _single_model_type[source]
Returns a constructor for the single models.
- Returns
SingleParameterModel
- abstract property _empty_model_type[source]
Returns a constructor for the empty model.
- Returns
EmptyParameterModel
- canFetchMore(_parent)[source]
Returns True if any of the submodels that haven’t been fetched yet can fetch more.
Returns auto filter menu for given logical index from header view.
- Parameters
logical_index (int) –
- Returns
AutoFilterMenu
- headerData(section, orientation=Qt.Orientation.Horizontal, role=Qt.ItemDataRole.DisplayRole)[source]
Returns an italic font in case the given column has an autofilter installed.
- _create_empty_model()[source]
Returns the empty model for this compound model.
- Returns
EmptyParameterModel
- filter_accepts_model(model)[source]
Returns a boolean indicating whether the given model passes the filter for compound model.
- Parameters
model (SingleModelBase or EmptyModelBase) –
- Returns
bool
- accepted_single_models()[source]
Returns a list of accepted single models by calling filter_accepts_model on each of them, just for convenience.
- Returns
list
- set_auto_filter(field, values)[source]
Updates and applies the auto filter.
- Parameters
field (str) – the field name
values (dict) – mapping (db_map, entity_class_id) to set of valid values
- _set_compound_auto_filter(field, values)[source]
Sets the auto filter for given column in the compound model.
- Parameters
field (str) – the field name
values (set) – set of valid (db_map, item_type, id) tuples
- _set_single_auto_filter(model, field)[source]
Sets the auto filter for given column in the given single model.
- Parameters
model (SingleParameterModel) – the model
field (str) – the field name
- Returns
True if the auto-filtered values were updated, None otherwise
- Return type
bool
- _row_map_iterator_for_model(model)[source]
Yields row map for the given model. Reimplemented to take filter status into account.
- Parameters
model (SingleParameterModel, EmptyParameterModel) –
- Yields
tuple – (model, row number) for each accepted row
- _models_with_db_map(db_map)[source]
Returns a collection of single models with given db_map.
- Parameters
db_map (DatabaseMapping) –
- Returns
list
- static _items_per_class(items)[source]
Returns a dict mapping entity_class ids to a set of items.
- Parameters
items (list) –
- Returns
dict
- handle_items_added(db_map_data)[source]
Runs when either parameter definitions or values are added to the dbs. Adds necessary sub-models and initializes them with data. Also notifies the empty model so it can remove rows that are already in.
- Parameters
db_map_data (dict) – list of added dict-items keyed by DatabaseMapping
- _add_items(db_map, entity_class_id, ids, committed)[source]
Creates new single model and resets it with the given parameter ids.
- Parameters
db_map (DatabaseMapping) – database map
entity_class_id (int) – parameter’s entity class id
ids (list of int) – parameter ids
committed (bool) – True if the ids have been committed, False otherwise
- handle_items_updated(db_map_data)[source]
Runs when either parameter definitions or values are updated in the dbs. Emits dataChanged so the parameter_name column is refreshed.
- Parameters
db_map_data (dict) – list of updated dict-items keyed by DatabaseMapping
- class spinetoolbox.spine_db_editor.mvcmodels.compound_models.FilterEntityAlternativeMixin(*args, **kwargs)[source]
Provides the interface to filter by entity and alternative.
- class spinetoolbox.spine_db_editor.mvcmodels.compound_models.EditParameterValueMixin[source]
Provides the interface to edit values via ParameterValueEditor.
- class spinetoolbox.spine_db_editor.mvcmodels.compound_models.CompoundParameterDefinitionModel(parent, db_mngr, *db_maps)[source]
Bases:
EditParameterValueMixin
,CompoundModelBase
A model that concatenates several single parameter_definition models and one empty parameter_definition model.
- Parameters
parent (SpineDBEditor) – the parent object
db_mngr (SpineDBManager) – the database manager
*db_maps (DatabaseMapping) – the database maps included in the model
- property _single_model_type[source]
Returns a constructor for the single models.
- Returns
SingleParameterModel
- class spinetoolbox.spine_db_editor.mvcmodels.compound_models.CompoundParameterValueModel(*args, **kwargs)[source]
Bases:
FilterEntityAlternativeMixin
,EditParameterValueMixin
,CompoundModelBase
A model that concatenates several single parameter_value models and one empty parameter_value model.
- property _single_model_type[source]
Returns a constructor for the single models.
- Returns
SingleParameterModel
- class spinetoolbox.spine_db_editor.mvcmodels.compound_models.CompoundEntityAlternativeModel(*args, **kwargs)[source]
Bases:
FilterEntityAlternativeMixin
,CompoundModelBase
Provides the interface to filter by entity and alternative.
- property _single_model_type[source]
Returns a constructor for the single models.
- Returns
SingleParameterModel
spinetoolbox.spine_db_editor.mvcmodels.empty_models
Empty models for parameter definitions and values.
Base class for all empty models that go in a CompoundModelBase subclass. |
|
An empty parameter_definition model. |
|
An empty parameter_value model. |
|
Makes relationships on the fly. |
- class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyModelBase(parent)[source]
Bases:
spinetoolbox.mvcmodels.empty_row_model.EmptyRowModel
Base class for all empty models that go in a CompoundModelBase subclass.
- Parameters
parent (CompoundModelBase) – the parent model
- add_items_to_db(db_map_data)[source]
Add items to db.
- Parameters
db_map_data (dict) – mapping DiffDatabaseMapping instance to list of items
- abstract _make_unique_id(item)[source]
Returns a unique id for the given model item (name-based). Used by handle_items_added to identify which rows have been added and thus need to be removed.
- handle_items_added(db_map_data)[source]
Runs when parameter definitions or values are added. Finds and removes model items that were successfully added to the db.
- batch_set_data(indexes, data)[source]
Sets data for indexes in batch. If successful, add items to db.
- _autocomplete_row(db_map, item)[source]
Fills in entity_class_name whenever other selections make it obvious.
- class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyParameterDefinitionModel(parent)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin
,ParameterMixin
,EmptyModelBase
An empty parameter_definition model.
- Parameters
parent (CompoundModelBase) – the parent model
- class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyParameterValueModel(parent)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.MakeEntityOnTheFlyMixin
,spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin
,ParameterMixin
,EntityMixin
,EmptyModelBase
An empty parameter_value model.
- Parameters
parent (CompoundModelBase) – the parent model
- class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyEntityAlternativeModel(parent)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.MakeEntityOnTheFlyMixin
,EntityMixin
,EmptyModelBase
Makes relationships on the fly.
- Parameters
parent (CompoundModelBase) – the parent model
spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item
Classes to represent entities in a tree.
dict() -> new empty dictionary |
|
dict() -> new empty dictionary |
|
dict() -> new empty dictionary |
|
A tree item that may belong in multiple databases. |
|
An entity_class item. |
|
An entity item. |
- class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityClassIndex[source]
Bases:
spinetoolbox.fetch_parent.FetchIndex
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityGroupIndex[source]
Bases:
spinetoolbox.fetch_parent.FetchIndex
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityIndex[source]
Bases:
spinetoolbox.fetch_parent.FetchIndex
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityTreeRootItem(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item.MultiDBTreeItem
A tree item that may belong in multiple databases.
- Parameters
model (MinimalTreeModel, optional) – item’s model
db_map_ids (dict, optional) – maps instances of DatabaseMapping to the id of the item in that db
- class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityClassItem(model, db_map_ids=None)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item.MultiDBTreeItem
An entity_class item.
- Parameters
model (MinimalTreeModel, optional) – item’s model
db_map_ids (dict, optional) – maps instances of DatabaseMapping to the id of the item in that db
- class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityItem(*args, is_member=False, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item.MultiDBTreeItem
An entity item.
- Parameters
model (MinimalTreeModel, optional) – item’s model
db_map_ids (dict, optional) – maps instances of DatabaseMapping to the id of the item in that db
- property child_item_class[source]
Child class is always
EntityItem
.
- default_parameter_data()[source]
Return data to put as default in a parameter table when this item is selected.
spinetoolbox.spine_db_editor.mvcmodels.entity_tree_models
Models to represent entities in a tree.
Base class for all tree models in Spine db editor. |
|
Groups items from given tree indexes by db map. |
- class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_models.EntityTreeModel(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_model.MultiDBTreeModel
Base class for all tree models in Spine db editor.
Init class.
- Parameters
db_editor (SpineDBEditor) –
db_mngr (SpineDBManager) – A manager for the given db_maps
*db_maps – DatabaseMapping instances
spinetoolbox.spine_db_editor.mvcmodels.frozen_table_model
Contains FrozenTableModel class.
Used by custom_qtableview.FrozenTableView |
- class spinetoolbox.spine_db_editor.mvcmodels.frozen_table_model.FrozenTableModel(db_mngr, parent=None)[source]
Bases:
PySide6.QtCore.QAbstractTableModel
Used by custom_qtableview.FrozenTableView
- Parameters
db_mngr (SpineDBManager) – database manager
parent (QObject, optional) – parent object
- set_headers(headers)[source]
Sets headers for the header row wiping data.
This method does nothing if the new headers are equal to existing ones.
- Parameters
headers (Iterable of str) – headers
- Returns
True if model was reset, False otherwise
- Return type
bool
- add_values(data)[source]
Adds more frozen values that aren’t in the table already.
- Parameters
data (set of tuple) – frozen values
- remove_values(data)[source]
Removes frozen values from the table.
- Parameters
data (set of tuple) – frozen values
- get_selected()[source]
Returns selected row.
- Returns
row index or None if no row is selected
- Return type
int
- get_frozen_value()[source]
Return currently selected frozen value.
- Returns
frozen value
- Return type
tuple
- insert_column_data(header, values, column)[source]
Inserts new column with given header.
- Parameters
header (str) – frozen header
values (set of tuple) – column’s values
column (int) – position
- remove_column(column)[source]
Removes column and makes rows unique.
- Parameters
column (int) – column to remove
- _unique_values()[source]
Turns non-header data into sets of unique values on each column.
- Returns
each column’s unique values
- Return type
list of set
- _find_first(row_data, mask_column=None)[source]
Finds first row that matches given row data.
- Parameters
row_data (tuple) – row data to search for
mask_column (int, optional) – ignored column
- Returns
row index
- Return type
int
spinetoolbox.spine_db_editor.mvcmodels.item_metadata_table_model
Contains ItemMetadataTableModel
and associated functionality.
Identifiers for hidden table columns. |
|
Allowed item types. |
|
Model for entity and parameter value metadata. |
- class spinetoolbox.spine_db_editor.mvcmodels.item_metadata_table_model.ExtraColumn[source]
Bases:
enum.IntEnum
Identifiers for hidden table columns.
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.spine_db_editor.mvcmodels.item_metadata_table_model.ItemType[source]
Bases:
enum.Enum
Allowed item types.
- class spinetoolbox.spine_db_editor.mvcmodels.item_metadata_table_model.ItemMetadataTableModel(db_mngr, db_maps, db_editor)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base.MetadataTableModelBase
Model for entity and parameter value metadata.
- Parameters
db_mngr (SpineDBManager) – database manager
db_maps (Iterable of DatabaseMapping) – database maps
db_editor (SpineDBEditor) – DB editor
See base class.
- set_entity_ids(db_map_ids)[source]
Sets the model to show metadata from given entity.
- Parameters
db_map_ids (dict) – mapping from database mapping to entity’s id in that database
- set_parameter_value_ids(db_map_ids)[source]
Sets the model to show metadata from given parameter value.
- Parameters
db_map_ids (dict) – mapping from database mapping to value’s id in that database
- _reset_metadata(item_type, db_map_ids)[source]
Resets model.
- Parameters
item_type (ItemType) – current item type
db_map_ids (dict) – mapping from database mapping to value’s id in that database
- add_item_metadata(db_map_data)[source]
Adds new item metadata from database manager to the model.
- Parameters
db_map_data (dict) – added items keyed by database mapping
spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model
Contains MetadataTableModel
and associated functionality.
Identifiers for hidden table columns. |
|
Model for metadata. |
- class spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model.ExtraColumn[source]
Bases:
enum.IntEnum
Identifiers for hidden table columns.
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model.MetadataTableModel(db_mngr, db_maps, db_editor)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base.MetadataTableModelBase
Model for metadata.
- Parameters
db_mngr (SpineDBManager) – database manager
db_maps (Iterable of DatabaseMapping) – database maps
db_editor (SpineDBEditor) – DB editor
See base class.
- add_metadata(db_map_data)[source]
Adds new metadata from database manager to the model.
- Parameters
db_map_data (dict) – added metadata items keyed by database mapping
spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base
Contains base class for metadata table models associated functionality.
Identifiers for visible table columns. |
|
Base for metadata table models |
- class spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base.Column[source]
Bases:
enum.IntEnum
Identifiers for visible table columns.
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base.MetadataTableModelBase(db_mngr, db_maps, db_editor)[source]
Bases:
PySide6.QtCore.QAbstractTableModel
Base for metadata table models
- Parameters
db_mngr (SpineDBManager) – database manager
db_maps (Iterable of DatabaseMapping) – database maps
db_editor (SpineDBEditor) – DB editor
- classmethod _make_adder_row(default_db_map)[source]
Generates a new empty last row.
- Parameters
default_db_map (DiffDatabaseMapping) – initial database mapping
- Returns
empty row
- Return type
list
Creates hidden extra columns for adder row.
- Returns
extra columns
- Return type
list
- set_db_maps(db_maps)[source]
Changes current database mappings.
- Parameters
db_maps (Iterable of DiffDatabaseMapping) – database mappings
- abstract _add_data_to_db_mngr(name, value, db_map)[source]
Tells database manager to start adding data.
- Parameters
name (str) – metadata name
value (str) – metadata value
db_map (DiffDatabaseMapping) – database mapping
- abstract _update_data_in_db_mngr(id_, name, value, db_map)[source]
Tells database manager to start updating data.
- Parameters
id (int) – database id
name (str) – metadata name
value (str) – metadata value
db_map (DiffDatabaseMapping) – database mapping
- batch_set_data(indexes, values)[source]
Sets data in multiple indexes simultaneously.
- Parameters
indexes (Iterable of QModelIndex) – indexes to set
values (Iterable of str) – values corresponding to indexes
- abstract _database_table_name()[source]
Returns primary database table name.
- Returns
table name
- Return type
str
- abstract _row_id(row)[source]
Returns a unique row id.
- Parameters
row (list) – data table row
- Returns
id or None
- Return type
int
- abstract static _ids_from_added_item(item)[source]
Returns ids that uniquely identify an added database item.
- Parameters
item (dict) – added item
- Returns
unique identifier
- Return type
Any
- abstract static _extra_cells_from_added_item(item)[source]
Constructs extra cells for data row from added database item.
- Parameters
item (dict) – added item
- Returns
extra cells
- Return type
list
- abstract _set_extra_columns(row, ids)[source]
Sets extra columns for data row.
- Parameters
row (list) – data row
ids (Any) –
- _add_data(db_map_data)[source]
Adds new data from database manager to the model.
- Parameters
db_map_data (dict) – added items keyed by database mapping
- _update_data(db_map_data, id_column)[source]
Update data table after database update.
- Parameters
db_map_data (dict) – updated items keyed by database mapping
id_column (int) – column that contains item ids
- _remove_data(db_map_data, id_column)[source]
Removes data from model after it has been removed from databases.
- Parameters
db_map_data (dict) – removed items keyed by database mapping
id_column (int) – column that contains item ids
spinetoolbox.spine_db_editor.mvcmodels.mime_types
Contains mime types used by the models.
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item
Base classes to represent items from multiple databases in a tree.
A tree item that may belong in multiple databases. |
- class spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item.MultiDBTreeItem(model, db_map_ids=None)[source]
Bases:
spinetoolbox.mvcmodels.minimal_tree_model.TreeItem
A tree item that may belong in multiple databases.
- Parameters
model (MinimalTreeModel, optional) – item’s model
db_map_ids (dict, optional) – maps instances of DatabaseMapping to the id of the item in that db
- property display_id[source]
Returns an id for display based on the display key. This id must be the same across all db_maps. If it’s not, this property becomes None and measures need to be taken (see update_children_by_id).
- property display_icon[source]
Returns an icon to display next to the name. Reimplement in subclasses to return something nice.
- child_number()[source]
Overriden to use find_row which is a dict-lookup rather than a list.index() call.
- abstract set_data(column, value, role)[source]
Sets data for this item.
- Parameters
column (int) – column index
value (object) – a new value
role (int) – role of the new value
- Returns
True if data was set successfully, False otherwise
- Return type
bool
- deep_refresh_children()[source]
Refreshes children after taking db_maps from them. Called after removing and updating children for this item.
- deep_take_db_map(db_map)[source]
Removes given db_map from this item and all its descendants, and returns a new item from the db_map’s data.
- Returns
MultiDBTreeItem, NoneType
- db_map_data(db_map)[source]
Returns data for this item in given db_map or an empty dict if not present.
- db_map_data_field(db_map, field, default=None)[source]
Returns field from data for this item in given db_map or None if not found.
- _create_new_children(db_map, children_ids, **kwargs)[source]
Creates new items from ids associated to a db map.
- Parameters
db_map (DiffDatabaseMapping) – create children for this db_map
children_ids (iter) – create children from these ids
- Returns
new children
- Return type
list of MultiDBTreeItem
- make_or_restore_child(db_map, id_, **kwargs)[source]
Makes or restores a child if one was ever made using given db_map and id. The purpose of restoring is to keep using the same FetchParent, which is useful in case the user undoes a series of removal operations that would add items in cascade to the tree.
- Parameters
db_map (DatabaseMapping) –
id (int) –
- Returns
MultiDBTreemItem
- _merge_children(new_children)[source]
Merges new children into this item. Ensures that each child has a valid display id afterwards.
- append_children_by_id(db_map_ids, **kwargs)[source]
Appends children by id.
- Parameters
db_map_ids (dict) – maps DiffDatabaseMapping instances to list of ids
- remove_children_by_id(db_map_ids)[source]
Removes children by id.
- Parameters
db_map_ids (dict) – maps DiffDatabaseMapping instances to list of ids
- update_children_by_id(db_map_ids, **kwargs)[source]
Updates children by id. Essentially makes sure all children have a valid display id after updating the underlying data. These may require ‘splitting’ a child into several for different dbs or merging two or more children from different dbs.
Examples of problems:
The user renames an object_class in one db but not in the others –> we need to split
The user renames an object_class and the new name is already ‘taken’ by another object_class in another db_map –> we need to merge
- Parameters
db_map_ids (dict) – maps DiffDatabaseMapping instances to list of ids
- insert_children(position, children)[source]
Inserts new children at given position.
- Parameters
position (int) – insert new items here
children (Iterable of MultiDBTreeItem) – insert items from this iterable
- Returns
True if children were inserted successfully, False otherwise
- Return type
bool
- find_children_by_id(db_map, *ids, reverse=True)[source]
Generates children with the given ids in the given db_map. If the first id is None, then generates all children with the given db_map.
- _find_unsorted_rows_by_id(db_map, *ids)[source]
Generates rows corresponding to children with the given ids in the given db_map. If the only id given is None, then generates rows corresponding to all children with the given db_map.
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_model
A base model class to represent items from multiple databases in a tree.
Base class for all tree models in Spine db editor. |
- class spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_model.MultiDBTreeModel(db_editor, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.mvcmodels.minimal_tree_model.MinimalTreeModel
Base class for all tree models in Spine db editor.
Init class.
- Parameters
db_editor (SpineDBEditor) –
db_mngr (SpineDBManager) – A manager for the given db_maps
*db_maps – DatabaseMapping instances
spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item
Tree items for parameter_value lists.
An item representing a db. |
|
A list item. |
|
Paints the item gray if it's the last. |
- class spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item.DBItem(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardDBItem
An item representing a db.
- class spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item.ListItem(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EditableMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.SortChildrenMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.BoldTextMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem
A list item.
- class spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item.ValueItem(model, identifier=None)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EditableMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem
Paints the item gray if it’s the last.
- Parameters
model (MinimalTreeModel) –
identifier (int, optional) – item’s database id
spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_model
A tree model for parameter_value lists.
A model to display parameter_value_list data in a tree view. |
- class spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_model.ParameterValueListModel(db_editor, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_model_base.TreeModelBase
A model to display parameter_value_list data in a tree view.
- Parameters
db_editor (SpineDBEditor) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
spinetoolbox.spine_db_editor.mvcmodels.pivot_model
Provides PivotModel.
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_model.PivotModel[source]
-
- reset_model(data, top_left_headers=(), rows=(), columns=(), frozen=(), frozen_value=())[source]
Resets the model.
- add_to_model(data)[source]
Adds data to model.
- Parameters
data (dict) – pivot model data
- Returns
added row count and added column count
- Return type
tuple
- frozen_values(data)[source]
Collects frozen values from data.
- Parameters
data (dict) – pivot model data
- Returns
frozen values
- Return type
set of tuple
- _check_pivot(rows, columns, frozen, frozen_value)[source]
Checks if given pivot is valid.
- Returns
error message or None if no error
- Return type
str, NoneType
- _index_key_getter(indexes)[source]
Returns an itemgetter that always returns tuples from list of indexes
- Parameters
indexes (tuple) –
- Returns
an itemgetter
- Return type
Callable
- _get_unique_index_values(indexes)[source]
Returns unique indexes that match the frozen condition.
- Parameters
indexes (tuple) – indexes to match
- Returns
unique indexes
- Return type
list
- set_frozen_value(value)[source]
Sets values for the frozen indexes.
- Parameters
value (tuple of str) –
- set_frozen(frozen)[source]
Sets the frozen names without resetting the pivot.
- Parameters
frozen (Iterable of str) –
spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models
Provides pivot table models for the Tabular View.
Base class for all 'top left pivot headers'. |
|
A top left header for an entity class. |
|
A top left header for parameter_definition. |
|
A top left header for parameter index. |
|
A top left header for alternative. |
|
A top left header for scenario. |
|
A top left header for database. |
|
|
|
A model for the pivot table in parameter_value input type. |
|
A model for the pivot table in parameter index expansion input type. |
|
A model for the pivot table in element input type. |
|
A model for the pivot table in scenario alternative input type. |
|
Initialize class. |
|
Returns a function to compute the db_map-id tuple of an item. |
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftHeaderItem(model)[source]
Base class for all ‘top left pivot headers’. Represents a header located in the top left area of the pivot table.
- Parameters
model (PivotTableModelBase) –
- static accepts(header_id)[source]
Tests if header id is valid.
- Parameters
header_id (Any) – header id
- Returns
True if id is valid, False otherwise
- Return type
bool
- abstract header_data(header_id, role=Qt.ItemDataRole.DisplayRole)[source]
Returns header data for given id.
- Parameters
header_id (Any) – header id
role (Qt.ItemDataRole) – data role
- Returns
data corresponding to role
- Return type
Any
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftEntityHeaderItem(model, rank, class_name, class_id)[source]
Bases:
TopLeftHeaderItem
A top left header for an entity class.
- Parameters
model (PivotTableModelBase) –
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftParameterHeaderItem(model)[source]
Bases:
TopLeftHeaderItem
A top left header for parameter_definition.
- Parameters
model (PivotTableModelBase) –
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftParameterIndexHeaderItem(model)[source]
Bases:
TopLeftHeaderItem
A top left header for parameter index.
- Parameters
model (PivotTableModelBase) –
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftAlternativeHeaderItem(model)[source]
Bases:
TopLeftHeaderItem
A top left header for alternative.
- Parameters
model (PivotTableModelBase) –
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftScenarioHeaderItem(model)[source]
Bases:
TopLeftHeaderItem
A top left header for scenario.
- Parameters
model (PivotTableModelBase) –
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftDatabaseHeaderItem(model)[source]
Bases:
TopLeftHeaderItem
A top left header for database.
- Parameters
model (PivotTableModelBase) –
- set_data(codename)[source]
Sets database mapping’s codename.
- Parameters
codename (str) – database codename
- Returns
True if codename was acceptable, False otherwise
- Return type
bool
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.PivotTableModelBase(db_editor)[source]
Bases:
PySide6.QtCore.QAbstractTableModel
- Parameters
db_editor (SpineDBEditor) –
- property plot_x_column[source]
Returns the index of the column designated as Y values for plotting or None.
- abstract call_reset_model(pivot=None)[source]
- Parameters
pivot (tuple, optional) – list of rows, list of columns, list of frozen indexes, frozen value
- update_model(data)[source]
Update model with new data, but doesn’t grow the model.
- Parameters
data (dict) –
- set_frozen(frozen)[source]
Sets the order of frozen headers without changing model data.
- Parameters
frozen (list of str) – new frozen
- set_frozen_value(frozen_value)[source]
Sets frozen value resetting the model.
- Parameters
frozen_value (tuple) – frozen value
- Returns
True if value was set, False otherwise
- Return type
bool
- x_value(index)[source]
Returns x value for given model index.
- Parameters
index (QModelIndex) – model index
- Returns
x value
- Return type
Any
- x_parameter_name()[source]
Returns x column’s parameter name.
- Returns
parameter name
- Return type
str
- rowCount(parent=QModelIndex())[source]
Number of rows in table, number of header rows + datarows + 1 empty row
- columnCount(parent=QModelIndex())[source]
Number of columns in table, number of header columns + datacolumns + 1 empty columns
- top_left_indexes()[source]
Returns indexes in the top left area.
- Returns
list(QModelIndex): top indexes (horizontal headers, associated to rows) list(QModelIndex): left indexes (vertical headers, associated to columns)
- index_in_top_left(index)[source]
Returns whether the given index is in top left corner, where pivot names are displayed.
- index_in_column_headers(index)[source]
Returns whether the given index is in column headers (horizontal) area.
- index_in_row_headers(index)[source]
Returns whether the given index is in row headers (vertical) area.
- index_in_empty_column_headers(index)[source]
Returns whether the given index is in empty column headers (vertical) area.
- index_in_empty_row_headers(index)[source]
Returns whether the given index is in empty row headers (vertical) area.
- column_is_index_column(column)[source]
Returns True if column is the column containing expanded parameter_value indexes.
- map_to_pivot(index)[source]
Returns a tuple of row and column in the pivot model that corresponds to the given model index.
- Parameters
index (QModelIndex) –
- Returns
row int: column
- Return type
int
- top_left_id(index)[source]
Returns the id of the top left header corresponding to the given header index.
- Parameters
index (QModelIndex) –
- Returns
int, NoneType
- _header_id(index)[source]
Returns the id of the given row or column header index.
- Parameters
index (QModelIndex) –
- Returns
tuple or DatabaseMapping or NoneType
- _header_ids(row, column)[source]
Returns the ids for the headers at given row and column.
- Parameters
row (int) –
column (int) –
- Returns
tuple(int)
- header_name(index)[source]
Returns the name corresponding to the given header index. Used by PivotTableView.
- Parameters
index (QModelIndex) –
- Returns
str
- get_db_map_entities()[source]
Returns a dict mapping db maps to a list of dict entity items in the current class.
- Returns
dict
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.ParameterValuePivotTableModel(parent)[source]
Bases:
PivotTableModelBase
A model for the pivot table in parameter_value input type.
- Parameters
parent (SpineDBEditor) –
- _load_empty_parameter_value_data(db_map_entities=None, db_map_parameter_ids=None, db_map_alternative_ids=None)[source]
Returns a dict containing all possible combinations of entities and parameters for the current class in all db_maps.
- Parameters
db_map_entities (dict, optional) – if given, only load data for these db maps and entities
db_map_parameter_ids (dict, optional) – if given, only load data for these db maps and parameter definitions
db_map_alternative_ids (dict, optional) – if given, only load data for these db maps and alternatives
- Returns
Key is a tuple object_id, …, parameter_id, value is None.
- Return type
dict
- _all_combination_for_empty_parameter_value(db_map_entities, db_map_parameter_ids, db_map_alternative_ids)[source]
- _load_full_parameter_value_data(db_map_parameter_values=None, action='add')[source]
Returns a dict of parameter values for the current class.
- Parameters
db_map_parameter_values (list, optional) –
action (str) –
- Returns
Key is a tuple object_id, …, parameter_id, value is the parameter_value.
- Return type
dict
- db_map_entity_ids(indexes)[source]
Returns db_map and entity ids for given indexes. Used by PivotTableView.
- Parameters
indexes (list of QModelIndex) – indexes corresponding to entity items
- Returns
mapping DatabaseMapping to set of entity ids
- Return type
dict
- all_header_names(index)[source]
Returns the entity, parameter, alternative, and db names corresponding to the given data index.
- Parameters
index (QModelIndex) –
- Returns
object names str: parameter name str: alternative name str: db name
- Return type
list(str)
- index_name(index)[source]
Returns a string that concatenates the object and parameter names corresponding to the given data index. Used by plotting and ParameterValueEditor.
- Parameters
index (QModelIndex) –
- Returns
str
- column_name(column)[source]
Returns a string that concatenates the object and parameter names corresponding to the given column. Used by plotting.
- Parameters
column (int) –
- Returns
str
- _batch_set_parameter_value_data(row_map, column_map, data, values)[source]
Sets parameter values in batch.
- get_set_data_delayed(index)[source]
Returns a function that ParameterValueEditor can call to set data for the given index at any later time, even if the model changes.
- Parameters
index (QModelIndex) –
- Returns
function
- _get_db_map_parameter_value_or_def_ids(item_type)[source]
Returns a dict mapping db maps to a list of integer parameter (value or def) ids from the current class.
- Parameters
item_type (str) – either “parameter_value” or “parameter_definition”
- Returns
dict
- _get_db_map_parameter_values_or_defs(item_type)[source]
Returns a dict mapping db maps to list of dict parameter (value or def) items from the current class.
- Parameters
item_type (str) – either “parameter_value” or “parameter_definition”
- Returns
dict
- load_full_parameter_value_data(db_map_parameter_values=None, action='add')[source]
Returns a dict of parameter values for the current class.
- Parameters
db_map_parameter_values (list, optional) –
action (str) –
- Returns
Key is a tuple object_id, …, parameter_id, value is the parameter_value.
- Return type
dict
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.IndexExpansionPivotTableModel(parent)[source]
Bases:
ParameterValuePivotTableModel
A model for the pivot table in parameter index expansion input type.
- Parameters
parent (SpineDBEditor) –
- column_is_index_column(column)[source]
Returns True if column is the column containing expanded parameter_value indexes.
- _load_empty_parameter_value_data(db_map_entities=None, db_map_parameter_ids=None, db_map_alternative_ids=None)[source]
Does not load the data since adding values in index expansion mode is disabled.
- Parameters
db_map_entities (dict, optional) – mapping from database map to iterable of entity items
db_map_parameter_ids (dict, optional) – mapping from database map to iterable of parameter definition id tuples
db_map_alternative_ids (dict, optional) – mapping from database map to iterable of alternative id tuples
- Returns
empty data
- Return type
dict
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.ElementPivotTableModel(parent)[source]
Bases:
PivotTableModelBase
A model for the pivot table in element input type.
- Parameters
parent (SpineDBEditor) –
- _load_full_element_data(db_map_entities=None, action='add')[source]
Returns a dict of entity elements in the current class.
- Parameters
db_map_entities (dict, optional) – a mapping from database map to entities in the current entity class
action (str) – ‘add’ or ‘remove’
- Returns
Key is db_map-object id tuple, value is relationship id.
- Return type
dict
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.ScenarioAlternativePivotTableModel(parent)[source]
Bases:
PivotTableModelBase
A model for the pivot table in scenario alternative input type.
- Parameters
parent (SpineDBEditor) –
- class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.PivotTableSortFilterProxy(parent=None)[source]
Bases:
PySide6.QtCore.QSortFilterProxyModel
Initialize class.
- set_filter(identifier, filter_value)[source]
Sets filter for a given index (object_class) name.
- Parameters
identifier (int) – index identifier
filter_value (set, None) – A set of accepted values, or None if no filter (all pass)
- filterAcceptsRow(source_row, source_parent)[source]
Returns true if the item in the row indicated by the given source_row and source_parent should be included in the model; otherwise returns false.
spinetoolbox.spine_db_editor.mvcmodels.scenario_item
Classes to represent items in scenario tree.
A root item representing a db. |
|
A scenario leaf item. |
|
A scenario alternative leaf item. |
- class spinetoolbox.spine_db_editor.mvcmodels.scenario_item.ScenarioDBItem(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardDBItem
A root item representing a db.
- class spinetoolbox.spine_db_editor.mvcmodels.scenario_item.ScenarioItem(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EditableMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.BoldTextMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem
A scenario leaf item.
- class spinetoolbox.spine_db_editor.mvcmodels.scenario_item.ScenarioAlternativeItem(model, identifier=None)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EditableMixin
,spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem
A scenario alternative leaf item.
- Parameters
model (MinimalTreeModel) –
identifier (int, optional) – item’s database id
spinetoolbox.spine_db_editor.mvcmodels.scenario_model
Contains scenario tree model.
A model to display scenarios in a tree view. |
- class spinetoolbox.spine_db_editor.mvcmodels.scenario_model.ScenarioModel(db_editor, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.tree_model_base.TreeModelBase
A model to display scenarios in a tree view.
- Parameters
db_editor (SpineDBEditor) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
- mimeData(indexes)[source]
Stores selected indexes into MIME data.
If indexes contains scenario indexes, only those indexes will be kept. Otherwise, only scenario alternative indexes are kept.
The MIME data contains distinct data: - Text representation of the selection - A pickled dict mapping db identifier to list of alternative ids - A pickled dict mapping db identifier to list of scenario ids
- Parameters
indexes (Sequence of QModelIndex) – selected indexes
- Returns
MIME data or None if selection was bad
- Return type
QMimeData
- paste_alternative_mime_data(mime_data, row, scenario_item)[source]
Adds alternatives from MIME data to the model.
- Parameters
mime_data (QMimeData) – mime data that must contain ALTERNATIVE_DATA format
row (int) – where to paste within scenario item, -1 lets the model choose
scenario_item (ScenarioItem) – parent item
- paste_scenario_mime_data(mime_data, db_item)[source]
Adds scenarios and their alternatives from MIME data to the model.
- Parameters
mime_data (QMimeData) – mime data that must contain ALTERNATIVE_DATA format
db_item (ScenarioDBItem) – parent item
- duplicate_scenario(scenario_item)[source]
Duplicates scenario within database.
- Parameters
scenario_item (ScenarioItem) – scenario item to duplicate
spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins
Miscellaneous mixins for parameter models.
Base class for all mixins that convert model items (name-based) into database items (id-based). |
|
Base class for all mixins that convert model items (name-based) into database items (id-based). |
|
Makes relationships on the fly. |
- class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.ConvertToDBMixin[source]
Base class for all mixins that convert model items (name-based) into database items (id-based).
- class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin[source]
Bases:
ConvertToDBMixin
Base class for all mixins that convert model items (name-based) into database items (id-based).
- class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.MakeEntityOnTheFlyMixin[source]
Bases:
ConvertToDBMixin
Makes relationships on the fly.
- static _make_entity_on_the_fly(item, db_map)[source]
Returns a database entity item (id-based) from the given model parameter_value item (name-based).
- Parameters
item (dict) – the model parameter_value item
db_map (DiffDatabaseMapping) – the database where the resulting item belongs
- Returns
the db entity item list: error log
- Return type
dict
spinetoolbox.spine_db_editor.mvcmodels.single_models
Single models for parameter definitions and values (as ‘for a single entity’).
Table model for outlining simple tabular data. |
|
Base class for all single models that go in a CompoundModelBase subclass. |
|
Provides the interface to filter by entity and alternative. |
|
Provides the data method for parameter values and definitions. |
|
A parameter_definition model for a single entity_class. |
|
A parameter_value model for a single entity_class. |
|
An entity_alternative model for a single entity_class. |
- class spinetoolbox.spine_db_editor.mvcmodels.single_models.HalfSortedTableModel(parent=None, header=None, lazy=True)[source]
Bases:
spinetoolbox.mvcmodels.minimal_table_model.MinimalTableModel
Table model for outlining simple tabular data.
- Parameters
parent (QObject, optional) – the parent object
header (list of str) – header labels
lazy (boolean) – if True, fetches data lazily
- class spinetoolbox.spine_db_editor.mvcmodels.single_models.SingleModelBase(parent, db_map, entity_class_id, committed, lazy=False)[source]
Bases:
HalfSortedTableModel
Base class for all single models that go in a CompoundModelBase subclass.
- Parameters
parent (CompoundModelBase) – the parent model
db_map (DatabaseMapping) –
entity_class_id (int) –
committed (bool) –
- item_id(row)[source]
Returns parameter id for row.
- Parameters
row (int) – row index
- Returns
parameter id
- Return type
int
- class spinetoolbox.spine_db_editor.mvcmodels.single_models.FilterEntityAlternativeMixin(*args, **kwargs)[source]
Provides the interface to filter by entity and alternative.
- class spinetoolbox.spine_db_editor.mvcmodels.single_models.ParameterMixin[source]
Provides the data method for parameter values and definitions.
- class spinetoolbox.spine_db_editor.mvcmodels.single_models.SingleParameterDefinitionModel(parent, db_map, entity_class_id, committed, lazy=False)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin
,ParameterMixin
,SingleModelBase
A parameter_definition model for a single entity_class.
- Parameters
parent (CompoundModelBase) – the parent model
db_map (DatabaseMapping) –
entity_class_id (int) –
committed (bool) –
- class spinetoolbox.spine_db_editor.mvcmodels.single_models.SingleParameterValueModel(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.MakeEntityOnTheFlyMixin
,spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin
,ParameterMixin
,EntityMixin
,FilterEntityAlternativeMixin
,SingleModelBase
A parameter_value model for a single entity_class.
- class spinetoolbox.spine_db_editor.mvcmodels.single_models.SingleEntityAlternativeModel(*args, **kwargs)[source]
Bases:
spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.MakeEntityOnTheFlyMixin
,EntityMixin
,FilterEntityAlternativeMixin
,SingleModelBase
An entity_alternative model for a single entity_class.
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility
A tree model for parameter_value lists.
A tree item that fetches their children as they are inserted. |
|
Paints the item gray if it's the last. |
|
Bolds text. |
|
Guarantees there's always an empty child. |
|
An item representing a db. |
|
A tree item that fetches their children as they are inserted. |
- class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardTreeItem(model)[source]
Bases:
spinetoolbox.mvcmodels.minimal_tree_model.TreeItem
A tree item that fetches their children as they are inserted.
- Parameters
model (MinimalTreeModel) – The model where the item belongs.
- class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin[source]
Paints the item gray if it’s the last.
- class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildMixin[source]
Guarantees there’s always an empty child.
- class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin(*args, **kwargs)[source]
- class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardDBItem(model, db_map)[source]
Bases:
SortChildrenMixin
,StandardTreeItem
An item representing a db.
Init class.
- Parameters
model (MinimalTreeModel) –
db_map (DatabaseMapping) –
- class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem(model, identifier=None)[source]
Bases:
StandardTreeItem
A tree item that fetches their children as they are inserted.
- Parameters
model (MinimalTreeModel) –
identifier (int, optional) – item’s database id
spinetoolbox.spine_db_editor.mvcmodels.tree_model_base
Models to represent things in a tree.
A base model to display items in a tree view. |
- class spinetoolbox.spine_db_editor.mvcmodels.tree_model_base.TreeModelBase(db_editor, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.mvcmodels.minimal_tree_model.MinimalTreeModel
A base model to display items in a tree view.
- Parameters
db_editor (SpineDBEditor) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
spinetoolbox.spine_db_editor.mvcmodels.utils
General helper functions and classes for DB editor’s models.
|
Writes data in given indexes into a CSV table. |
spinetoolbox.spine_db_editor.ui
Automatically generated UI modules for Spine db editor.
spinetoolbox.spine_db_editor.widgets
Interface logic for Spine db editor.
spinetoolbox.spine_db_editor.widgets.add_items_dialogs
Classes for custom QDialogs to add items to databases.
A dialog to let the user add new 'ready' multidimensional entities. |
|
A dialog to query user's preferences for new db items. |
|
A dialog to query user's preferences for new entity classes. |
|
A dialog to query user's preferences for new entities. |
|
A dialog to query user's preferences for new entities. |
|
A dialog to query user's preferences for managing entity dimensions. |
|
|
|
|
|
|
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddReadyEntitiesDialog(parent, entity_class, entities, db_mngr, *db_maps, commit_data=True)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.DialogWithTableAndButtons
A dialog to let the user add new ‘ready’ multidimensional entities.
- Parameters
parent (SpineDBEditor) –
entity_class (dict) –
entities (list(list(str)) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddItemsDialog(parent, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialog
A dialog to query user’s preferences for new db items.
- Parameters
parent (SpineDBEditor) –
db_mngr (SpineDBManager) –
*db_maps – DiffDatabaseMapping instances
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddEntityClassesDialog(parent, item, db_mngr, *db_maps, force_default=False)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ShowIconColorEditorMixin
,spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntityClassesMixin
,AddItemsDialog
A dialog to query user’s preferences for new entity classes.
- Parameters
parent (SpineDBEditor) –
item (MultiDBTreeItem) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
force_default (bool) – if True, defaults are non-editable
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddEntitiesOrManageElementsDialog(parent, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntityClassesMixin
,spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntitiesMixin
,AddItemsDialog
A dialog to query user’s preferences for new entities.
- Parameters
parent (SpineDBEditor) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddEntitiesDialog(parent, item, db_mngr, *db_maps, force_default=False, commit_data=True)[source]
Bases:
AddEntitiesOrManageElementsDialog
A dialog to query user’s preferences for new entities.
- Parameters
parent (SpineDBEditor) –
item (MultiDBTreeItem) –
db_mngr (SpineDBManager) –
*db_maps – DatabaseMapping instances
force_default (bool) – if True, defaults are non-editable
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.ManageElementsDialog(parent, item, db_mngr, *db_maps)[source]
Bases:
AddEntitiesOrManageElementsDialog
A dialog to query user’s preferences for managing entity dimensions.
- Parameters
parent (SpineDBEditor) – data store widget
item (MultiDBTreeItem) –
db_mngr (SpineDBManager) – the manager to do the removal
*db_maps – DatabaseMapping instances
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.EntityGroupDialogBase(parent, entity_class_item, db_mngr, *db_maps)[source]
Bases:
PySide6.QtWidgets.QDialog
- Parameters
parent (SpineDBEditor) – data store widget
entity_class_item (EntityClassItem) –
db_mngr (SpineDBManager) –
*db_maps – database mappings
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddEntityGroupDialog(parent, entity_class_item, db_mngr, *db_maps)[source]
Bases:
EntityGroupDialogBase
- Parameters
parent (SpineDBEditor) – data store widget
entity_class_item (EntityClassItem) –
db_mngr (SpineDBManager) –
*db_maps – database mappings
- class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.ManageMembersDialog(parent, entity_item, db_mngr, *db_maps)[source]
Bases:
EntityGroupDialogBase
- Parameters
parent (SpineDBEditor) – data store widget
entity_item (entity_tree_item.EntityItem) –
db_mngr (SpineDBManager) –
*db_maps – database mappings
spinetoolbox.spine_db_editor.widgets.commit_viewer
Contains Database editor’s Commit viewer.
Commit viewer's central widget. |
|
A widget to show commit message, author and data on a QTreeWidget. |
|
A composite widget that contains a table and a label. |
|
Commit viewer window. |
|
Worker that fetches affected items. |
- class spinetoolbox.spine_db_editor.widgets.commit_viewer._DBCommitViewer(db_mngr, db_map, parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
Commit viewer’s central widget.
- Parameters
db_mngr (SpineDBManager) – database manager
db_map (DatabaseMapping) – database mapping
parent (QWidget, optional) – parent widget
- _select_commit(current, previous)[source]
Start a worker thread that fetches affected items for the selected commit.
- Parameters
current (QTreeWidgetItem) – currently selected commit item
previous (QTreeWidgetItem) – previously selected commit item
- _launch_new_worker(commit_id)[source]
Starts a new worker thread.
If a thread is already running, it is quite before starting a new one.
- Parameters
commit_id (TempId) – commit id
- _process_affected_items(item_type, keys, items)[source]
Adds a fetched chunk of affected items to appropriate table view.
- Parameters
item_type (str) – fethced item type
keys (Sequence of str) – item keys
items (Sequence of Sequence) – list of items, each item being a list of labels; items must have the same length as keys
- _max_affected_items_fetched(item_type, still_available)[source]
Updates the fetch status label.
- Parameters
item_type (str) – item type
still_available (int) – number of items left unfetched
- class spinetoolbox.spine_db_editor.widgets.commit_viewer._CommitItem(commit, parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
A widget to show commit message, author and data on a QTreeWidget.
- Parameters
commit (dict) – commit database item
parent (QWidget, optional) – parent widget
- class spinetoolbox.spine_db_editor.widgets.commit_viewer._AffectedItemsWidget[source]
Bases:
PySide6.QtWidgets.QWidget
A composite widget that contains a table and a label.
- class spinetoolbox.spine_db_editor.widgets.commit_viewer.CommitViewer(qsettings, db_mngr, *db_maps, parent=None)[source]
Bases:
PySide6.QtWidgets.QMainWindow
Commit viewer window.
- Parameters
qsettings (QSettings) – application settings
db_mngr (SpineDBManager) – database manager
*db_maps – database mappings to view
parent (QWidget, optional) – parent widget
- class spinetoolbox.spine_db_editor.widgets.commit_viewer.Worker(db_mngr, db_map, commit_id)[source]
Bases:
PySide6.QtCore.QObject
Worker that fetches affected items.
The items are fetched in chunks which makes it possible to quit the thread mid-execution. There is also a hard limit to how many items are fetched.
- Parameters
db_mngr (SpineDBManager) – database manager
db_map (DatabaseMapping) – database mapping
commit_id (TempId) – commit id
- static _parse_value(db_mngr, db_map, item, key)[source]
Converts item field values to something more displayable.
- Parameters
db_mngr (SpineDBManager) – database manager
db_map (DatabaseMapping) – database mapping
item (PublicItem) – database item
key (str) – value’s key
- Returns
displayable presentation of the value
- Return type
str
spinetoolbox.spine_db_editor.widgets.custom_delegates
Custom item delegates.
A mixin that fixes Pivot table's header table editor position. |
|
A mixin that fixes Pivot table's header table editor position. |
|
A mixin that fixes Pivot table's header table editor position. |
|
A mixin that fixes Pivot table's header table editor position. |
|
Delegate for Array and Map editors' table cells. |
|
Base class for all custom stacked table delegates. |
|
A delegate for the database name. |
|
A delegate for either the value or the default value. |
|
A delegate for the default value. |
|
A delegate for the parameter_value. |
|
A delegate for the parameter value list. |
|
A delegate for the object_class name. |
|
A delegate for the object parameter name. |
|
A delegate for the entity byname. |
|
A delegate for the alternative name. |
|
Base class for all custom stacked table delegates. |
|
A delegate for the alternative tree. |
|
A delegate for the scenario tree. |
|
A delegate for the parameter_name and description columns in Parameter Definition Table View. |
|
A delegate for the parameter value list tree. |
|
A custom delegate for the model in {Add/Edit}ItemDialogs. |
|
A delegate for the model and view in {Add/Edit}EntityClassesDialog. |
|
A delegate for the model and view in {Add/Edit}EntitiesDialog. |
|
A delegate for the model and view in RemoveEntitiesDialog. |
|
A delegate for the name and value columns in Metadata Table View. |
|
A delegate for name and value columns in item metadata editor. |
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.PivotTableDelegateMixin[source]
A mixin that fixes Pivot table’s header table editor position.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.RelationshipPivotTableDelegate(parent)[source]
Bases:
PivotTableDelegateMixin
,spinetoolbox.widgets.custom_delegates.CheckBoxDelegate
A mixin that fixes Pivot table’s header table editor position.
- Parameters
parent (SpineDBEditor) – parent widget, i.e. the database editor
- static _is_relationship_index(index)[source]
Checks whether the given index corresponds to a relationship, in which case we need to use the check box delegate.
- Parameters
index (QModelIndex) – index to check
- Returns
True if index corresponds to relationship, False otherwise
- Return type
bool
- setEditorData(editor, index)[source]
Do nothing. We’re setting editor data right away in createEditor.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ScenarioAlternativeTableDelegate(parent)[source]
Bases:
PivotTableDelegateMixin
,spinetoolbox.widgets.custom_delegates.RankDelegate
A mixin that fixes Pivot table’s header table editor position.
- Parameters
parent (SpineDBEditor) – database editor
- static _is_scenario_alternative_index(index)[source]
Checks whether or not the given index corresponds to a scenario alternative, in which case we need to use the rank delegate.
- Returns
bool
- setEditorData(editor, index)[source]
Do nothing. We’re setting editor data right away in createEditor.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterPivotTableDelegate(parent)[source]
Bases:
PivotTableDelegateMixin
,PySide6.QtWidgets.QStyledItemDelegate
A mixin that fixes Pivot table’s header table editor position.
- Parameters
parent (SpineDBEditor) – parent widget, i.e. database editor
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueElementDelegate[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
Delegate for Array and Map editors’ table cells.
- value_editor_requested[source]
Emitted when editing the value requires the full blown editor dialog.
- setModelData(editor, model, index)[source]
Sets data in the model.
editor (CustomLineEditor): editor widget model (QAbstractItemModel): model index (QModelIndex): target index
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.TableDelegate(parent, db_mngr)[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
Base class for all custom stacked table delegates.
- db_mngr
database manager
- Type
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.DatabaseNameDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for the database name.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueOrDefaultValueDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for either the value or the default value.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDatabaseManager) – database manager
- _create_or_request_parameter_value_editor(parent, index)[source]
Emits the signal to request a standalone ParameterValueEditor from parent widget.
- Parameters
parent (QWidget) – editor’s parent widget
index (QModelIndex) – index to parameter value model
- Returns
editor or None if
parameter_value_editor_request
signal was emitted- Return type
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterDefaultValueDelegate(parent, db_mngr)[source]
Bases:
ParameterValueOrDefaultValueDelegate
A delegate for the default value.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDatabaseManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueDelegate(parent, db_mngr)[source]
Bases:
ParameterValueOrDefaultValueDelegate
A delegate for the parameter_value.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDatabaseManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ValueListDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for the parameter value list.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.EntityClassNameDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for the object_class name.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterNameDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for the object parameter name.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.EntityBynameDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for the entity byname.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.AlternativeNameDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for the alternative name.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.BooleanValueDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
Base class for all custom stacked table delegates.
- db_mngr
database manager
- Type
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.AlternativeDelegate[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate for the alternative tree.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ScenarioDelegate(*args, **kwargs)[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate for the scenario tree.
- Parameters
*args – arguments passed to QStyledItemDelegate
**kwargs – keyword arguments passed to QStyledItemDelegate
- setEditorData(editor, index)[source]
Do nothing. We’re setting editor data right away in createEditor.
- _update_alternative_ids(item)[source]
Updates available alternatives avoiding duplicates in a scenario.
Excludes alternatives that are already in the scenario
- Parameters
item (ScenarioAlternativeItem) – one of scenario’s scenario alternatives
- Returns
available alternative names
- Return type
list of str
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterDefinitionNameAndDescriptionDelegate(parent, db_mngr)[source]
Bases:
TableDelegate
A delegate for the parameter_name and description columns in Parameter Definition Table View.
- Parameters
parent (QWidget) – parent widget
db_mngr (SpineDBManager) – database manager
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueListDelegate[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate for the parameter value list tree.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageItemsDelegate[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A custom delegate for the model in {Add/Edit}ItemDialogs.
- close_editor(editor, index)[source]
Closes editor.
Needed by SearchBarEditor.
- Parameters
editor (QWidget) – editor widget
index (QModelIndex) – index that is being edited
- connect_editor_signals(editor, index)[source]
Connect editor signals if necessary.
- Parameters
editor (QWidget) – editor widget
index (QModelIndex) – index being edited
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageEntityClassesDelegate[source]
Bases:
ManageItemsDelegate
A delegate for the model and view in {Add/Edit}EntityClassesDialog.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageEntitiesDelegate[source]
Bases:
ManageItemsDelegate
A delegate for the model and view in {Add/Edit}EntitiesDialog.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.RemoveEntitiesDelegate[source]
Bases:
ManageItemsDelegate
A delegate for the model and view in RemoveEntitiesDialog.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.MetadataDelegate[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate for the name and value columns in Metadata Table View.
- class spinetoolbox.spine_db_editor.widgets.custom_delegates.ItemMetadataDelegate(item_metadata_model, metadata_model, column, parent)[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate for name and value columns in item metadata editor.
- Parameters
item_metadata_model (ItemMetadataModel) – item metadata model
metadata_model (MetadataTableModel) – metadata model
column (int) – item metadata table column
parent (QObject, optional) – parent object
spinetoolbox.spine_db_editor.widgets.custom_editors
Custom editors for model/view programming.
A custom QLineEdit to handle data from models. |
|
A custom QLineEdit to handle data from models. |
|
Line editor that is visible on Pivot view's header tables due to a clever hack. |
|
A delegate for placing a CustomLineEditor on the first row of SearchBarEditor. |
|
A Google-like search bar, implemented as a QTableView with a _CustomLineEditDelegate in the first row. |
|
A Google-like search bar, implemented as a QTableView with a _CustomLineEditDelegate in the first row. |
|
A check list editor. |
|
A delegate to highlight decorations in a QListWidget. |
|
An editor to let the user select an icon and a color for an object_class. |
- class spinetoolbox.spine_db_editor.widgets.custom_editors.EventFilterForCatchingRollbackShortcut[source]
Bases:
PySide6.QtCore.QObject
- class spinetoolbox.spine_db_editor.widgets.custom_editors.CustomComboBoxEditor(parent)[source]
Bases:
PySide6.QtWidgets.QComboBox
- class spinetoolbox.spine_db_editor.widgets.custom_editors.CustomLineEditor(parent)[source]
Bases:
PySide6.QtWidgets.QLineEdit
A custom QLineEdit to handle data from models.
- class spinetoolbox.spine_db_editor.widgets.custom_editors.ParameterValueLineEditor(parent)[source]
Bases:
CustomLineEditor
A custom QLineEdit to handle data from models.
- class spinetoolbox.spine_db_editor.widgets.custom_editors.PivotHeaderTableLineEditor(parent=None)[source]
Bases:
CustomLineEditor
Line editor that is visible on Pivot view’s header tables due to a clever hack.
- Parameters
parent (QWidget, optional) – parent widget
- class spinetoolbox.spine_db_editor.widgets.custom_editors._CustomLineEditDelegate[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate for placing a CustomLineEditor on the first row of SearchBarEditor.
- class spinetoolbox.spine_db_editor.widgets.custom_editors.SearchBarEditor(parent, tutor=None)[source]
Bases:
PySide6.QtWidgets.QTableView
A Google-like search bar, implemented as a QTableView with a _CustomLineEditDelegate in the first row.
- Parameters
parent (QWidget, optional) – parent widget
tutor (QWidget, optional) – another widget used for positioning.
- set_data(current, items)[source]
Populates model.
- Parameters
current (str) – item that is currently selected from given items
items (Sequence of str) – items to show in the list
- set_base_offset(offset)[source]
Changes the base offset that is applied to the editor’s position.
- Parameters
offset (QPoint) – new offset
- update_geometry(option)[source]
Updates geometry.
- Parameters
option (QStyleOptionViewItem) – style information
- _handle_delegate_text_edited(text)[source]
Filters model as the first row is being edited.
- Parameters
text (str) – text the user has entered on the first row
- _proxy_model_filter_accepts_row(source_row, source_parent)[source]
Always accept first row while filtering the rest.
- Parameters
source_row (int) – source row index
source_parent (QModelIndex) – parent index for source row
- Returns
True if row is accepted, False otherwise
- Return type
bool
- class spinetoolbox.spine_db_editor.widgets.custom_editors.BooleanSearchBarEditor(parent, tutor=None)[source]
Bases:
SearchBarEditor
A Google-like search bar, implemented as a QTableView with a _CustomLineEditDelegate in the first row.
- Parameters
parent (QWidget, optional) – parent widget
tutor (QWidget, optional) – another widget used for positioning.
- class spinetoolbox.spine_db_editor.widgets.custom_editors.CheckListEditor(parent, tutor=None)[source]
Bases:
PySide6.QtWidgets.QTableView
A check list editor.
- Parameters
parent (QWidget) – parent widget
tutor (QWidget, optional) – a widget that helps in positioning
- toggle_selected(index)[source]
Adds or removes given index from selected items.
- Parameters
index (QModelIndex) – index to toggle
- class spinetoolbox.spine_db_editor.widgets.custom_editors._IconPainterDelegate[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate to highlight decorations in a QListWidget.
- class spinetoolbox.spine_db_editor.widgets.custom_editors.IconColorEditor(parent)[source]
Bases:
PySide6.QtWidgets.QDialog
An editor to let the user select an icon and a color for an object_class.
- Parameters
parent (QWidget) – parent widget
spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews
Classes for custom QGraphicsViews for the Entity graph view.
QGraphicsView for the Entity Graph View. |
- class spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews._GraphProperty(name, settings_name)[source]
- class spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews._GraphBoolProperty(*args, **kwargs)[source]
Bases:
_GraphProperty
- class spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews._GraphIntProperty(min_value, max_value, default_value, *args, **kwargs)[source]
Bases:
_GraphProperty
- class spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews.EntityQGraphicsView(parent)[source]
Bases:
spinetoolbox.widgets.custom_qgraphicsviews.CustomQGraphicsView
QGraphicsView for the Entity Graph View.
- Parameters
parent (QWidget) – Graph View Form’s (QMainWindow) central widget (self.centralwidget)
- _update_actions_visibility()[source]
Enables or disables actions according to current selection in the graph.
Shows all hidden items.
Shows some hidden items.
- set_cross_hairs_items(entity_class, cross_hairs_items)[source]
Sets ‘cross_hairs’ items for connecting entities.
- Parameters
entity_class (dict) –
cross_hairs_items (list(QGraphicsItems)) –
- _update_cross_hairs_pos(pos)[source]
Updates the hovered object item and sets the ‘cross_hairs’ icon accordingly.
- Parameters
pos (QPoint) – the desired position in view coordinates
- contextMenuEvent(e)[source]
Shows context menu.
- Parameters
e (QContextMenuEvent) – Context menu event
- wheelEvent(event)[source]
Zooms in/out. If user has pressed the shift key, rotates instead.
- Parameters
event (QWheelEvent) – Mouse wheel event
spinetoolbox.spine_db_editor.widgets.custom_qtableview
Custom QTableView classes that support copy-paste and the like.
Base stacked view. |
|
Base stacked view. |
|
Base stacked view. |
|
Base stacked view. |
|
Visualize entities and their alternatives. |
|
Custom QTableView class with pivot capabilities. |
|
|
|
Base for metadata and item metadata table views. |
|
Table view for metadata. |
|
Table view for entity and parameter value metadata. |
|
Updates (object or relationship) parameter_definition or value with newly edited data. |
- spinetoolbox.spine_db_editor.widgets.custom_qtableview._set_data(index, new_value)[source]
Updates (object or relationship) parameter_definition or value with newly edited data.
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.StackedTableView(parent)[source]
Bases:
spinetoolbox.widgets.custom_qtableview.AutoFilterCopyPasteTableView
Base stacked view.
- Parameters
parent (QWidget) – parent widget
- connect_spine_db_editor(spine_db_editor)[source]
Connects a Spine db editor to work with this view.
- Parameters
spine_db_editor (SpineDBEditor) –
- _make_delegate(column_name, delegate_class)[source]
Creates a delegate for the given column and returns it.
- Parameters
column_name (str) –
delegate_class (TableDelegate) –
- Returns
TableDelegate
Creates a context menu for this view.
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterTableView(parent)[source]
Bases:
StackedTableView
Base stacked view.
- Parameters
parent (QWidget) – parent widget
- value_column_header: str[source]
Either “default_value” or “value”. Used to identify the value column for advanced editing and plotting.
Creates a context menu for this view.
- open_in_editor()[source]
Opens the current index in a parameter_value editor using the connected Spine db editor.
- abstract _plot_selection(selection, plot_widget=None)[source]
Adds selected indexes to existing plot or creates a new plot window.
- Parameters
selection (Iterable of QModelIndex) – a list of QModelIndex objects for plotting
plot_widget (PlotWidget, optional) – an existing plot widget to draw into or None to create a new widget
- Returns
a PlotWidget object
- Return type
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterDefinitionTableView(parent)[source]
Bases:
ParameterTableView
Base stacked view.
- Parameters
parent (QWidget) – parent widget
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterValueTableView(parent)[source]
Bases:
ParameterTableView
Base stacked view.
- Parameters
parent (QWidget) – parent widget
- connect_spine_db_editor(spine_db_editor)[source]
Connects a Spine db editor to work with this view.
- Parameters
spine_db_editor (SpineDBEditor) –
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.EntityAlternativeTableView(parent)[source]
Bases:
StackedTableView
Visualize entities and their alternatives.
- Parameters
parent (QWidget) – parent widget
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.PivotTableView(parent=None)[source]
Bases:
spinetoolbox.widgets.custom_qtableview.CopyPasteTableView
Custom QTableView class with pivot capabilities.
Uses ‘contexts’ to provide different UI elements (table headers, context menus,…) depending on what data the pivot table currently contains.
- Parameters
parent (QWidget, optional) – parent widget
- class _ContextBase(view, db_editor, horizontal_header, vertical_header)[source]
Base class for pivot table view’s contexts.
- Parameters
view (PivotTableView) – parent view
db_editor (SpineDBEditor) – database editor
horizontal_header (QHeaderView) – horizontal header
vertical_header (QHeaderView) – vertical header
Generates context menu.
Shows the context menu.
- class _EntityContextBase(view, db_editor, horizontal_header, vertical_header)[source]
Bases:
PivotTableView._ContextBase
Base class for contexts that contain entities and entity classes.
- Parameters
view (PivotTableView) – parent view
db_editor (SpineDBEditor) – database editor
horizontal_header (QHeaderView) – horizontal header
vertical_header (QHeaderView) – vertical header
See base class.
- class _ParameterValueContext(view, db_editor)[source]
Bases:
PivotTableView._EntityContextBase
Context for showing parameter values in the pivot table.
- Parameters
view (PivotTableView) – parent view
db_editor (SpineDBEditor) – database editor
See base class.
Shows the context menu.
- class _IndexExpansionContext(view, db_editor)[source]
Bases:
PivotTableView._ParameterValueContext
Context for expanded parameter values
- Parameters
view (PivotTableView) – parent view
db_editor (SpineDBEditor) – database editor
- class _ElementContext(view, db_editor)[source]
Bases:
PivotTableView._EntityContextBase
Context for presenting relationships in the pivot table.
- Parameters
view (PivotTableView) – parent view
db_editor (SpineDBEditor) – database editor
See base class.
- class _ScenarioAlternativeContext(view, db_editor)[source]
Bases:
PivotTableView._ContextBase
Context for presenting scenarios and alternatives
- Parameters
view (PivotTableView) – parent view
db_editor (SpineDBEditor) – database editor
See base class.
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.FrozenTableView(parent=None)[source]
Bases:
PySide6.QtWidgets.QTableView
- Parameters
parent (QWidget) – parent widget
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.MetadataTableViewBase(parent)[source]
Bases:
spinetoolbox.widgets.custom_qtableview.CopyPasteTableView
Base for metadata and item metadata table views.
- Parameters
parent (QWidget, optional) – parent widget
- connect_spine_db_editor(db_editor)[source]
Finishes view’s initialization.
- Parameters
db_editor (SpineDBEditor) – database editor instance
- _enable_delegates(db_editor)[source]
Creates delegates for this view
- Parameters
db_editor (SpineDBEditor) – database editor
Fills context menu with actions.
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.MetadataTableView(parent)[source]
Bases:
MetadataTableViewBase
Table view for metadata.
- Parameters
parent (QWidget, optional) – parent widget
- class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ItemMetadataTableView(parent)[source]
Bases:
MetadataTableViewBase
Table view for entity and parameter value metadata.
- Parameters
parent (QWidget) – parent widget
- set_models(item_metadata_model, metadata_model)[source]
Sets models.
- Parameters
item_metadata_model (ItemMetadataModel) – item metadata model
metadata_model (MetadataTableModel) – metadata model
spinetoolbox.spine_db_editor.widgets.custom_qtreeview
Classes for custom QTreeViews and QTreeWidgets.
Tree view for entity classes and entities. |
|
Base class for all non-entity tree views. |
|
Custom QTreeView for the alternative tree in SpineDBEditor. |
|
Custom QTreeView for the scenario tree in SpineDBEditor. |
|
Custom QTreeView class for parameter_value_list in SpineDBEditor. |
- class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.EntityTreeView(parent)[source]
Bases:
spinetoolbox.widgets.custom_qtreeview.CopyPasteTreeView
Tree view for entity classes and entities.
- Parameters
parent (QWidget) – parent widget
- connect_spine_db_editor(spine_db_editor)[source]
Connects a Spine db editor to work with this view.
- Parameters
spine_db_editor (SpineDBEditor) –
Creates a context menu for this view.
- _handle_selection_changed(selected, deselected)[source]
Classifies selection by item type and emits signal.
- mousePressEvent(event)[source]
Overrides selection behaviour if the user has selected sticky selection in Settings. If sticky selection is enabled, multiple-selection is enabled when selecting items in the Object tree. Pressing the Ctrl-button down, enables single selection.
- Parameters
event (QMouseEvent) –
- update_actions_availability()[source]
Updates the visible property of actions according to whether or not they apply to given item.
- find_next_entity()[source]
Finds the next occurrence of the relationship at the current index and expands it.
- class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ItemTreeView(parent)[source]
Bases:
spinetoolbox.widgets.custom_qtreeview.CopyPasteTreeView
Base class for all non-entity tree views.
- Parameters
parent (QWidget) – parent widget
- abstract update_actions_availability(item)[source]
Updates the visible property of actions according to whether or not they apply to given item.
- connect_spine_db_editor(spine_db_editor)[source]
Prepares the view to work with the DB editor.
- Parameters
spine_db_editor (SpineDBEditor) – editor instance
Creates a context menu for this view.
- class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.AlternativeTreeView(parent)[source]
Bases:
ItemTreeView
Custom QTreeView for the alternative tree in SpineDBEditor.
- Parameters
parent (QWidget) – parent widget
See base class.
- _db_map_alt_ids_from_selection(selection)[source]
Gather alternative ids per database map from selection.
- Parameters
selection (QItemSelection) – selection
- Returns
mapping from database map to set of alternative ids
- Return type
dict
- class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ScenarioTreeView(parent)[source]
Bases:
ItemTreeView
Custom QTreeView for the scenario tree in SpineDBEditor.
- Parameters
parent (QWidget) – parent widget
See base class.
- _db_map_alternative_ids_from_selection(selection)[source]
Collects database maps and alternative ids within given selection.
- Parameters
selection (Sequence of QModelIndex) – selection indices
- Returns
mapping from database map to set of alternative ids
- Return type
dict
- class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ParameterValueListTreeView(parent)[source]
Bases:
ItemTreeView
Custom QTreeView class for parameter_value_list in SpineDBEditor.
- Parameters
parent (QWidget) – parent widget
Creates a context menu for this view.
spinetoolbox.spine_db_editor.widgets.custom_qwidgets
Custom QWidgets.
A button to open files or show them in the folder. |
|
A button to open sqlite files, show them in the folder, or add them to the project. |
|
- class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.OpenFileButton(file_path, progress, db_editor)[source]
Bases:
PySide6.QtWidgets.QWidget
A button to open files or show them in the folder.
- class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.OpenSQLiteFileButton(file_path, progress, db_editor)[source]
Bases:
OpenFileButton
A button to open sqlite files, show them in the folder, or add them to the project.
- class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.ShootingLabel(origin, destination, parent=None, duration=1200)[source]
Bases:
PySide6.QtWidgets.QLabel
- class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.ProgressBarWidget(parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
- class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.TimeLineWidget(parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs
Classes for custom QDialogs to edit items in databases.
A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all |
|
A dialog to query user's preferences for updating entity classes. |
|
A dialog to query user's preferences for updating entities. |
|
A dialog to query user's preferences for removing tree items. |
|
Provides a method to retrieve entity classes for AddEntitiesDialog and AddEntityClassesDialog. |
- class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.EditOrRemoveItemsDialog(parent, db_mngr)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialog
A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all dialogs to query user’s preferences for adding/editing/managing data items.
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) –
- class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.EditEntityClassesDialog(parent, db_mngr, selected)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ShowIconColorEditorMixin
,EditOrRemoveItemsDialog
A dialog to query user’s preferences for updating entity classes.
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) – the manager to do the update
selected (set) – set of EntityClassItem instances to edit
- class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.EditEntitiesDialog(parent, db_mngr, selected, class_key)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntityClassesMixin
,spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntitiesMixin
,EditOrRemoveItemsDialog
A dialog to query user’s preferences for updating entities.
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) – the manager to do the update
selected (set) – set of EntityItem instances to edit
class_key (tuple) – for identifying the entity class
- class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.RemoveEntitiesDialog(parent, db_mngr, selected)[source]
Bases:
EditOrRemoveItemsDialog
A dialog to query user’s preferences for removing tree items.
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) – the manager to do the removal
selected (dict) – maps item type (class) to instances
- class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.SelectSuperclassDialog(parent, entity_class_item, db_mngr, *db_maps)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntityClassesMixin
,spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.DialogWithButtons
Provides a method to retrieve entity classes for AddEntitiesDialog and AddEntityClassesDialog.
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) –
spinetoolbox.spine_db_editor.widgets.element_name_list_editor
Contains the ElementNameListEditor class.
A custom delegate to use with ElementNameListEditor. |
|
A dialog to select the element name list for an entity using Google-like search bars. |
- class spinetoolbox.spine_db_editor.widgets.element_name_list_editor.SearchBarDelegate[source]
Bases:
PySide6.QtWidgets.QItemDelegate
A custom delegate to use with ElementNameListEditor.
- class spinetoolbox.spine_db_editor.widgets.element_name_list_editor.ElementNameListEditor(parent, index, entity_class_names, entity_byname_lists, current_element_byname_list)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialog
A dialog to select the element name list for an entity using Google-like search bars.
- Parameters
parent (SpineDBEditor) –
index (QModelIndex) –
entity_class_names (list) – string entity_class names
entity_byname_lists (list) – lists of string entity names
current_element_byname_list (list) –
spinetoolbox.spine_db_editor.widgets.graph_layout_generator
Contains the GraphLayoutGeneratorRunnable class.
Computes the layout for the Entity Graph View. |
- class spinetoolbox.spine_db_editor.widgets.graph_layout_generator.GraphLayoutGeneratorRunnable(identifier, vertex_count, src_inds=(), dst_inds=(), spread=0, heavy_positions=None, max_iters=12, weight_exp=-2)[source]
Bases:
PySide6.QtCore.QRunnable
Computes the layout for the Entity Graph View.
spinetoolbox.spine_db_editor.widgets.graph_view_mixin
Contains the GraphViewMixin class.
Provides the graph view for the DB editor. |
|
|
|
|
|
|
|
|
|
|
- class spinetoolbox.spine_db_editor.widgets.graph_view_mixin.GraphViewMixin(*args, **kwargs)[source]
Provides the graph view for the DB editor.
- _refresh_icons(item_type, db_map_data)[source]
Runs when entity classes are added or updated in the db. Refreshes icons of entities in graph.
- Parameters
db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.
- _graph_handle_entities_added(db_map_data)[source]
Runs when entities are added to the db. Adds the new entities to the graph if needed.
- Parameters
db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.
- _graph_handle_entities_removed(db_map_data)[source]
Runs when entities are removed from the db. Rebuilds graph if needed.
- Parameters
db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.
- _graph_handle_entities_updated(db_map_data)[source]
Runs when entities are updated in the db.
- Parameters
db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.
- add_db_map_ids_to_items(db_map_data)[source]
Goes through entity items and adds the corresponding db_map ids. This could mean either restoring removed (db_map, id) tuples previously removed, or adding new (db_map, id) tuples.
- Parameters
db_map_data (dict(DiffDatabaseMapping, list)) – List of added items keyed by db_map
- Returns
tuples (db_map, id) that didn’t match any item in the view.
- Return type
list
- _handle_entity_tree_selection_changed_in_graph(selected)[source]
Stores the given selection of entity tree indexes and builds graph.
- build_graph(persistent=False)[source]
Builds graph from current selection of items.
- Parameters
persistent (bool, optional) – If True, elements in the current graph (if any) retain their position in the new one.
- _complete_graph(layout_gen_id, x, y)[source]
- Parameters
layout_gen_id (object) –
x (list) – Horizontal coordinates
y (list) – Vertical coordinates
- _update_selected_item_type_db_map_ids(selected_tree_inds)[source]
Upsates the dict mapping item type to db_map to selected ids.
- _get_item_property(db_map, entity_id, pname, time_line_index)[source]
Returns a tuple of (min_value, value, max_value) for given entity and property. Returns self.NOT_SPECIFIED if the property is not defined for the entity. Returns None if the property is not defined for any entity.
- Returns
tuple or None
- _make_layout_generator()[source]
Returns a layout generator for the current graph.
- Returns
GraphLayoutGeneratorRunnable
- _make_new_items(x, y)[source]
Makes new items for the graph.
- Parameters
x (list) –
y (list) –
- Returns
True if graph contains any items after the operation, False otherwise
- Return type
bool
- start_connecting_entities(db_map, entity_class, ent_item)[source]
Starts connecting entites with the given entity item.
- Parameters
db_map (DiffDatabaseMapping) –
entity_class (dict) –
ent_item (..graphics_items.EntityItem) –
spinetoolbox.spine_db_editor.widgets.item_metadata_editor
Contains machinery to deal with item metadata editor.
A DB editor helper class that manages entity and parameter value metadata editor. |
- class spinetoolbox.spine_db_editor.widgets.item_metadata_editor.ItemMetadataEditor(item_metadata_table_view, db_editor, metadata_editor, db_mngr)[source]
A DB editor helper class that manages entity and parameter value metadata editor.
- Parameters
item_metadata_table_view (ItemMetadataTableView) – editor’s view
db_editor (SpineDBEditor) – database editor
metadata_editor (MetadataEditor) – metadata editor
db_mngr (SpineDBManager) – database manager
- connect_signals(ui)[source]
Connects user interface signals.
- Parameters
ui (Ui_MainWindow) – DB editor’s user interface
- init_models(db_maps)[source]
Initializes editor’s models.
- Parameters
db_maps (Iterable of DiffDatabaseMapping) – database mappings
spinetoolbox.spine_db_editor.widgets.manage_items_dialogs
Classes for custom QDialogs to add, edit and remove database items.
|
|
|
|
A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all |
|
Provides a method to retrieve entity classes for AddEntitiesDialog and AddEntityClassesDialog. |
|
Provides a method to retrieve entities for AddEntitiesDialog and EditEntitiesDialog. |
|
Provides methods to show an IconColorEditor upon request. |
- class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.DialogWithButtons(parent, db_mngr)[source]
Bases:
PySide6.QtWidgets.QDialog
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) –
- class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.DialogWithTableAndButtons(parent, db_mngr)[source]
Bases:
DialogWithButtons
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) –
- class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialog(parent, db_mngr)[source]
Bases:
DialogWithTableAndButtons
A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all dialogs to query user’s preferences for adding/editing/managing data items.
- Parameters
parent (SpineDBEditor) – data store widget
db_mngr (SpineDBManager) –
- class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntityClassesMixin[source]
Provides a method to retrieve entity classes for AddEntitiesDialog and AddEntityClassesDialog.
- class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntitiesMixin(*args, **kwargs)[source]
Provides a method to retrieve entities for AddEntitiesDialog and EditEntitiesDialog.
spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs
Classes for custom QDialogs to add edit and remove database items.
A widget that shows checkboxes for each database. |
|
A dialog to query a selection of dbs and items from the user. |
|
A dialog to query user's preferences for mass removing db items. |
|
A dialog to let users chose items for JSON export. |
- class spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs._SelectDatabases(db_maps, checked_states, parent)[source]
Bases:
PySide6.QtWidgets.QWidget
A widget that shows checkboxes for each database.
- Parameters
db_maps (tuple of DatabaseMapping) – database maps
checked_states (dict, optional) – mapping from item name to check state boolean
parent (QWidget) – parent widget
- class spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs.MassSelectItemsDialog(parent, db_mngr, *db_maps, stored_state, ok_button_text)[source]
Bases:
spinetoolbox.widgets.custom_qwidgets.SelectDatabaseItemsDialog
A dialog to query a selection of dbs and items from the user.
- Parameters
parent (SpineDBEditor) – parent widget
db_mngr (SpineDBManager) – database manager
*db_maps – the dbs to select items from
stored_state (dict, Optional) – widget’s previous state
ok_button_text (str, optional) – alternative label for the OK button
- class spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs.MassRemoveItemsDialog(parent, db_mngr, *db_maps, stored_state=None)[source]
Bases:
MassSelectItemsDialog
A dialog to query user’s preferences for mass removing db items.
Initialize class.
- Parameters
parent (SpineDBEditor) –
db_mngr (SpineDBManager) –
db_maps (DiffDatabaseMapping) – the dbs to select items from
stored_state (dict, Optional) – widget’s previous state
- class spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs.MassExportItemsDialog(parent, db_mngr, *db_maps, stored_state=None)[source]
Bases:
MassSelectItemsDialog
A dialog to let users chose items for JSON export.
- Parameters
parent (SpineDBEditor) –
db_mngr (SpineDBManager) –
db_maps (DiffDatabaseMapping) – the dbs to select items from
stored_state (dict, Optional) – widget’s previous state
spinetoolbox.spine_db_editor.widgets.metadata_editor
Contains machinery to deal with metadata editor.
A DB editor helper class that manages metadata editor. |
- class spinetoolbox.spine_db_editor.widgets.metadata_editor.MetadataEditor(metadata_table_view, db_editor, db_mngr)[source]
A DB editor helper class that manages metadata editor.
- Parameters
metadata_table_view (MetadataTableView) – editor’s view
db_editor (SpineDBEditor) – database editor
db_mngr (SpineDBManager) – database manager
- connect_signals(ui)[source]
Connects user interface signals.
- Parameters
ui (Ui_MainWindow) – DB editor’s user interface
spinetoolbox.spine_db_editor.widgets.multi_spine_db_editor
Contains the MultiSpineDBEditor class.
Database editor's tabbed main window. |
|
- class spinetoolbox.spine_db_editor.widgets.multi_spine_db_editor.MultiSpineDBEditor(db_mngr, db_url_codenames=None)[source]
Bases:
spinetoolbox.widgets.multi_tab_window.MultiTabWindow
Database editor’s tabbed main window.
- Parameters
db_mngr (SpineDBManager) – database manager
db_url_codenames (dict, optional) – mapping from database URL to its codename
- _make_other()[source]
Creates a new MultiTabWindow of this type.
- Returns
new MultiTabWindow
- Return type
- _connect_tab_signals(tab)[source]
Connects Spine Db editor window (tab) signals.
- Parameters
tab (SpineDBEditor) – Spine Db editor window
- Returns
True if ok, False otherwise
- Return type
bool
- _disconnect_tab_signals(index)[source]
Disconnects signals of Spine Db editor window (tab) in given index.
- Parameters
index (int) – Tab index
- Returns
True if ok, False otherwise
- Return type
bool
- _make_new_tab(db_url_codenames=None, window=False)[source]
Makes a new tab, if successful return the tab, returns None otherwise
Opens a context menu for the toolbar.
- Parameters
global_pos (QPoint) – menu position on screen
Creates a context menu for given tab.
- Parameters
index (int) – tab index
- Returns
context menu or None if tab was not found
- Return type
QMenu
- _insert_statusbar_button(button)[source]
Inserts given button to the ‘beginning’ of the status bar and decorates it with a shooting label.
- Parameters
button (OpenFileButton) –
spinetoolbox.spine_db_editor.widgets.pivot_table_header_view
Contains custom QHeaderView for the pivot table.
Header view for the pivot table. |
|
Header view for the pivot table in parameter value and index expansion mode. |
|
Header view for the pivot table in parameter value and index expansion mode. |
- class spinetoolbox.spine_db_editor.widgets.pivot_table_header_view.PivotTableHeaderView(orientation, area, pivot_table_view)[source]
Bases:
PySide6.QtWidgets.QHeaderView
Header view for the pivot table.
- Parameters
orientation (Qt.Orientation) – Qt.Orientation.Horizontal or Qt.Orientation.Vertical
area (str) – which pivot area the header represents: “columns”, “rows” or “frozen”
pivot_table_view (PivotTableView) – parent view
- class spinetoolbox.spine_db_editor.widgets.pivot_table_header_view.ParameterValuePivotHeaderView(orientation, area, pivot_table_view)[source]
Bases:
PivotTableHeaderView
Header view for the pivot table in parameter value and index expansion mode.
- Parameters
orientation (Qt.Orientation) – Qt.Orientation.Horizontal or Qt.Orientation.Vertical
area (str) – which pivot area the header represents: “columns”, “rows” or “frozen”
pivot_table_view (PivotTableView) – parent view
- _column_selection()[source]
Lists current column’s indexes that contain some data.
- Returns
column indexes
- Return type
list of QModelIndex
- class spinetoolbox.spine_db_editor.widgets.pivot_table_header_view.ScenarioAlternativePivotHeaderView(orientation, area, pivot_table_view)[source]
Bases:
PivotTableHeaderView
Header view for the pivot table in parameter value and index expansion mode.
- Parameters
orientation (Qt.Orientation) – Qt.Orientation.Horizontal or Qt.Orientation.Vertical
area (str) – which pivot area the header represents: “columns”, “rows” or “frozen”
pivot_table_view (PivotTableView) – parent view
Requests a header context menu be shown at given global position.
spinetoolbox.spine_db_editor.widgets.scenario_generator
Contains a dialog for generating scenarios from selected alternatives.
Generic enumeration. |
|
A dialog where users can generate scenarios from given alternatives. |
|
Removes duplicate scenario alternatives. |
|
Returns the name of a 'base' alternative or empty string if not found. |
|
Returns a formattable string with enough zero padding to hold item_count digits. |
- class spinetoolbox.spine_db_editor.widgets.scenario_generator._ScenarioNameResolution[source]
Bases:
enum.Enum
Generic enumeration.
Derive from this class to define new enumerations.
- class spinetoolbox.spine_db_editor.widgets.scenario_generator.ScenarioGenerator(parent, db_map, alternatives, spine_db_editor)[source]
Bases:
PySide6.QtWidgets.QWidget
A dialog where users can generate scenarios from given alternatives.
- Parameters
parent (QWidget) – parent widget
db_map (DiffDatabaseMapping) – database mapping that contains the alternatives
alternatives (Iterable of CacheItem) – alternatives from which the scenarios are generated
spine_db_editor (SpineDBEditor) – database editor instance
- accept()[source]
Generates scenarios and closes the dialog.
The operation may get cancelled by user if there are conflicts in scenario names.
- _generate_scenarios(new_scenarios, scenarios_to_modify, scenario_alternatives)[source]
Generates scenarios with all possible combinations of given alternatives.
- Parameters
new_scenarios (Iterable of str) – names of new scenarios to create
scenarios_to_modify (Iterable of str) – names of scenarios to modify
scenario_alternatives (list of list) – alternative items for each scenario
- _check_existing_scenarios(proposed_scenario_names, existing_scenario_names)[source]
Checks if proposed scenarios exist, and if so, prompts users what to do.
- Parameters
proposed_scenario_names (Iterable of str) – proposed scenario names
existing_scenario_names (set of str) – existing scenario names
- Returns
action to take
- Return type
- spinetoolbox.spine_db_editor.widgets.scenario_generator._ensure_unique(scenario_alternatives)[source]
Removes duplicate scenario alternatives.
- Parameters
scenario_alternatives (list of list) – scenario alternatives
- spinetoolbox.spine_db_editor.widgets.scenario_generator._find_base_alternative(names)[source]
Returns the name of a ‘base’ alternative or empty string if not found.
Basically, checks if “Base” is in names, otherwise searches for the first case-insensitive version of “base”.
- Parameters
names (list of str) – alternative names
- Returns
base alternative name
- Return type
str
- spinetoolbox.spine_db_editor.widgets.scenario_generator._suffix(item_count)[source]
Returns a formattable string with enough zero padding to hold item_count digits.
- Parameters
item_count (int) – maximum number of items
- Returns
string in the form ‘{:0n}’ where n is the number of digits in item_count
- Return type
str
spinetoolbox.spine_db_editor.widgets.select_graph_parameters_dialog
Classes for custom QDialogs to add items to databases.
A delegate for the database name. |
- class spinetoolbox.spine_db_editor.widgets.select_graph_parameters_dialog.SelectGraphParametersDialog(parent, parameters)[source]
Bases:
PySide6.QtWidgets.QDialog
- class spinetoolbox.spine_db_editor.widgets.select_graph_parameters_dialog.ParameterNameDelegate(parent, db_mngr, *db_maps)[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate for the database name.
spinetoolbox.spine_db_editor.widgets.spine_db_editor
Contains the SpineDBEditor class.
Base class for SpineDBEditor (i.e. Spine database editor). |
|
A widget to visualize Spine dbs. |
- class spinetoolbox.spine_db_editor.widgets.spine_db_editor.SpineDBEditorBase(db_mngr)[source]
Bases:
PySide6.QtWidgets.QMainWindow
Base class for SpineDBEditor (i.e. Spine database editor).
- Parameters
db_mngr (SpineDBManager) – The manager to use
- static is_db_map_editor()[source]
Always returns True as SpineDBEditors are truly database editors.
Unless, of course, the database can one day be opened in read-only mode. In that case this method should return False.
- Returns
Always True
- Return type
bool
Returns a menu with all dock toggle/view actions. Called by
self.add_main_menu()
.- Returns
QMenu
Adds a menu with main actions to toolbar.
- add_message(msg)[source]
Pushes message to notification stack.
- Parameters
msg (str) – String to show in the notification
- refresh_copy_paste_actions()[source]
Runs when menus are about to show. Enables or disables actions according to selection status.
- import_data(data)[source]
Imports data to all database mappings open in the editor.
- Parameters
data (dict) – data to import
- show_mass_export_items_dialog(checked=False)[source]
Shows dialog for user to select dbs and items for export.
- duplicate_entity(entity_item)[source]
Duplicates an entity.
- Parameters
entity_item (EntityItem) –
- duplicate_scenario(db_map, scen_id)[source]
Duplicates a scenario.
- Parameters
db_map (DiffDatabaseMapping) –
scen_id (int) –
- export_data(db_map_ids_for_export)[source]
Exports data from given dictionary into a file.
- Parameters
db_map_ids_for_export – Dictionary mapping db maps to keyword arguments for spinedb_api.export_data
- _store_purge_settings(state)[source]
Stores Purge items dialog state.
- Parameters
state (dict) – dialog state
- show_parameter_value_editor(index, plain=False)[source]
Shows the parameter_value editor for the given index of given table view.
- _log_items_change(msg)[source]
Enables or disables actions and informs the user about what just happened.
- restore_ui(view_type, fresh=False)[source]
Restores UI state from previous session.
- Parameters
view_type (str) – What the selected view type is.
fresh (bool) – If true, the view specified with subgroup will be applied, instead of loading the previous window state of the said view.
- tear_down()[source]
Performs clean up duties.
- Returns
True if editor is ready to close, False otherwise
- Return type
bool
- _prompt_to_commit_changes()[source]
Prompts the user to commit or rollback changes to ‘dirty’ db maps.
- Returns
QMessageBox status code
- Return type
int
- _get_commit_msg(db_names)[source]
Prompts user for commit message.
- Parameters
db_names (Iterable of str) – database names
- Returns
commit message
- Return type
str
- class spinetoolbox.spine_db_editor.widgets.spine_db_editor.SpineDBEditor(db_mngr, db_url_codenames=None)[source]
Bases:
spinetoolbox.spine_db_editor.widgets.tabular_view_mixin.TabularViewMixin
,spinetoolbox.spine_db_editor.widgets.graph_view_mixin.GraphViewMixin
,spinetoolbox.spine_db_editor.widgets.stacked_view_mixin.StackedViewMixin
,spinetoolbox.spine_db_editor.widgets.tree_view_mixin.TreeViewMixin
,SpineDBEditorBase
A widget to visualize Spine dbs.
Initializes everything.
- Parameters
db_mngr (SpineDBManager) – The manager to use
- tabify_and_raise(docks)[source]
Tabifies docks in given list, then raises the first.
- Parameters
docks (list) –
- apply_stacked_style(_checked=None)[source]
Applies the stacked style, inspired in the former tree view.
- apply_pivot_style(_checked=None)[source]
Applies the pivot style, inspired in the former tabular view.
spinetoolbox.spine_db_editor.widgets.stacked_view_mixin
Contains the StackedViewMixin class.
Provides stacked parameter tables for the Spine db editor. |
- class spinetoolbox.spine_db_editor.widgets.stacked_view_mixin.StackedViewMixin(*args, **kwargs)[source]
Provides stacked parameter tables for the Spine db editor.
- show_element_name_list_editor(index, entity_class_id, db_map)[source]
Shows the element name list editor.
- Parameters
index (QModelIndex) –
entity_class_id (int) –
db_map (DatabaseMapping) –
- _set_default_parameter_data(index=None)[source]
Sets default rows for parameter models according to given index.
- Parameters
index (QModelIndex) – an index of the entity tree
- _handle_graph_selection_changed(selected_items)[source]
Resets filter according to graph selection.
- _handle_entity_tree_selection_changed_in_parameter_tables(selected_indexes)[source]
Resets filter according to entity tree selection.
- _handle_alternative_selection_changed(selected_db_map_alt_ids)[source]
Resets filter according to selection in alternative tree view.
- _handle_scenario_alternative_selection_changed(selected_db_map_alt_ids)[source]
Resets filter according to selection in scenario tree view.
- _update_alternative_selection(selected_db_map_alt_ids, other_tree_view, this_tree_view)[source]
Combines alternative selections from alternative and scenario tree views.
- Parameters
selected_db_map_alt_ids (dict) – mapping from database map to set of alternative ids
other_tree_view (AlternativeTreeView or ScenarioTreeView) – tree view whose selection didn’t change
this_tree_view (AlternativeTreeView or ScenarioTreeView) – tree view whose selection changed
spinetoolbox.spine_db_editor.widgets.tabular_view_header_widget
Contains TabularViewHeaderWidget class.
A draggable QWidget. |
- class spinetoolbox.spine_db_editor.widgets.tabular_view_header_widget.TabularViewHeaderWidget(identifier, area, menu=None, parent=None)[source]
Bases:
PySide6.QtWidgets.QFrame
A draggable QWidget.
- Parameters
identifier (str) –
area (str) – either “rows”, “columns”, or “frozen”
menu (FilterMenu, optional) –
parent (QWidget, optional) – Parent widget
spinetoolbox.spine_db_editor.widgets.tabular_view_mixin
Contains TabularViewMixin class.
Provides the pivot table and its frozen table for the Database editor. |
- class spinetoolbox.spine_db_editor.widgets.tabular_view_mixin.TabularViewMixin(*args, **kwargs)[source]
Provides the pivot table and its frozen table for the Database editor.
- static _is_class_index(index)[source]
Returns whether the given tree index is a class index.
- Parameters
index (QModelIndex) – index from object or relationship tree
- Returns
bool
- get_pivot_preferences()[source]
Returns saved pivot preferences.
- Returns
pivot tuple, or None if no preference stored
- Return type
tuple, NoneType
- make_pivot_headers()[source]
Turns top left indexes in the pivot table into TabularViewHeaderWidget.
- _make_inserted_frozen_headers(parent_index, first_column, last_column)[source]
Turns the first row of columns in the frozen table into TabularViewHeaderWidgets.
- Parameters
parent_index (QModelIndex) – frozen table column’s parent index
first_column (int) – first inserted column
last_column (int) – last inserted column
- _make_all_frozen_headers()[source]
Turns the first row of columns in the frozen table into TabularViewHeaderWidgets.
- _check_frozen_value_selected(parent, first_row, last_row)[source]
Ensures that at least one row is selected in frozen table when number of rows change.
Returns a filter menu for given filterable item.
- Parameters
identifier (str) – item identifier
- Returns
filter menu corresponding to identifier
- Return type
- create_header_widget(identifier, area, with_menu=True)[source]
Returns a TabularViewHeaderWidget for given object_class identifier.
- Parameters
identifier (str) –
area (str) –
with_menu (bool) –
- Returns
TabularViewHeaderWidget
- static _get_insert_index(pivot_list, catcher, position)[source]
Returns an index for inserting a new element in the given pivot list.
- Returns
int
- handle_header_dropped(dropped, catcher, position='')[source]
Updates pivots when a header is dropped.
- Parameters
dropped (TabularViewHeaderWidget) – drag source widget
catcher (TabularViewHeaderWidget or PivotTableHeaderView or FrozenTableView) – drop target widget
position (str) – either “before”, “after”, or “”
- _change_selected_frozen_row(current, previous)[source]
Sets the frozen value from selection in frozen table.
- _update_current_index_if_need()[source]
Ensures selected frozen row corresponds to current index.
Frozen table gets sorted from time to time possibly changing the selected row.
- _add_values_to_frozen_table(frozen_values)[source]
Adds values to frozen table.
- Parameters
frozen_values (set of tuple) – values to add
- _remove_values_from_frozen_table(frozen_values)[source]
Removes values from frozen table.
- Parameters
frozen_values (set of tuple) – values to remove
spinetoolbox.spine_db_editor.widgets.tree_view_mixin
Contains the TreeViewMixin class.
Provides object and relationship trees for the Spine db editor. |
spinetoolbox.spine_db_editor.widgets.url_toolbar
Contains the UrlToolBar class and helpers.
- class spinetoolbox.spine_db_editor.widgets.url_toolbar.UrlToolBar(db_editor)[source]
Bases:
PySide6.QtWidgets.QToolBar
- class spinetoolbox.spine_db_editor.widgets.url_toolbar._FilterWidget(db_mngr, db_map, item_type, filter_type, active_item, parent=None)[source]
Bases:
PySide6.QtWidgets.QTreeWidget
- class spinetoolbox.spine_db_editor.widgets.url_toolbar._FilterArrayWidget(db_mngr, db_map, parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
Submodules
spinetoolbox.spine_db_editor.graphics_items
Classes for drawing graphics items on graph view’s QGraphicsScene.
|
|
Connects two EntityItems. |
|
Creates new relationships directly in the graph. |
|
Represents the relationship that's being created using the CrossHairsItem. |
|
Connects a CrossHairsEntityItem with the CrossHairsItem, |
|
Provides a label for EntityItem. |
|
- class spinetoolbox.spine_db_editor.graphics_items.EntityItem(spine_db_editor, x, y, extent, db_map_ids, offset=None)[source]
Bases:
PySide6.QtWidgets.QGraphicsRectItem
- Parameters
spine_db_editor (SpineDBEditor) – ‘owner’
x (float) – x-coordinate of central point
y (float) – y-coordinate of central point
extent (int) – Preferred extent
db_map_ids (tuple) – tuple of (db_map, id) tuples
- has_unique_key()[source]
Returns whether or not the item still has a single key in all the databases it represents.
- Returns
bool
- default_parameter_data()[source]
Return data to put as default in a parameter table when this item is selected.
- shape()[source]
Returns a shape containing the entire bounding rect, to work better with icon transparency.
- apply_rotation(angle, center)[source]
Applies rotation.
- Parameters
angle (float) – The angle in degrees.
center (QPointF) – Rotates around this point.
- mouseMoveEvent(event)[source]
Moves the item and all connected arcs.
- Parameters
event (QGraphicsSceneMouseEvent) –
- itemChange(change, value)[source]
Keeps track of item’s movements on the scene. Rotates svg item if the relationship is 2D. This makes it possible to define e.g. an arow icon for relationships that express direction.
- Parameters
change (GraphicsItemChange) – a flag signalling the type of the change
value – a value related to the change
- Returns
the same value given as input
- setVisible(on)[source]
Sets visibility status for this item and all arc items.
- Parameters
on (bool) –
- contextMenuEvent(e)[source]
Shows context menu.
- Parameters
e (QGraphicsSceneMouseEvent) – Mouse event
Populates the ‘Expand’ or ‘Collapse’ menu.
- Parameters
menu (QMenu) –
Populates the ‘Add relationships’ menu.
- Parameters
menu (QMenu) –
- class spinetoolbox.spine_db_editor.graphics_items.ArcItem(ent_item, el_item, width)[source]
Bases:
PySide6.QtWidgets.QGraphicsPathItem
Connects two EntityItems.
- Parameters
ent_item (spinetoolbox.widgets.graph_view_graphics_items.EntityItem) – entity item
el_item (spinetoolbox.widgets.graph_view_graphics_items.EntityItem) – element item
width (float) – Preferred line width
- class spinetoolbox.spine_db_editor.graphics_items.CrossHairsItem(*args, **kwargs)[source]
Bases:
EntityItem
Creates new relationships directly in the graph.
- Parameters
spine_db_editor (SpineDBEditor) – ‘owner’
x (float) – x-coordinate of central point
y (float) – y-coordinate of central point
extent (int) – Preferred extent
db_map_ids (tuple) – tuple of (db_map, id) tuples
- class spinetoolbox.spine_db_editor.graphics_items.CrossHairsEntityItem(*args, **kwargs)[source]
Bases:
EntityItem
Represents the relationship that’s being created using the CrossHairsItem.
- Parameters
spine_db_editor (SpineDBEditor) – ‘owner’
x (float) – x-coordinate of central point
y (float) – y-coordinate of central point
extent (int) – Preferred extent
db_map_ids (tuple) – tuple of (db_map, id) tuples
- class spinetoolbox.spine_db_editor.graphics_items.CrossHairsArcItem(ent_item, el_item, width)[source]
Bases:
ArcItem
Connects a CrossHairsEntityItem with the CrossHairsItem, and with all the EntityItem’s in the relationship so far.
- Parameters
ent_item (spinetoolbox.widgets.graph_view_graphics_items.EntityItem) – entity item
el_item (spinetoolbox.widgets.graph_view_graphics_items.EntityItem) – element item
width (float) – Preferred line width
- class spinetoolbox.spine_db_editor.graphics_items.EntityLabelItem(entity_item)[source]
Bases:
PySide6.QtWidgets.QGraphicsTextItem
Provides a label for EntityItem.
Initializes item.
- Parameters
entity_item (spinetoolbox.widgets.graph_view_graphics_items.EntityItem) – The parent item.
- class spinetoolbox.spine_db_editor.graphics_items.BgItem(svg, parent=None)[source]
Bases:
PySide6.QtWidgets.QGraphicsRectItem
- class spinetoolbox.spine_db_editor.graphics_items._ResizableQGraphicsSvgItem(*args, **kwargs)[source]
Bases:
PySide6.QtSvgWidgets.QGraphicsSvgItem
spinetoolbox.spine_db_editor.helpers
Helpers and utilities for Spine Database editor.
Converts a 'foreign' string (from e.g. Excel) to entity class display icon. |
|
Converts a 'foreign' string (from e.g. Excel) to boolean. |
spinetoolbox.spine_db_editor.main
spinetoolbox.spine_db_editor.scenario_generation
Contains functions for automatically generating scenarios from a set of alternatives.
|
Creates all possible combinations of alternatives. |
|
Creates all possible single-alternative scenarios. |
spinetoolbox.widgets
Init file for widgets package. Intentionally empty.
Submodules
spinetoolbox.widgets.about_widget
A widget for presenting basic information about the application.
About widget class. |
- class spinetoolbox.widgets.about_widget.AboutWidget(toolbox)[source]
Bases:
PySide6.QtWidgets.QWidget
About widget class.
- Parameters
toolbox (ToolboxUI) – QMainWindow instance
- calc_pos()[source]
Calculate the top-left corner position of this widget in relation to main window position and size in order to show about window in the middle of the main window.
- keyPressEvent(e)[source]
Close form when Escape, Enter, Return, or Space bar keys are pressed.
- Parameters
e (QKeyEvent) – Received key press event.
- closeEvent(event=None)[source]
Handle close window.
- Parameters
event (QEvent) – Closing event if ‘X’ is clicked.
- mousePressEvent(e)[source]
Save mouse position at the start of dragging.
- Parameters
e (QMouseEvent) – Mouse event
spinetoolbox.widgets.add_project_item_widget
Widget shown to user when a new Project Item is created.
A widget to query user's preferences for a new item. |
- class spinetoolbox.widgets.add_project_item_widget.AddProjectItemWidget(toolbox, x, y, class_, spec='')[source]
Bases:
PySide6.QtWidgets.QWidget
A widget to query user’s preferences for a new item.
- x
X coordinate of new item
- Type
int
- y
Y coordinate of new item
- Type
int
Initialize class.
- abstract call_add_item()[source]
Creates new Item according to user’s selections.
Must be reimplemented by subclasses.
spinetoolbox.widgets.add_up_spine_opt_wizard
Classes for custom QDialogs for julia setup.
Enum where members are also (and must be) ints |
|
A wizard to install & upgrade SpineOpt. |
|
A QWizards page with a log. Useful for pages that need to capture the output of a process. |
|
A QWizards page with a log. Useful for pages that need to capture the output of a process. |
|
A QWizards page with a log. Useful for pages that need to capture the output of a process. |
|
|
- class spinetoolbox.widgets.add_up_spine_opt_wizard._PageId[source]
Bases:
enum.IntEnum
Enum where members are also (and must be) ints
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.widgets.add_up_spine_opt_wizard.AddUpSpineOptWizard(parent, julia_exe, julia_project)[source]
Bases:
PySide6.QtWidgets.QWizard
A wizard to install & upgrade SpineOpt.
- Parameters
parent (QWidget) – the parent widget (SettingsWidget)
julia_exe (str) – path to Julia executable
julia_project (str) – path to Julia project
- class spinetoolbox.widgets.add_up_spine_opt_wizard.IntroPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.add_up_spine_opt_wizard.SelectJuliaPage(parent, julia_exe, julia_project)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.add_up_spine_opt_wizard.CheckPreviousInstallPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.add_up_spine_opt_wizard.AddUpSpineOptPage(parent)[source]
Bases:
spinetoolbox.widgets.custom_qwidgets.QWizardProcessPage
A QWizards page with a log. Useful for pages that need to capture the output of a process.
- class spinetoolbox.widgets.add_up_spine_opt_wizard.SuccessPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.add_up_spine_opt_wizard.FailurePage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.add_up_spine_opt_wizard.TroubleshootProblemsPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.add_up_spine_opt_wizard.TroubleshootSolutionPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.add_up_spine_opt_wizard.ResetRegistryPage(parent)[source]
Bases:
spinetoolbox.widgets.custom_qwidgets.QWizardProcessPage
A QWizards page with a log. Useful for pages that need to capture the output of a process.
- class spinetoolbox.widgets.add_up_spine_opt_wizard.AddUpSpineOptAgainPage(parent)[source]
Bases:
AddUpSpineOptPage
A QWizards page with a log. Useful for pages that need to capture the output of a process.
spinetoolbox.widgets.array_editor
Contains an editor widget for array type parameter values.
Editor widget for Arrays. |
- class spinetoolbox.widgets.array_editor.ArrayEditor(parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
Editor widget for Arrays.
- Parameters
parent (QWidget, optional) – parent widget
- set_value(value)[source]
Sets the parameter_value for editing in this widget.
- Parameters
value (Array) – value for editing
- _check_if_plotting_enabled(type_name)[source]
Checks is array’s data type allows the array to be plotted.
- Parameters
type_name (str) – data type’s name
- open_value_editor(index)[source]
Opens an editor widget for array element.
- Parameters
index (QModelIndex) – element’s index
Shows the table’s context menu.
- Parameters
position (QPoint) – menu’s position on the table
spinetoolbox.widgets.array_value_editor
An editor dialog for Array elements.
Editor widget for Array elements. |
- class spinetoolbox.widgets.array_value_editor.ArrayValueEditor(index, value_type, parent=None)[source]
Bases:
spinetoolbox.widgets.parameter_value_editor_base.ParameterValueEditorBase
Editor widget for Array elements.
- Parameters
index (QModelIndex) – an index to a parameter_value in parent_model
parent (QWidget, optional) – a parent widget
spinetoolbox.widgets.code_text_edit
Provides simple text editor for programming purposes.
spinetoolbox.widgets.commit_dialog
Classes for custom QDialogs to add edit and remove database items.
A dialog to query user's preferences for new commit. |
spinetoolbox.widgets.custom_combobox
Contains custom combo box classes.
A custom QComboBox for showing kernels in Settings->Tools. |
|
Combobox with elided text. |
|
- class spinetoolbox.widgets.custom_combobox.CustomQComboBox[source]
Bases:
PySide6.QtWidgets.QComboBox
A custom QComboBox for showing kernels in Settings->Tools.
- class spinetoolbox.widgets.custom_combobox.ElidedCombobox[source]
Bases:
PySide6.QtWidgets.QComboBox
Combobox with elided text.
spinetoolbox.widgets.custom_delegates
Custom item delegates.
A delegate that places a fully functioning QCheckBox. |
|
A delegate that places a QCheckBox but draws a number instead of the check. |
- class spinetoolbox.widgets.custom_delegates.ComboBoxDelegate(items)[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
- class spinetoolbox.widgets.custom_delegates.CheckBoxDelegate(parent, centered=True)[source]
Bases:
PySide6.QtWidgets.QStyledItemDelegate
A delegate that places a fully functioning QCheckBox.
- Parameters
parent (QWiget) –
centered (bool) – whether or not the checkbox should be center-aligned in the widget
- createEditor(parent, option, index)[source]
Important, otherwise an editor is created if the user clicks in this cell. ** Need to hook up a signal to the model.
- editorEvent(event, model, option, index)[source]
Change the data in the model and the state of the checkbox when user presses left mouse button and this cell is editable. Otherwise do nothing.
- class spinetoolbox.widgets.custom_delegates.RankDelegate(parent, centered=True)[source]
Bases:
CheckBoxDelegate
A delegate that places a QCheckBox but draws a number instead of the check.
- Parameters
parent (QWiget) –
centered (bool) – whether or not the checkbox should be center-aligned in the widget
spinetoolbox.widgets.custom_qgraphicsscene
Custom QGraphicsScene used in the Design View.
A custom QGraphicsScene. It provides signals to notify about items, |
|
A scene for the Design view. |
- class spinetoolbox.widgets.custom_qgraphicsscene.CustomGraphicsScene[source]
Bases:
PySide6.QtWidgets.QGraphicsScene
A custom QGraphicsScene. It provides signals to notify about items, and a method to center all items in the scene.
At the moment it’s used by DesignGraphicsScene and the GraphViewMixin
- class spinetoolbox.widgets.custom_qgraphicsscene.DesignGraphicsScene(parent, toolbox)[source]
Bases:
CustomGraphicsScene
A scene for the Design view.
Mainly, it handles drag and drop events of ProjectItemDragMixin sources.
- Parameters
parent (QObject) – scene’s parent object
toolbox (ToolboxUI) – reference to the main window
- mousePressEvent(event)[source]
Puts link drawer to sleep and logs message if it looks like the user doesn’t know what they’re doing.
- mouseReleaseEvent(event)[source]
Makes link if drawer is released over a valid connector button or cancel link drawing on right button.
- handle_selection_changed()[source]
Activates items or links based on currently selected items (or links).
- set_bg_color(color)[source]
Change background color when this is changed in Settings.
- Parameters
color (QColor) – Background color
- set_bg_choice(bg_choice)[source]
Set background choice when this is changed in Settings.
- Parameters
bg (str) – “grid”, “tree”, or “solid”
- dragEnterEvent(event)[source]
Accept event. Then call the super class method only if drag source is not a ProjectItemDragMixin.
- dragMoveEvent(event)[source]
Accept event. Then call the super class method only if drag source is not a ProjectItemDragMixin.
- dropEvent(event)[source]
Only accept drops when the source is an instance of ProjectItemDragMixin. Capture text from event’s mimedata and show the appropriate ‘Add Item form.’
- event(event)[source]
Accepts GraphicsSceneHelp events without doing anything, to not interfere with our usage of QToolTip.showText in graphics_items.ExclamationIcon.
spinetoolbox.widgets.custom_qgraphicsviews
Classes for custom QGraphicsViews for the Design and Graph views.
Super class for Design and Entity QGraphicsViews. |
|
QGraphicsView for the Design View. |
|
Makes a left-click mouse event that is otherwise close of given event. |
- class spinetoolbox.widgets.custom_qgraphicsviews.CustomQGraphicsView(parent)[source]
Bases:
PySide6.QtWidgets.QGraphicsView
Super class for Design and Entity QGraphicsViews.
- Parameters
parent (QWidget) – parent widget
- keyPressEvent(event)[source]
Enables zooming with plus and minus keys (comma resets zoom).
- Parameters
event (QKeyEvent) – key press event
- mousePressEvent(event)[source]
Sets rubber band selection mode if Control or right mouse button is pressed. Enables resetting the zoom factor from the middle mouse button.
- _drag_duration_passed(mouse_event)[source]
Test is drag duration has passed.
- Parameters
mouse_event (QMouseEvent) – current mouse event
- resizeEvent(event)[source]
Updates zoom if needed when the view is resized.
- Parameters
event (QResizeEvent) – a resize event
- setScene(scene)[source]
Sets a new scene to this view.
- Parameters
scene (DesignGraphicsScene) – a new scene
- _update_zoom_limits()[source]
Updates the minimum zoom limit and the zoom level with which the view fits all the items in the scene.
- _handle_zoom_time_line_advanced(pos)[source]
Performs zoom whenever the smooth zoom time line advances.
- _handle_transformation_time_line_finished()[source]
Cleans up after the smooth transformation time line finishes.
- gentle_zoom(factor, zoom_focus=None)[source]
Perform a zoom by a given factor.
- Parameters
factor (float) – a scaling factor relative to the current scene scaling
zoom_focus (QPoint) – focus of the zoom, e.g. mouse pointer position
- _set_preferred_scene_rect()[source]
Sets the scene rect to the result of uniting the scene viewport rect and the items bounding rect.
Disables the context menu.
Enables the context menu.
- class spinetoolbox.widgets.custom_qgraphicsviews.DesignQGraphicsView(parent)[source]
Bases:
CustomQGraphicsView
QGraphicsView for the Design View.
- Parameters
parent (QWidget) – parent widget
- add_icon(item_name)[source]
Adds project item’s icon to the scene.
- Parameters
item_name (str) – project item’s name
- remove_icon(item_name)[source]
Removes project item’s icon from scene.
- Parameters
item_name (str) – name of the icon to remove
- add_link(src_connector, dst_connector)[source]
Pushes an AddLinkCommand to the toolbox undo stack.
- Parameters
src_connector (ConnectorButton) – source connector button
dst_connector (ConnectorButton) – destination connector button
- do_add_link(connection)[source]
Adds given connection to the Design view.
- Parameters
connection (Connection) – the connection to add
- do_update_link(updated_connection)[source]
Replaces a link on the Design view.
- Parameters
updated_connection (Connection) – connection that was updated
- remove_links(links)[source]
Pushes a RemoveConnectionsCommand to the Toolbox undo stack.
- Parameters
links (list of Link) – links to remove
- do_remove_link(connection)[source]
Removes a link from the scene.
- Parameters
connection (ConnectionBase) – link’s connection
- take_link(link)[source]
Remove link, then start drawing another one from the same source connector.
- add_jump(src_connector, dst_connector)[source]
Pushes an AddJumpCommand to the Toolbox undo stack.
- Parameters
src_connector (ConnectorButton) – source connector button
dst_connector (ConnectorButton) – destination connector button
spinetoolbox.widgets.custom_qlineedits
Contains a custom line edit.
A custom QLineEdit for Project Item Properties. |
- class spinetoolbox.widgets.custom_qlineedits.PropertyQLineEdit[source]
Bases:
spinetoolbox.widgets.custom_qwidgets.UndoRedoMixin
,PySide6.QtWidgets.QLineEdit
A custom QLineEdit for Project Item Properties.
spinetoolbox.widgets.custom_qtableview
Custom QTableView classes that support copy-paste and the like.
Custom QTableView class with copy and paste methods. |
|
Custom QTableView class with autofilter functionality. |
|
Custom QTableView base class with copy and paste methods for indexed parameter values. |
|
A QTableView for fixed resolution time series table. |
|
A QTableView class with for variable resolution time series and time patterns. |
|
Custom QTableView with copy and paste methods for single column tables. |
|
Custom QTableView with copy and paste methods for map tables. |
|
Returns the top left and bottom right corners of selection. |
Evaluates if given string could be a time stamp. |
|
- class spinetoolbox.widgets.custom_qtableview.CopyPasteTableView(parent=None)[source]
Bases:
PySide6.QtWidgets.QTableView
Custom QTableView class with copy and paste methods.
- init_copy_and_paste_actions()[source]
Initializes copy and paste actions and connects relevant signals.
- set_external_copy_and_paste_actions(copy_action, paste_action)[source]
Sets the view to use external copy and paste actions.
Note that this doesn’t connect the actions’ trigger signals; the owner of the actions is responsible for handling them.
- Parameters
copy_action (QAction) – copy action
paste_action (QAction) – paste action
- static _read_pasted_text(text)[source]
Parses a tab separated CSV text table.
- Parameters
text (str) – a CSV formatted table
- Returns
a list of rows
- Return type
list
- class spinetoolbox.widgets.custom_qtableview.AutoFilterCopyPasteTableView(parent)[source]
Bases:
CopyPasteTableView
Custom QTableView class with autofilter functionality.
- Parameters
parent (QObject) –
- setModel(model)[source]
Disconnects the sectionPressed signal which seems to be connected by the super method. Otherwise pressing the header just selects the column.
- Parameters
model (QAbstractItemModel) –
Shows current column’s auto filter menu.
Called when user clicks on a horizontal section header. Shows/hides the auto filter widget.
- Parameters
logical_index (int) – header section index
- class spinetoolbox.widgets.custom_qtableview.IndexedParameterValueTableViewBase(parent=None)[source]
Bases:
CopyPasteTableView
Custom QTableView base class with copy and paste methods for indexed parameter values.
- class spinetoolbox.widgets.custom_qtableview.TimeSeriesFixedResolutionTableView(parent=None)[source]
Bases:
IndexedParameterValueTableViewBase
A QTableView for fixed resolution time series table.
- static _read_pasted_text(text)[source]
Parses the given CSV table. Parsing is locale aware.
- Parameters
text (str) – a CSV table containing numbers
- Returns
A list of floats
- Return type
list of float
- _paste_to_values_column(values, first_row, paste_length)[source]
Pastes data to the Values column.
- Parameters
values (list) – a list of float values to paste
first_row (int) – index of the first row where to paste
paste_length (int) – length of the paste selection (can be different from len(values))
- Returns
A tuple (list(pasted indexes), list(pasted values))
- Return type
tuple
- class spinetoolbox.widgets.custom_qtableview.IndexedValueTableView(parent=None)[source]
Bases:
IndexedParameterValueTableViewBase
A QTableView class with for variable resolution time series and time patterns.
- _paste_two_columns(data_indexes, data_values, first_row, paste_length)[source]
Pastes data indexes and values.
- Parameters
data_indexes (list) – a list of data indexes (time stamps/durations)
data_values (list) – a list of data values
first_row (int) – first row index
paste_length (int) – selection length for pasting
- Returns
a tuple (modified model indexes, modified model values)
- Return type
tuple
- _paste_single_column(values, first_row, first_column, paste_length)[source]
Pastes a single column of data.
- Parameters
values (list) – a list of data to paste (data indexes or values)
first_row (int) – first row index
paste_length (int) – selection length for pasting
- Returns
a tuple (modified model indexes, modified model values)
- Return type
tuple
- class spinetoolbox.widgets.custom_qtableview.ArrayTableView(parent=None)[source]
Bases:
IndexedParameterValueTableViewBase
Custom QTableView with copy and paste methods for single column tables.
- class spinetoolbox.widgets.custom_qtableview.MapTableView(parent=None)[source]
Bases:
CopyPasteTableView
Custom QTableView with copy and paste methods for map tables.
- copy(_=False)[source]
Copies current selection to clipboard in Excel compatible CSV format.
- Returns
True if data was copied on the clipboard, False otherwise
- Return type
bool
- spinetoolbox.widgets.custom_qtableview._range(selection)[source]
Returns the top left and bottom right corners of selection.
- Parameters
selection (QItemSelection) – a list of selected QItemSelection objects
- Returns
a tuple (top row, bottom row, left column, right column)
- Return type
tuple of ints
- spinetoolbox.widgets.custom_qtableview._could_be_time_stamp(s)[source]
Evaluates if given string could be a time stamp.
This is to deal with special cases that are not intended as time stamps but could end up as one by the very greedy
DateTime
constructor.- Parameters
s (str) – string to evaluate
- Returns
True if s could be a time stamp, False otherwise
- Return type
bool
spinetoolbox.widgets.custom_qtextbrowser
Class for a custom QTextBrowser for showing the logs and tool output.
Custom QTextBrowser class. |
|
Custom QTextBrowser class. |
- class spinetoolbox.widgets.custom_qtextbrowser.CustomQTextBrowser(parent)[source]
Bases:
PySide6.QtWidgets.QTextBrowser
Custom QTextBrowser class.
- Parameters
parent (QWidget) – Parent widget
- append(text)[source]
Appends new text block to the end of the original document.
If the document contains more text blocks after the addition than a set limit, blocks are deleted at the start of the contents.
- Parameters
text (str) – text to add
- contextMenuEvent(event)[source]
Reimplemented method to add a clear action into the default context menu.
- Parameters
event (QContextMenuEvent) – Received event
- make_log_entry_point(timestamp)[source]
Creates cursors (log entry points) for given items in event log.
- Parameters
timestamp (str) – time stamp
- class spinetoolbox.widgets.custom_qtextbrowser.MonoSpaceFontTextBrowser(parent)[source]
Bases:
CustomQTextBrowser
Custom QTextBrowser class.
- Parameters
parent (QWidget) – Parent widget
spinetoolbox.widgets.custom_qtreeview
Classes for custom QTreeView.
Custom QTreeView class with copy and paste support. |
|
Custom QTreeView class for 'Sources' in Tool specification editor widget. |
|
Custom QTreeView class for Tool specification editor form to enable keyPressEvent. |
- class spinetoolbox.widgets.custom_qtreeview.CopyPasteTreeView(parent)[source]
Bases:
PySide6.QtWidgets.QTreeView
Custom QTreeView class with copy and paste support.
- Parameters
parent (QWidget) – parent widget
- can_copy()[source]
Returns True if tree view has a selection to copy from.
- Returns
True if there is something to copy
- Return type
bool
- can_paste()[source]
Returns whether it is possible to paste into this view.
- Returns
True if pasting is possible, False otherwise
- Return type
bool
- class spinetoolbox.widgets.custom_qtreeview.SourcesTreeView(parent)[source]
Bases:
PySide6.QtWidgets.QTreeView
Custom QTreeView class for ‘Sources’ in Tool specification editor widget.
- Parameters
parent (QWidget) – parent widget
spinetoolbox.widgets.custom_qwidgets
Custom QWidgets for Filtering and Zooming.
Filter widget class. |
|
A QWidgetAction with custom hovering. |
|
An action with a tool bar. |
|
A toolbar on the right, with enough space to print a text beneath. |
|
A toolbar on the right, with enough space to print a text beneath. |
|
A menu item with a toolbar on the right. |
|
A custom tool bar for |
|
A titled separator. |
|
A QLabel that always wraps text. |
|
A QLabel that supports hyperlinks. |
|
A QWizards page with a log. Useful for pages that need to capture the output of a process. |
|
A read only QLabel with a QToolButton that copies the text to clipboard. |
|
A QLabel with elided text. |
|
A spinbox where undo and redo key strokes apply to the project. |
|
Dialog that lets selecting database items. |
|
Dialog that lets selecting database items. |
- class spinetoolbox.widgets.custom_qwidgets.FilterWidget(parent, make_filter_model, *args, **kwargs)[source]
Bases:
PySide6.QtWidgets.QWidget
Filter widget class.
Init class.
- Parameters
parent (QWidget, optional) – parent widget
make_filter_model (Callable) – callable that constructs the filter model
*args – arguments forwarded to
make_filter_model
**kwargs – keyword arguments forwarded to
make_filter_model
- class spinetoolbox.widgets.custom_qwidgets.CustomWidgetAction(parent=None)[source]
Bases:
PySide6.QtWidgets.QWidgetAction
A QWidgetAction with custom hovering.
Class constructor.
- Parameters
parent (QMenu) – the widget’s parent
- class spinetoolbox.widgets.custom_qwidgets.ToolBarWidgetAction(text, parent=None, compact=False)[source]
Bases:
CustomWidgetAction
An action with a tool bar.
- tool_bar
- Type
QToolBar
Class constructor.
- Parameters
parent (QMenu) – the widget’s parent
- class spinetoolbox.widgets.custom_qwidgets.ToolBarWidgetBase(text, parent=None, io_files=None)[source]
Bases:
PySide6.QtWidgets.QWidget
A toolbar on the right, with enough space to print a text beneath.
- tool_bar
- Type
QToolBar
Class constructor.
- Parameters
text (str) –
parent (QWidget) – the widget’s parent
- class spinetoolbox.widgets.custom_qwidgets.ToolBarWidget(text, parent=None, io_files=None)[source]
Bases:
ToolBarWidgetBase
A toolbar on the right, with enough space to print a text beneath.
- tool_bar
- Type
QToolBar
Class constructor.
- Parameters
text (str) –
parent (QWidget) – the widget’s parent
- class spinetoolbox.widgets.custom_qwidgets.MenuItemToolBarWidget(text, parent=None, compact=False)[source]
Bases:
ToolBarWidgetBase
A menu item with a toolbar on the right.
Class constructor.
- Parameters
text (str) –
parent (QWidget) – the widget’s parent
compact (bool) – if True, the widget uses the minimal space
- class spinetoolbox.widgets.custom_qwidgets._MenuToolBar(parent=None)[source]
Bases:
PySide6.QtWidgets.QToolBar
A custom tool bar for
MenuItemToolBarWidget
.- add_frame(left, right, title)[source]
Add frame around given actions, with given title.
- Parameters
left (QAction) –
right (QAction) –
title (str) –
- _setup_action_button(action)[source]
- Customizes the QToolButton associated with given action:
Makes sure that the text honors the action’s mnemonics.
Installs this as event filter on the button (see
self.eventFilter()
).
Must be called everytime an action is added to the tool bar.
- Parameters
action (QAction) – Action to set up
- actionEvent(ev)[source]
Updates
self._enabled
: True if at least one non-separator action is enabled, False otherwise. Emitsself.enabled_changed
accordingly.
- class spinetoolbox.widgets.custom_qwidgets.TitleWidgetAction(title, parent=None)[source]
Bases:
CustomWidgetAction
A titled separator.
Class constructor.
- Parameters
parent (QMenu) – the widget’s parent
- class spinetoolbox.widgets.custom_qwidgets.WrapLabel(text='', parent=None)[source]
Bases:
PySide6.QtWidgets.QLabel
A QLabel that always wraps text.
- class spinetoolbox.widgets.custom_qwidgets.HyperTextLabel(text='', parent=None)[source]
Bases:
WrapLabel
A QLabel that supports hyperlinks.
- class spinetoolbox.widgets.custom_qwidgets.QWizardProcessPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
A QWizards page with a log. Useful for pages that need to capture the output of a process.
- class spinetoolbox.widgets.custom_qwidgets.LabelWithCopyButton(text='', parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
A read only QLabel with a QToolButton that copies the text to clipboard.
- class spinetoolbox.widgets.custom_qwidgets.ElidedLabel(*args, **kwargs)[source]
Bases:
ElidedTextMixin
,PySide6.QtWidgets.QLabel
A QLabel with elided text.
- class spinetoolbox.widgets.custom_qwidgets.HorizontalSpinBox(*args, **kwargs)[source]
Bases:
PySide6.QtWidgets.QToolBar
- class spinetoolbox.widgets.custom_qwidgets.PropertyQSpinBox[source]
Bases:
UndoRedoMixin
,PySide6.QtWidgets.QSpinBox
A spinbox where undo and redo key strokes apply to the project.
- class spinetoolbox.widgets.custom_qwidgets.SelectDatabaseItemsDialog(checked_states, ok_button_text=None, parent=None)[source]
Bases:
PySide6.QtWidgets.QDialog
Dialog that lets selecting database items.
- Parameters
checked_states (dict, optional) – checked states for each item
ok_button_text (str, optional) – alternative label for the OK button
parent (QWidget, optional) – parent widget
- class spinetoolbox.widgets.custom_qwidgets.PurgeSettingsDialog(checked_states, ok_button_text=None, parent=None)[source]
Bases:
SelectDatabaseItemsDialog
Dialog that lets selecting database items.
- Parameters
checked_states (dict, optional) – checked states for each item
ok_button_text (str, optional) – alternative label for the OK button
parent (QWidget, optional) – parent widget
spinetoolbox.widgets.datetime_editor
An editor widget for editing datetime database (relationship) parameter values.
An editor widget for DateTime type parameter values. |
Converts a QDateTime object to Python's datetime.datetime type. |
|
Converts Python's datetime.datetime object to QDateTime. |
- spinetoolbox.widgets.datetime_editor._QDateTime_to_datetime(dt)[source]
Converts a QDateTime object to Python’s datetime.datetime type.
- spinetoolbox.widgets.datetime_editor._datetime_to_QDateTime(dt)[source]
Converts Python’s datetime.datetime object to QDateTime.
spinetoolbox.widgets.duration_editor
An editor widget for editing duration database (relationship) parameter values.
spinetoolbox.widgets.install_julia_wizard
Classes for custom QDialogs for julia setup.
Enum where members are also (and must be) ints |
|
A wizard to install julia |
|
A QWizards page with a log. Useful for pages that need to capture the output of a process. |
|
- class spinetoolbox.widgets.install_julia_wizard._PageId[source]
Bases:
enum.IntEnum
Enum where members are also (and must be) ints
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.widgets.install_julia_wizard.InstallJuliaWizard(parent)[source]
Bases:
PySide6.QtWidgets.QWizard
A wizard to install julia
Initialize class.
- Parameters
parent (QWidget) – the parent widget (SettingsWidget)
- class spinetoolbox.widgets.install_julia_wizard.JillNotFoundPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.install_julia_wizard.IntroPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.install_julia_wizard.SelectDirsPage(parent)[source]
Bases:
PySide6.QtWidgets.QWizardPage
- class spinetoolbox.widgets.install_julia_wizard.InstallJuliaPage(parent)[source]
Bases:
spinetoolbox.widgets.custom_qwidgets.QWizardProcessPage
A QWizards page with a log. Useful for pages that need to capture the output of a process.
spinetoolbox.widgets.jump_properties_widget
Contains jump properties widget’s business logic.
Widget for jump link properties. |
- class spinetoolbox.widgets.jump_properties_widget.JumpPropertiesWidget(toolbox, base_color=None)[source]
Bases:
spinetoolbox.widgets.properties_widget.PropertiesWidgetBase
Widget for jump link properties.
- Parameters
toolbox (ToolboxUI) – The toolbox instance where this widget should be embedded
- set_link(jump)[source]
Hooks the widget to given jump link, so that user actions are reflected in the jump link’s configuration.
- Parameters
jump (LoggingJump) – link to hook into
spinetoolbox.widgets.jupyter_console_widget
Class for a custom RichJupyterWidget that can run Tool instances.
Base class for all embedded console widgets that can run tool instances. |
- class spinetoolbox.widgets.jupyter_console_widget.JupyterConsoleWidget(toolbox, kernel_name, owner=None)[source]
Bases:
qtconsole.rich_jupyter_widget.RichJupyterWidget
Base class for all embedded console widgets that can run tool instances.
- Parameters
toolbox (ToolboxUI) – QMainWindow instance
kernel_name (str) – Kernel name to start
owner (ProjectItem, NoneType) – Item that owns the console.
- request_start_kernel(conda=False)[source]
Requests Spine Engine to launch a kernel manager for the given kernel_name.
- Parameters
conda (bool) – Conda kernel or not
- Returns
Path to connection file if kernel manager was launched successfully, None otherwise
- Return type
str or None
- _handle_kernel_started_msg(msg)[source]
Handles the response message from KernelExecutionManager.
- Parameters
msg (dict) – Message with item_name, type, etc. keys
- Returns
Path to a connection file if engine started the requested kernel manager successfully, None otherwise.
- Return type
str or None
- _execute(source, hidden)[source]
Catches exit or similar commands and closes the console immediately if user so chooses.
- insert_text_to_console(msg)[source]
Inserts given message to console.
- Parameters
msg (str) – Text to insert
- set_connection_file(connection_file)[source]
Sets connection file obtained from engine to this console.
- Parameters
connection_file (str) – Path to a connection file obtained from a running kernel manager.
- connect_to_kernel()[source]
Connects a local kernel client to a kernel manager running on Spine Engine.
- request_restart_kernel_manager()[source]
Restarts kernel manager on engine and connects a new kernel client to it.
Reimplemented to add actions to console context-menus.
spinetoolbox.widgets.kernel_editor
Widget for showing the progress of making a Julia or Python kernel.
Base class for kernel editors. |
|
A Simple Python kernel maker. The Python executable path is passed in |
|
A Simple Julia Kernel maker. The julia exe and project are passed in |
|
Formats message for the kernel editor text browser. |
|
Formats process message for the kernel editor text browser. |
- class spinetoolbox.widgets.kernel_editor.KernelEditorBase(parent, python_or_julia)[source]
Bases:
PySide6.QtWidgets.QDialog
Base class for kernel editors.
- Parameters
parent (SettingsWidget) – Parent widget
python_or_julia (str) – kernel type; valid values: “julia”, “python”
- _solve_new_kernel_name()[source]
Finds out the new kernel name after a new kernel has been created.
- check_options(prgm, kernel_name, display_name, python_or_julia)[source]
Checks that user options are valid before advancing with kernel making.
- Parameters
prgm (str) – Full path to Python or Julia program
kernel_name (str) – Kernel name
display_name (str) – Kernel display name
python_or_julia (str) – Either ‘python’ or ‘julia’
- Returns
True if all user input is valid for making a new kernel, False otherwise
- Return type
bool
- make_python_kernel(checked=False)[source]
Makes a new Python kernel. Offers to install ipykernel package if it is missing from the selected Python environment. Overwrites existing kernel with the same name if this is ok by user.
- static is_package_installed(python_path, package_name)[source]
Checks if given package is installed to given Python environment.
- Parameters
python_path (str) – Full path to selected Python interpreter
package_name (str) – Package name
- Returns
True if installed, False if not
- Return type
(bool)
- start_package_install_process(python_path, package_name)[source]
Starts installing the given package using pip.
- Parameters
python_path (str) – Full path to selected Python interpreter
package_name (str) – Package name to install using pip
- handle_package_install_process_finished(retval)[source]
Handles installing package finished.
- Parameters
retval (int) – Process return value. 0: success, !0: failure
- start_kernelspec_install_process(prgm, k_name, d_name)[source]
Installs kernel specifications for the given Python environment. Runs e.g. this command in QProcess
python -m ipykernel install –user –name python-X.Y –display-name PythonX.Y
Creates new kernel specs into %APPDATA%jupyterkernels. Existing directory will be overwritten.
Note: We cannot use –sys.prefix here because if we have selected to create a kernel for some other python that was used in launching the app, the kernel will be created into a location that is not discoverable by jupyter and hence not by Spine Toolbox. E.g. when sys.executable is C:Python36python.exe, and we have selected that as the python for Spine Toolbox (Settings->Tools->Python interpreter is empty), creating a kernel with –sys-prefix creates kernel specs into C:Python36sharejupyterkernelspython-3.6. This is ok and the kernel spec is discoverable by jupyter and Spine Toolbox.
BUT when sys.executable is C:Python36python.exe, and we have selected another python for Spine Toolbox (Settings->Tools->Python interpreter is C:Python38python.exe), creating a kernel with –sys-prefix creates a kernel into C:Python38sharejupyterkernelspython-3.8-sys-prefix. This is not discoverable by jupyter nor Spine Toolbox. You would need to start the app using C:Python38python.exe to see and use that kernel spec.
Using –user option instead, creates kernel specs that are discoverable by any python that was used in starting Spine Toolbox.
- Parameters
prgm (str) – Full path to Python interpreter for which the kernel is created
k_name (str) – Kernel name
d_name (str) – Kernel display name
- handle_kernelspec_install_process_finished(retval)[source]
Handles case when the process for installing the kernel has finished.
- Parameters
retval (int) – Process return value. 0: success, !0: failure
- make_julia_kernel(checked=False)[source]
Makes a new Julia kernel. Offers to install IJulia package if it is missing from the selected Julia project. Overwrites existing kernel with the same name if this is ok by user.
- is_ijulia_installed(program, project)[source]
Checks if IJulia is installed for the given project. Note: Trying command ‘using IJulia’ does not work since it automatically tries loading it from the LOAD_PATH if not it’s not found in the active project.
- Returns
0 when process failed to start, 1 when IJulia is installed, 2 when IJulia is not installed.
- Return type
int
- start_ijulia_install_process(julia, project)[source]
Starts installing IJulia package to given Julia project.
- Parameters
julia (str) – Full path to selected Julia executable
project (str) – Julia project (e.g. dir path or ‘@.’, or ‘.’)
- handle_ijulia_install_finished(ret)[source]
Runs when IJulia install process finishes.
- Parameters
ret (int) – Process return value. 0: success, !0: failure
- handle_ijulia_rebuild_finished(ret)[source]
Runs when IJulia rebuild process finishes.
- Parameters
ret (int) – Process return value. 0: success, !0: failure
- start_ijulia_installkernel_process(program, project, kernel_name)[source]
Installs the kernel using IJulia.installkernel function. Given kernel_name is the new kernel DISPLAY name prefix. IJulia strips the whitespace and uncapitalizes this to make the kernel name automatically. Julia version is concatenated to both kernel and display names automatically (This cannot be changed).
- handle_installkernel_process_finished(retval)[source]
Checks whether the IJulia.installkernel process finished successfully.
- Parameters
retval (int) – Process return value. 0: success, !0: failure
- restore_dialog_dimensions()[source]
Restore widget location, dimensions, and state from previous session.
- add_message(msg)[source]
Append regular message to kernel editor text browser.
- Parameters
msg (str) – String written to QTextBrowser
- add_success_message(msg)[source]
Append message with green text color to kernel editor text browser.
- Parameters
msg (str) – String written to QTextBrowser
- add_error_message(msg)[source]
Append message with red color to kernel editor text browser.
- Parameters
msg (str) – String written to QTextBrowser
- add_warning_message(msg)[source]
Append message with yellow (golden) color to kernel editor text browser.
- Parameters
msg (str) – String written to QTextBrowser
- add_process_message(msg)[source]
Writes message from stdout to kernel editor text browser.
- Parameters
msg (str) – String written to QTextBrowser
- class spinetoolbox.widgets.kernel_editor.MiniPythonKernelEditor(parent, python_exe)[source]
Bases:
KernelEditorBase
A Simple Python kernel maker. The Python executable path is passed in the constructor, then calling
make_kernel
starts the process.- Parameters
parent (SettingsWidget) – Parent widget
python_or_julia (str) – kernel type; valid values: “julia”, “python”
- class spinetoolbox.widgets.kernel_editor.MiniJuliaKernelEditor(parent, julia_exe, julia_project)[source]
Bases:
KernelEditorBase
A Simple Julia Kernel maker. The julia exe and project are passed in the constructor, then calling
make_kernel
starts the process.- Parameters
parent (SettingsWidget) – Parent widget
python_or_julia (str) – kernel type; valid values: “julia”, “python”
spinetoolbox.widgets.link_properties_widget
Link properties widget.
Widget for connection link properties. |
- class spinetoolbox.widgets.link_properties_widget.LinkPropertiesWidget(toolbox, base_color=None)[source]
Bases:
spinetoolbox.widgets.properties_widget.PropertiesWidgetBase
Widget for connection link properties.
- Parameters
toolbox (ToolboxUI) – The toolbox instance where this widget should be embedded
- set_link(connection)[source]
Hooks the widget to given link, so that user actions are reflected in the link’s filter configuration.
- Parameters
connection (LoggingConnection) –
- _handle_auto_check_filters_state_changed(checked)[source]
Updates filters’ auto enabled setting.
- Parameters
checked (bool) – True if the checkbox is checked, False otherwise
- set_auto_check_filters_state(checked)[source]
Sets the checked status of filter default online status check box
- Parameters
checked (bool) – True if the checkbox is checked
Adds actions to filter validation menu.
- Returns
menu actions
- Return type
dict
- _handle_purge_settings_changed()[source]
Pushes a command that sets new purge settings onto undo stack.
spinetoolbox.widgets.map_editor
An editor widget for editing a map type parameter values.
A widget for editing maps. |
- class spinetoolbox.widgets.map_editor.MapEditor(parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
A widget for editing maps.
- Parameters
parent (QWidget, optional) – parent widget
Opens table context menu.
- Parameters
position (QPoint) – menu’s position
spinetoolbox.widgets.map_value_editor
An editor dialog for map indexes and values.
Dialog for editing parameter values in Map value editor. |
- class spinetoolbox.widgets.map_value_editor.MapValueEditor(index, parent=None)[source]
Bases:
spinetoolbox.widgets.parameter_value_editor_base.ParameterValueEditorBase
Dialog for editing parameter values in Map value editor.
- Parameters
index (QModelIndex) – an index to a parameter_value in parent_model
parent (QWidget, optional) – a parent widget
spinetoolbox.widgets.multi_tab_spec_editor
Contains the MultiTabSpecEditor class.
A main window that has a tab widget as its central widget. |
- class spinetoolbox.widgets.multi_tab_spec_editor.MultiTabSpecEditor(toolbox, item_type)[source]
Bases:
spinetoolbox.widgets.multi_tab_window.MultiTabWindow
A main window that has a tab widget as its central widget.
- Parameters
qsettings (QSettings) – Toolbox settings
settings_group (str) – this window’s settings group in
qsettings
- _make_other()[source]
Creates a new MultiTabWindow of this type.
- Returns
new MultiTabWindow
- Return type
- _make_new_tab(*args, **kwargs)[source]
Creates a new tab.
- Parameters
*args – positional arguments neede to make a new tab
**kwargs – keyword arguments needed to make a new tab
- _connect_tab_signals(tab)[source]
Connects spec editor window (tab) signals.
- Parameters
tab (SpecificationEditorWindowBase) – Specification editor window
- Returns
True if ok, False otherwise
- Return type
bool
- _disconnect_tab_signals(index)[source]
Disconnects signals of spec editor window (tab) in given index.
- Parameters
index (int) – Tab index
- Returns
True if ok, False otherwise
- Return type
bool
Opens a context menu for the toolbar.
- Parameters
global_pos (QPoint) – menu position on screen
spinetoolbox.widgets.multi_tab_window
Contains the MultiTabWindow and TabBarPlus classes.
A main window that has a tab widget as its central widget. |
|
Tab bar that has a plus button floating to the right of the tabs. |
- class spinetoolbox.widgets.multi_tab_window.MultiTabWindow(qsettings, settings_group)[source]
Bases:
PySide6.QtWidgets.QMainWindow
A main window that has a tab widget as its central widget.
- Parameters
qsettings (QSettings) – Toolbox settings
settings_group (str) – this window’s settings group in
qsettings
- abstract _make_other()[source]
Creates a new MultiTabWindow of this type.
- Returns
new MultiTabWindow
- Return type
- others()[source]
List of other MultiTabWindows of the same type.
- Returns
other MultiTabWindows windows
- Return type
list of MultiTabWindow
- abstract _make_new_tab(*args, **kwargs)[source]
Creates a new tab.
- Parameters
*args – positional arguments neede to make a new tab
**kwargs – keyword arguments needed to make a new tab
Opens a context menu for the toolbar.
- Parameters
global_pos (QPoint) – menu position on screen
- name()[source]
Generates name based on the current tab and total tab count.
- Returns
a name
- Return type
str
- add_new_tab(*args, **kwargs)[source]
Creates a new tab and adds it at the end of the tab bar.
- Parameters
*args – parameters forwarded to
MutliTabWindow._make_new_tab()
**kwargs – parameters forwarded to
MultiTabwindow._make_new_tab()
- Returns
True if successful, False otherwise
- Return type
bool
- insert_new_tab(index, *args, **kwargs)[source]
Creates a new tab and inserts it at the given index.
- Parameters
index (int) – insertion point index
*args – parameters forwarded to
MutliTabWindow._make_new_tab()
**kwargs – parameters forwarded to
MultiTabwindow._make_new_tab()
- _add_connect_tab(tab, text)[source]
Appends a new tab and connects signals.
- Parameters
tab (QWidget) – tab contents widget
text (str) – appended tab title
- _insert_connect_tab(index, tab, text)[source]
Inserts a new tab and connects signals.
- Parameters
index (int) – insertion point index
tab (QWidget) – tab contents widget
text (str) – inserted tab title
- _remove_disconnect_tab(index)[source]
Disconnects and removes a tab.
- Parameters
index (int) – tab index
- _connect_tab(index)[source]
Connects signals from a tab contents widget.
- Parameters
index (int) – tab index
- _connect_tab_signals(tab)[source]
Connects signals from a tab contents widget.
- Parameters
tab (QWidget) – tab contents widget
- Returns
True if signals were connected successfully, False otherwise
- Return type
bool
- _disconnect_tab_signals(index)[source]
Disconnects signals from given tab.
- Parameters
index (int) – tab index
- Returns
True if signals were disconnected successfully, False otherwise
- Return type
bool
- _handle_tab_window_title_changed(tab, title)[source]
Updates tab’s title.
- Parameters
tab (QWidget) – tab’s content widget
title (str) – new tab title; if emtpy, one will be generated
- _take_tab(index)[source]
Removes a tab and returns its contents.
- Parameters
index (int) – tab index
- Returns
widget the tab was holding and tab’s title
- Return type
tuple
- move_tab(index, other=None)[source]
Moves a tab to another MultiTabWindow.
- Parameters
index (int) – tab index
other (MultiTabWindow, optional) – target window; if None, creates a new window
- detach(index, hot_spot, offset=0)[source]
Detaches the tab at given index into another MultiTabWindow window and starts dragging it.
- Parameters
index (int) –
hot_spot (QPoint) –
offset (int) –
- start_drag(hot_spot, offset=0)[source]
Starts dragging a detached tab.
- Parameters
hot_spot (QPoint) – The anchor point of the drag in widget coordinates.
offset (int) – Horizontal offset of the tab in the bar.
- _frame_height()[source]
Calculates the total ‘thickness’ of window frame in vertical direction.
- Returns
frame height
- Return type
int
- timerEvent(event)[source]
Performs the drag, i.e., moves the window with the mouse cursor. As soon as the mouse hovers the tab bar of another MultiTabWindow, reattaches it.
- mouseReleaseEvent(event)[source]
Stops the drag. This only happens when the detached tab is not reattached to another window.
- reattach(index, tab, text)[source]
Reattaches a tab that has been dragged over this window’s tab bar.
- Parameters
index (int) – Index in this widget’s tab bar where the detached tab has been dragged.
tab (QWidget) – The widget in the tab being dragged.
text (str) – The title of the tab.
- handle_close_request_from_tab()[source]
Catches close event triggered by a QAction in tab’s QToolBar. Calls QTabWidgets close tabs method to ensure that the last closed tab closes the editor window.
- set_current_tab(tab)[source]
Sets the tab that is shown on the window.
- Parameters
tab (QWidget) – tab’s contents widget
Creates a context menu for given tab.
- Parameters
index (int) – tab index
- Returns
context menu or None if tab was not found
- Return type
QMenu
- class spinetoolbox.widgets.multi_tab_window.TabBarPlus(parent)[source]
Bases:
PySide6.QtWidgets.QTabBar
Tab bar that has a plus button floating to the right of the tabs.
- Parameters
parent (MultiSpineDBEditor) –
- resizeEvent(event)[source]
Sets the dimension of the plus button. Also, makes the tab bar as wide as the parent.
- mousePressEvent(event)[source]
Registers the position of the press, in case we need to detach the tab.
- mouseMoveEvent(event)[source]
Detaches a tab either if the user moves beyond the limits of the tab bar, or if it’s the only one.
- _send_release_event(pos)[source]
Sends a mouse release event at given position in local coordinates. Called just before detaching a tab.
- Parameters
pos (QPoint) –
- start_dragging(index)[source]
Stars dragging the given index. This happens when a detached tab is reattached to this bar.
- Parameters
index (int) –
spinetoolbox.widgets.notification
Contains a notification widget.
Custom pop-up notification widget with fade-in and fade-out effect. |
|
A notification with a button. |
|
A notification that may have a link. |
|
|
- class spinetoolbox.widgets.notification.Notification(parent, txt, anim_duration=_FADE_IN_OUT_DURATION, life_span=None, word_wrap=True, corner=Qt.TopRightCorner)[source]
Bases:
PySide6.QtWidgets.QFrame
Custom pop-up notification widget with fade-in and fade-out effect.
- Parameters
parent (QWidget) – Parent widget
txt (str) – Text to display in notification
anim_duration (int) – Duration of the animation in msecs
life_span (int) – How long does the notification stays in place in msecs
word_wrap (bool) –
corner (Qt.Corner) –
- class spinetoolbox.widgets.notification.ButtonNotification(*args, button_text='', button_slot=None, **kwargs)[source]
Bases:
Notification
A notification with a button.
- Parameters
parent (QWidget) – Parent widget
txt (str) – Text to display in notification
anim_duration (int) – Duration of the animation in msecs
life_span (int) – How long does the notification stays in place in msecs
word_wrap (bool) –
corner (Qt.Corner) –
- class spinetoolbox.widgets.notification.LinkNotification(*args, open_link=None, **kwargs)[source]
Bases:
Notification
A notification that may have a link.
- Parameters
parent (QWidget) – Parent widget
txt (str) – Text to display in notification
anim_duration (int) – Duration of the animation in msecs
life_span (int) – How long does the notification stays in place in msecs
word_wrap (bool) –
corner (Qt.Corner) –
spinetoolbox.widgets.open_project_dialog
Contains a class for a widget that represents a ‘Open Project Directory’ dialog.
A dialog that lets user select a project to open either by choosing |
|
Custom file system model. |
|
- class spinetoolbox.widgets.open_project_dialog.OpenProjectDialog(toolbox)[source]
Bases:
PySide6.QtWidgets.QDialog
A dialog that lets user select a project to open either by choosing an old .proj file or by choosing a project directory.
- Parameters
toolbox (ToolboxUI) – QMainWindow instance
- expand_and_resize(p)[source]
Expands, resizes, and scrolls the tree view to the current directory when the file model has finished loading the path. Slot for the file model’s directoryLoaded signal. The directoryLoaded signal is emitted only if the directory has not been cached already. Note, that this is only used when the open project dialog is opened
- Parameters
p (str) – Directory that has been loaded
- validator_state_changed()[source]
Changes the combobox border color according to the current state of the validator.
- current_index_changed(i)[source]
Combobox selection changed. This slot is processed when a new item is selected from the drop-down list. This is not processed when new item txt is QValidotor.Intermediate.
- Parameters
i (int) – Selected row in combobox
- current_changed(current, previous)[source]
Processed when the current item in file system tree view has been changed with keyboard or mouse. Updates the text in combobox.
- Parameters
current (QModelIndex) – Currently selected index
previous (QModelIndex) – Previously selected index
- set_selected_path(index)[source]
Sets the text in the combobox as the selected path in the file system tree view.
- Parameters
index (QModelIndex) – The index which was mouse clicked.
- combobox_text_edited(text)[source]
Updates selected path when combobox text is edited. Note: pressing enter in combobox does not trigger this.
- go_root(checked=False)[source]
Slot for the ‘Root’ button. Scrolls the treeview to show and select the user’s root directory.
Note: We need to expand and scroll the tree view here after setCurrentIndex just in case the directory has been loaded already.
- go_home(checked=False)[source]
Slot for the ‘Home’ button. Scrolls the treeview to show and select the user’s home directory.
- go_documents(checked=False)[source]
Slot for the ‘Documents’ button. Scrolls the treeview to show and select the user’s documents directory.
- go_desktop(checked=False)[source]
Slot for the ‘Desktop’ button. Scrolls the treeview to show and select the user’s desktop directory.
- open_project(index)[source]
Opens project if index contains a valid Spine Toolbox project. Slot for the mouse doubleClicked signal. Prevents showing the ‘Not a valid spine toolbox project’ notification if user just wants to collapse a directory.
- Parameters
index (QModelIndex) – File model index which was double clicked
- done(r)[source]
Checks that selected path exists and is a valid Spine Toolbox directory when ok button is clicked or when enter is pressed without the combobox being in focus.
- Parameters
r (int) –
- static update_recents(entry, qsettings)[source]
Adds a new entry to QSettings variable that remembers the five most recent project storages.
- Parameters
entry (str) – Abs. path to a directory that most likely contains other Spine Toolbox Projects as well. First entry is also used as the initial path for File->New Project dialog.
qsettings (QSettings) – Toolbox qsettings object
- static remove_directory_from_recents(p, qsettings)[source]
Removes directory from the recent project storages.
- Parameters
p (str) – Full path to a project directory
qsettings (QSettings) – Toolbox qsettings object
Shows the context menu for the QCombobox with a ‘Clear history’ entry.
- Parameters
pos (QPoint) – Mouse position
- class spinetoolbox.widgets.open_project_dialog.CustomQFileSystemModel[source]
Bases:
PySide6.QtWidgets.QFileSystemModel
Custom file system model.
- class spinetoolbox.widgets.open_project_dialog.DirValidator(parent=None)[source]
Bases:
PySide6.QtGui.QValidator
- validate(txt, pos)[source]
Returns Invalid if input is invalid according to this validator’s rules, Intermediate if it is likely that a little more editing will make the input acceptable and Acceptable if the input is valid.
- Parameters
txt (str) – Text to validate
pos (int) – Cursor position
- Returns
Invalid, Intermediate, or Acceptable
- Return type
QValidator.State
spinetoolbox.widgets.options_dialog
Provides OptionsDialog.
A dialog with options. |
- class spinetoolbox.widgets.options_dialog.OptionsDialog(parent, title, text, option_to_answer, notes=None, preferred=None)[source]
Bases:
PySide6.QtWidgets.QDialog
A dialog with options.
- Parameters
parent (QWidget) – the parent widget
title (srt) – title of the window
text (str) – text to show to the user
option_to_answer (dict) – mapping option string to corresponding answer to return
preferred (int,optional) – preselected option if any
spinetoolbox.widgets.parameter_value_editor
An editor dialog for editing database (relationship) parameter values.
Dialog for editing parameter values in Database editor. |
- class spinetoolbox.widgets.parameter_value_editor.ParameterValueEditor(index, parent=None, plain=False)[source]
Bases:
spinetoolbox.widgets.parameter_value_editor_base.ParameterValueEditorBase
Dialog for editing parameter values in Database editor.
- Parameters
index (QModelIndex) – an index to a parameter_value in parent_model
parent (QWidget, optional) – a parent widget
plain (bool) – if True, allow only plain value editing, otherwise allow all parameter types
spinetoolbox.widgets.parameter_value_editor_base
A base for editor windows for editing parameter values.
Enum to identify value types that use different editors. |
|
Dialog for editing parameter values. |
- class spinetoolbox.widgets.parameter_value_editor_base.ValueType[source]
Bases:
enum.Enum
Enum to identify value types that use different editors.
- class spinetoolbox.widgets.parameter_value_editor_base.ParameterValueEditorBase(index, editor_widgets, parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
Dialog for editing parameter values.
The dialog takes an index and shows a specialized editor corresponding to the value type in a stack widget. The user can change the value type by changing the specialized editor using a combo box. When the dialog is closed the value from the currently shown specialized editor is written back to the given index.
- Parameters
index (QModelIndex) – an index to a parameter_value in parent_model
editor_widgets (dict) – a mapping from
ValueType
toQWidget
parent (QWidget, optional) – a parent widget
- accept()[source]
Saves the parameter_value shown in the currently selected editor widget to the database manager.
- _change_parameter_type(selector_index)[source]
Handles switching between value types.
Does a rude conversion between fixed and variable resolution time series. In other cases, a default ‘empty’ value is used.
- Parameters
selector_index (int) – an index to the selector combo box
- _select_editor(value)[source]
Shows the editor widget corresponding to the given value type on the editor stack.
- _use_default_editor(message=None)[source]
Opens the default editor widget. Optionally, displays a warning dialog indicating the problem.
- Parameters
message (str, optional) –
spinetoolbox.widgets.persistent_console_widget
Contains a widget acting as a console for Julia & Python REPL’s.
A widget to interact with a persistent process. |
|
|
- class spinetoolbox.widgets.persistent_console_widget._CustomLineEdit(console)[source]
Bases:
PySide6.QtWidgets.QPlainTextEdit
- class spinetoolbox.widgets.persistent_console_widget.PersistentConsoleWidget(toolbox, key, language, owner=None)[source]
Bases:
PySide6.QtWidgets.QPlainTextEdit
A widget to interact with a persistent process.
- Parameters
toolbox (ToolboxUI) –
key (tuple) – persistent process identifier
language (str) – for syntax highlighting and prompting, etc.
owner (ProjectItemBase, optional) – console owner
- _insert_stdin_text(cursor, text)[source]
Inserts highlighted text.
- Parameters
cursor (QTextCursor) –
text (str) –
- _insert_stdout_text(cursor, text)[source]
Inserts ansi highlighted text.
- Parameters
cursor (QTextCursor) –
text (str) –
- _insert_text_before_prompt(text, with_prompt=False)[source]
Inserts given text before the prompt. Used when adding input and output from external execution.
- Parameters
text (str) –
- set_killed(killed)[source]
Emits the
killed
signal.- Parameters
killed (bool) – if True, may the console rest in peace
- _do_set_killed(killed)[source]
Sets the console as killed or alive.
- Parameters
killed (bool) – if True, may the console rest in peace
- add_stdin(data)[source]
Adds new prompt with data. Used when adding stdin from external execution.
- Parameters
data (str) –
- add_stdout(data)[source]
Adds new line to stdout. Used when adding stdout from external execution.
- Parameters
data (str) –
- add_stderr(data)[source]
Adds new line to stderr. Used when adding stderr from external execution.
- Parameters
data (str) –
- key_press_event(ev)[source]
Handles key press event from line edit.
- Returns
True if handled, False if not.
- create_engine_manager()[source]
Returns a new local or remote spine engine manager or an existing remote spine engine manager. Returns None if connecting to Spine Engine Server fails.
- _autocomplete(text)[source]
Autocompletes current text in the prompt (or output options if multiple matches).
- Parameters
text (str) –
- _interrupt_persistent(_=False)[source]
Sends a task to executor which will interrupt the underlying persistent process.
- _kill_persistent(_=False)[source]
Sends a task to executor which will kill the underlying persistent process.
Appends two more actions: Restart, and Interrupt.
- Parameters
menu (QMenu) – where to append
spinetoolbox.widgets.plain_parameter_value_editor
An editor widget for editing plain number database (relationship) parameter values.
A widget to edit float or boolean type parameter values. |
spinetoolbox.widgets.plot_canvas
A Qt widget to use as a matplotlib backend.
Generic enumeration. |
|
A widget for plotting with matplotlib. |
- class spinetoolbox.widgets.plot_canvas.LegendPosition[source]
Bases:
enum.Enum
Generic enumeration.
Derive from this class to define new enumerations.
- class spinetoolbox.widgets.plot_canvas.PlotCanvas(parent=None, legend_axes_position=LegendPosition.BOTTOM)[source]
Bases:
matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg
A widget for plotting with matplotlib.
- Parameters
legend_axes_position (LegendPosition) – legend axes position relative to plot axes
parent (QWidget, optional) – a parent widget
spinetoolbox.widgets.plot_widget
A Qt widget showing a toolbar and a matplotlib plotting canvas.
A widget that contains a toolbar and a plotting canvas. |
|
Custom QTableView class with copy and paste methods. |
|
Fills a given menu with available plot window names. |
- class spinetoolbox.widgets.plot_widget.PlotWidget(parent=None, legend_axes_position=LegendPosition.BOTTOM)[source]
Bases:
PySide6.QtWidgets.QWidget
A widget that contains a toolbar and a plotting canvas.
- canvas
the plotting canvas
- Type
- original_xy_data
unmodified data on which the plots are based
- Type
list of XYData
- Parameters
parent (QWidget, optional) – parent widget
legend_axes_position (LegendPosition) – legend axes position relative to plot axes
- _get_plot_data()[source]
Gathers plot data into a table.
- Returns
data as table
- Return type
list of list
- add_legend(handles)[source]
Adds a legend to the plot’s legend axes.
- Parameters
handles (list) – legend handles
- class spinetoolbox.widgets.plot_widget._PlotDataView(parent=None)[source]
Bases:
spinetoolbox.widgets.custom_qtableview.CopyPasteTableView
Custom QTableView class with copy and paste methods.
- class spinetoolbox.widgets.plot_widget._PlotDataWidget(rows, parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
Fills a given menu with available plot window names.
- Parameters
menu (QMenu) – menu to modify
spinetoolbox.widgets.plugin_manager_widgets
Contains PluginManager dialogs and widgets.
Initialize class |
|
Initialize class |
- class spinetoolbox.widgets.plugin_manager_widgets._InstallPluginModel[source]
Bases:
PySide6.QtGui.QStandardItemModel
- class spinetoolbox.widgets.plugin_manager_widgets._ManagePluginsModel[source]
Bases:
_InstallPluginModel
- class spinetoolbox.widgets.plugin_manager_widgets.InstallPluginDialog(parent)[source]
Bases:
PySide6.QtWidgets.QDialog
Initialize class
spinetoolbox.widgets.project_item_drag
Classes for custom QListView.
Custom class with dragging support. |
|
Custom class with dragging support. |
|
Custom class with dragging support. |
|
Custom class with dragging support. |
|
Custom class with dragging support. |
|
- class spinetoolbox.widgets.project_item_drag.ProjectItemDragMixin(*args, **kwargs)[source]
Custom class with dragging support.
- class spinetoolbox.widgets.project_item_drag.NiceButton(*args, **kwargs)[source]
Bases:
PySide6.QtWidgets.QToolButton
- class spinetoolbox.widgets.project_item_drag.ProjectItemButtonBase(toolbox, item_type, icon, parent=None)[source]
Bases:
ProjectItemDragMixin
,NiceButton
Custom class with dragging support.
- class spinetoolbox.widgets.project_item_drag.ProjectItemButton(toolbox, item_type, icon, parent=None)[source]
Bases:
ProjectItemButtonBase
Custom class with dragging support.
- class spinetoolbox.widgets.project_item_drag.ProjectItemSpecButton(toolbox, item_type, icon, spec_name='', parent=None)[source]
Bases:
ProjectItemButtonBase
Custom class with dragging support.
- class spinetoolbox.widgets.project_item_drag.ShadeProjectItemSpecButton(toolbox, item_type, icon, spec_name='', parent=None)[source]
Bases:
ShadeMixin
,ProjectItemSpecButton
Custom class with dragging support.
- class spinetoolbox.widgets.project_item_drag.ShadeButton(*args, **kwargs)[source]
Bases:
ShadeMixin
,NiceButton
spinetoolbox.widgets.properties_widget
Contains PropertiesWidgetBase.
Properties widget base class. |
- class spinetoolbox.widgets.properties_widget.PropertiesWidgetBase(toolbox, base_color=None)[source]
Bases:
PySide6.QtWidgets.QWidget
Properties widget base class.
- set_item(project_item)[source]
Sets the active project item.
- Parameters
project_item (ProjectItem) – active project item
spinetoolbox.widgets.report_plotting_failure
Functions to report failures in plotting to the user.
|
Reports a PlottingError exception to the user. |
- spinetoolbox.widgets.report_plotting_failure.report_plotting_failure(error, parent_widget)[source]
Reports a PlottingError exception to the user.
- Parameters
error (PlottingError) – exception to report
parent_widget (QWidget) – parent widget
spinetoolbox.widgets.select_database_items
A widget and utilities to select database items.
Widget that allows selecting database items. |
|
Adds check boxes to grid layout. |
|
Sets the checked state of multiple check boxes. |
- spinetoolbox.widgets.select_database_items.add_check_boxes(check_boxes, checked_states, select_all_button, deselect_all_button, state_changed_slot, layout)[source]
Adds check boxes to grid layout.
- Parameters
check_boxes (dict) – mapping from label to QCheckBox
checked_states (dict) – mapping from label to checked state boolean
select_all_button (QPushButton) – the Select all button
deselect_all_button (QPushButton) – the Deselect all button
state_changed_slot (Callable) – slot to call when any checked state changes
layout (QGridLayout) – target layout
- spinetoolbox.widgets.select_database_items.batch_set_check_state(boxes, checked)[source]
Sets the checked state of multiple check boxes.
- Parameters
boxes (Iterable of QCheckBox) – check boxes
checked (bool) – checked state
- class spinetoolbox.widgets.select_database_items.SelectDatabaseItems(checked_states=None, parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
Widget that allows selecting database items.
- Parameters
checked_states (dict, optional) – mapping from item name to check state boolean
parent (QWidget) – parent widget
- _DATA_ITEMS = ('entity', 'entity_group', 'parameter_value', 'entity_metadata', 'parameter_value_metadata')[source]
- checked_states()[source]
Collects the checked states of database items.
- Returns
mapping from item name to checked state boolean
- Return type
dict
spinetoolbox.widgets.set_description_dialog
A widget for editing project description.
Dialog for setting a description for a project. |
- class spinetoolbox.widgets.set_description_dialog.SetDescriptionDialog(toolbox, project)[source]
Bases:
PySide6.QtWidgets.QDialog
Dialog for setting a description for a project.
- Parameters
toolbox (ToolboxUI) – QMainWindow instance
project (SpineToolboxProject) –
spinetoolbox.widgets.settings_widget
Widget for controlling user settings.
|
|
A widget to change user's preferred settings, but only for the Spine db editor. |
|
A widget to change user's preferred settings. |
|
Returns the kernel name corresponding to given executable or an empty string if not found. |
Checks if given Julia kernel's project matches the given Julia project. |
|
|
- class spinetoolbox.widgets.settings_widget.SettingsWidgetBase(qsettings)[source]
Bases:
PySide6.QtWidgets.QWidget
- Parameters
qsettings (QSettings) – Toolbox settings
- keyPressEvent(e)[source]
Close settings form when escape key is pressed.
- Parameters
e (QKeyEvent) – Received key press event.
- mousePressEvent(e)[source]
Save mouse position at the start of dragging.
- Parameters
e (QMouseEvent) – Mouse event
- mouseReleaseEvent(e)[source]
Save mouse position at the end of dragging.
- Parameters
e (QMouseEvent) – Mouse event
- mouseMoveEvent(e)[source]
Moves the window when mouse button is pressed and mouse cursor is moved.
- Parameters
e (QMouseEvent) – Mouse event
- class spinetoolbox.widgets.settings_widget.SpineDBEditorSettingsMixin[source]
- class spinetoolbox.widgets.settings_widget.SpineDBEditorSettingsWidget(multi_db_editor)[source]
Bases:
SpineDBEditorSettingsMixin
,SettingsWidgetBase
A widget to change user’s preferred settings, but only for the Spine db editor.
Initialize class.
- class spinetoolbox.widgets.settings_widget.SettingsWidget(toolbox)[source]
Bases:
SpineDBEditorSettingsMixin
,SettingsWidgetBase
A widget to change user’s preferred settings.
- Parameters
toolbox (ToolboxUI) – Parent widget.
Returns a context-menu for Python kernel comboBox.
Returns a context-menu for Julia kernel comboBox.
- eventFilter(o, event)[source]
Event filter that catches mouse right button release events. This event typically closes the context-menu, but we want to prevent this and show a context-menu instead.
- Parameters
o (QObject) – Watcher
event (QEvent) – Event
- Returns
True when event is caught, False otherwise
- Return type
bool
- _update_python_widgets_enabled(state)[source]
Enables or disables some widgets based on given boolean state.
- _update_julia_widgets_enabled(state)[source]
Enables or disables some widgets based on given boolean state.
- _update_remote_execution_page_widget_status(state)[source]
Enables or disables widgets on Remote Execution page, based on the state of remote execution enabled check box.
- browse_work_directory_button_clicked(_=False)[source]
Calls static method that shows a directory browser for selecting a Work directory.
- browse_gams_button_clicked(_=False)[source]
Calls static method that shows a file browser for selecting a Gams executable.
- browse_julia_button_clicked(_=False)[source]
Calls static method that shows a file browser for selecting a Julia path.
- browse_julia_project_button_clicked(_=False)[source]
Calls static method that shows a folder browser for selecting a Julia project.
- browse_python_button_clicked(_=False)[source]
Calls static method that shows a file browser for selecting a Python interpreter.
- browse_conda_button_clicked(_=False)[source]
Calls static method that shows a file browser for selecting a Conda executable.
- browse_certificate_directory_clicked(_=False)[source]
Calls static method that shows a file browser for selecting the security folder for Engine Server.
- make_python_kernel(_=False)[source]
Makes a Python kernel for Jupyter Console based on selected Python interpreter. If a kernel using this Python interpreter already exists, sets that kernel selected in the comboBox.
- make_julia_kernel(_=False)[source]
Makes a Julia kernel for Jupyter Console based on selected Julia executable and Julia project. If a kernel using the selected Julia executable and project already exists, sets that kernel selected in the comboBox.
Shows the context-menu on Python kernels combobox.
Shows the context-menu on Julia kernels combobox.
Shows the context-menu on Python kernels combobox popup list.
Shows the context-menu on Julia kernels combobox popup list.
- update_bg_color()[source]
Set tool button icon as the selected color and update Design View scene background color.
- read_settings()[source]
Read saved settings from app QSettings instance and update UI to display them.
- save_settings()[source]
Get selections and save them to persistent memory. Note: On Linux, True and False are saved as boolean values into QSettings. On Windows, booleans and integers are saved as strings. To make it consistent, we should use strings.
- _save_engine_settings()[source]
Stores Engine settings to application settings.
- Returns
True if settings were stored successfully, False otherwise
- Return type
bool
- set_work_directory(new_work_dir)[source]
Sets new work directory.
- Parameters
new_work_dir (str) – Possibly a new work directory
- update_ui()[source]
Updates UI to reflect current settings. Called when the user choses to cancel their changes. Undoes all temporary UI changes that resulted from the user playing with certain settings.
- _edit_remote_host(new_text)[source]
Prepends host line edit with the protocol for user convenience.
- Parameters
new_text (str) – Text in the line edit after user has entered a character
- add_julia_kernel(kernel_name, resource_dir, conda, icon, deats)[source]
Adds a kernel entry as an item to Julia kernels comboBox.
- restore_saved_julia_kernel()[source]
Sets saved or given julia kernel selected after kernels have been loaded.
- start_fetching_python_kernels(conda_path_updated=False)[source]
Starts a thread for fetching Python kernels.
- add_python_kernel(kernel_name, resource_dir, conda, icon, deats)[source]
Adds a kernel entry as an item to Python kernels comboBox.
- restore_saved_python_kernel()[source]
Sets saved or given python kernel selected after kernels have been loaded.
- spinetoolbox.widgets.settings_widget._get_kernel_name_by_exe(p, kernel_model)[source]
Returns the kernel name corresponding to given executable or an empty string if not found.
- Parameters
p (str) – Absolute path to an executable
kernel_model (QStandardItemModel) – Model with items containing kernel spec details
- Returns
Kernel name or an empty string
- Return type
str
- spinetoolbox.widgets.settings_widget._selected_project_matches_kernel_project(julia_kernel_name, julia_project, kernel_model)[source]
Checks if given Julia kernel’s project matches the given Julia project.
- Parameters
julia_kernel_name (str) – Kernel name
julia_project (str) – Path or some other string (e.g. ‘@.’) to denote the Julia project
kernel_model (QStandardItemModel) – Model containing kernels
- Returns
True if projects match, False otherwise
- Return type
bool
spinetoolbox.widgets.statusbars
Functions to make and handle QStatusBars.
spinetoolbox.widgets.time_pattern_editor
An editor widget for editing a time pattern type (relationship) parameter values.
A widget for editing time patterns. |
spinetoolbox.widgets.time_series_fixed_resolution_editor
Contains logic for the fixed step time series editor widget.
A widget for editing time series data with a fixed time step. |
|
Converts a list of durations into a string of comma-separated durations. |
|
Converts a comma-separated string of durations into a resolution array. |
- spinetoolbox.widgets.time_series_fixed_resolution_editor._resolution_to_text(resolution)[source]
Converts a list of durations into a string of comma-separated durations.
- spinetoolbox.widgets.time_series_fixed_resolution_editor._text_to_resolution(text)[source]
Converts a comma-separated string of durations into a resolution array.
- class spinetoolbox.widgets.time_series_fixed_resolution_editor.TimeSeriesFixedResolutionEditor(parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
A widget for editing time series data with a fixed time step.
- Parameters
parent (QWidget) – a parent widget
Shows the table’s context menu.
- Parameters
position (QPoint) – menu’s position in table view’s coordinates
spinetoolbox.widgets.time_series_variable_resolution_editor
Contains logic for the variable resolution time series editor widget.
A widget for editing variable resolution time series data. |
- class spinetoolbox.widgets.time_series_variable_resolution_editor.TimeSeriesVariableResolutionEditor(parent=None)[source]
Bases:
PySide6.QtWidgets.QWidget
A widget for editing variable resolution time series data.
- Parameters
parent (QWidget) – a parent widget
Shows the table’s context menu.
- Parameters
position (QPoint) – menu’s position on the table
spinetoolbox.widgets.toolbars
Functions to make and handle QToolBars.
Base class for Toolbox toolbars. |
|
A plugin toolbar. |
|
Base class for Toolbox toolbars. |
|
The base items |
|
Base class for Toolbox toolbars. |
- class spinetoolbox.widgets.toolbars._TitleWidget(title, toolbar)[source]
Bases:
PySide6.QtWidgets.QWidget
- class spinetoolbox.widgets.toolbars.ToolBar(name, toolbox)[source]
Bases:
PySide6.QtWidgets.QToolBar
Base class for Toolbox toolbars.
- Parameters
name (str) – toolbar’s name
toolbox (ToolboxUI) – Toolbox main window
- set_color(color)[source]
Sets toolbar’s background color.
- Parameters
color (QColor) – background color
- set_project_actions_enabled(enabled)[source]
Enables or disables project related actions.
- Parameters
enabled (bool) – True to enable actions, False to disable
- _insert_tool_button(before, button)[source]
Inserts button into the toolbar.
- Parameters
before (QWidget) – insert before this widget
button (QToolButton) – button to add
- Returns
QAction
- _add_tool_button(button)[source]
Adds a button to the toolbar.
- Parameters
button (QToolButton) – button to add
- Returns
QAction
- _make_tool_button(icon, text, slot=None, tip=None)[source]
Makes a new tool button and adds it to the toolbar.
- Parameters
icon (QIcon) – button’s icon
text (str) – button’s text
slot (Callable) – slot where to connect button’s clicked signal
tip (str) – button’s tooltip
- Returns
created button
- Return type
QToolButton
- class spinetoolbox.widgets.toolbars.PluginToolBar(name, parent)[source]
Bases:
ToolBar
A plugin toolbar.
- Parameters
parent (ToolboxUI) – QMainWindow instance
- class spinetoolbox.widgets.toolbars.SpecToolBar(parent)[source]
Bases:
ToolBar
Base class for Toolbox toolbars.
- Parameters
name (str) – toolbar’s name
toolbox (ToolboxUI) – Toolbox main window
Submodules
spinetoolbox.__main__
Spine Toolbox application main file.
spinetoolbox._version
Module Contents
spinetoolbox.config
Application constants and style sheets.
Module Contents
- spinetoolbox.config.INVALID_FILENAME_CHARS = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'][source]
- spinetoolbox.config.ONLINE_DOCUMENTATION_URL = 'https://spine-toolbox.readthedocs.io/en/master/'[source]
- spinetoolbox.config.PLUGIN_REGISTRY_URL = 'https://spine-tools.github.io/PluginRegistry/registry.json'[source]
spinetoolbox.execution_managers
Classes to manage tool instance execution in various forms.
Module Contents
Base class for all tool instance execution managers. |
|
Class to manage tool instance execution using a PySide6 QProcess. |
- class spinetoolbox.execution_managers.ExecutionManager(logger)[source]
Bases:
PySide6.QtCore.QObject
Base class for all tool instance execution managers.
Class constructor.
- Parameters
logger (LoggerInterface) – a logger instance
- class spinetoolbox.execution_managers.QProcessExecutionManager(logger, program='', args=None, silent=False, semisilent=False)[source]
Bases:
ExecutionManager
Class to manage tool instance execution using a PySide6 QProcess.
Class constructor.
- Parameters
logger (LoggerInterface) – a logger instance
program (str) – Path to program to run in the subprocess (e.g. julia.exe)
args (list, optional) – List of argument for the program (e.g. path to script file)
silent (bool) – Whether or not to emit logger msg signals
semisilent (bool) – If True, show Process Log messages
- start_execution(workdir=None)[source]
Starts the execution of a command in a QProcess.
- Parameters
workdir (str, optional) – Work directory
- wait_for_process_finished(msecs=30000)[source]
Wait for subprocess to finish.
- Parameters
msecs (int) – Timeout in milliseconds
- Returns
True if process finished successfully, False otherwise
- on_state_changed(new_state)[source]
Runs when QProcess state changes.
- Parameters
new_state (int) – Process state number (
QProcess::ProcessState
)
- on_process_error(process_error)[source]
Runs if there is an error in the running QProcess.
- Parameters
process_error (int) – Process error number (
QProcess::ProcessError
)
- teardown_process()[source]
Tears down the QProcess in case a QProcess.ProcessError occurred. Emits execution_finished signal.
spinetoolbox.fetch_parent
The FetchParent and FlexibleFetchParent classes.
Module Contents
|
|
|
|
|
|
dict() -> new empty dictionary |
|
- class spinetoolbox.fetch_parent.FetchParent(index=None, owner=None, chunk_size=1000)[source]
Bases:
PySide6.QtCore.QObject
- Parameters
index (FetchIndex, optional) – an index to speedup looking up fetched items
owner (object, optional) – somebody who owns this FetchParent. If it’s a QObject instance, then this FetchParent becomes obsolete whenever the owner is destroyed
chunk_size (int, optional) – the number of items this parent should be happy with fetching at a time. If None, then no limit is imposed and the parent should fetch the entire contents of the DB.
- abstract property fetch_item_type[source]
Returns the DB item type to fetch, e.g., “entity_class”.
- Returns
str
- key_for_index(db_map)[source]
Returns the key for this parent in the index.
- Parameters
db_map (DatabaseMapping) –
- Returns
Any
- accepts_item(item, db_map)[source]
Called by the associated SpineDBWorker whenever items are fetched and also added/updated/removed. Returns whether this parent accepts that item as a children.
In case of modifications, the SpineDBWorker will call one or more of
handle_items_added()
,handle_items_updated()
, orhandle_items_removed()
with all the items that pass this test.- Parameters
item (dict) – The item
db_map (DatabaseMapping) –
- Returns
bool
- shows_item(item, db_map)[source]
Called by the associated SpineDBWorker whenever items are fetched and accepted. Returns whether this parent will show this item to the user.
- Parameters
item (dict) – The item
db_map (DatabaseMapping) –
- Returns
bool
- set_obsolete(obsolete)[source]
Sets the obsolete status.
- Parameters
obsolete (bool) – whether parent has become obsolete
- set_fetched(fetched)[source]
Sets the fetched status.
- Parameters
fetched (bool) – whether parent has been fetched completely
- set_busy(busy)[source]
Sets the busy status.
- Parameters
busy (bool) – whether parent is busy fetching
- abstract handle_items_added(db_map_data)[source]
Called by SpineDBWorker when items are added to the DB.
- Parameters
db_map_data (dict) – Mapping DatabaseMapping instances to list of dict-items for which
accepts_item()
returns True.
- class spinetoolbox.fetch_parent.ItemTypeFetchParent(fetch_item_type, index=None, owner=None, chunk_size=1000)[source]
Bases:
FetchParent
- Parameters
index (FetchIndex, optional) – an index to speedup looking up fetched items
owner (object, optional) – somebody who owns this FetchParent. If it’s a QObject instance, then this FetchParent becomes obsolete whenever the owner is destroyed
chunk_size (int, optional) – the number of items this parent should be happy with fetching at a time. If None, then no limit is imposed and the parent should fetch the entire contents of the DB.
- property fetch_item_type[source]
Returns the DB item type to fetch, e.g., “entity_class”.
- Returns
str
- abstract handle_items_added(db_map_data)[source]
Called by SpineDBWorker when items are added to the DB.
- Parameters
db_map_data (dict) – Mapping DatabaseMapping instances to list of dict-items for which
accepts_item()
returns True.
- abstract handle_items_removed(db_map_data)[source]
Called by SpineDBWorker when items are removed from the DB.
- Parameters
db_map_data (dict) – Mapping DatabaseMapping instances to list of dict-items for which
accepts_item()
returns True.
- class spinetoolbox.fetch_parent.FlexibleFetchParent(fetch_item_type, handle_items_added=None, handle_items_removed=None, handle_items_updated=None, accepts_item=None, shows_item=None, key_for_index=None, index=None, owner=None, chunk_size=1000)[source]
Bases:
ItemTypeFetchParent
- Parameters
index (FetchIndex, optional) – an index to speedup looking up fetched items
owner (object, optional) – somebody who owns this FetchParent. If it’s a QObject instance, then this FetchParent becomes obsolete whenever the owner is destroyed
chunk_size (int, optional) – the number of items this parent should be happy with fetching at a time. If None, then no limit is imposed and the parent should fetch the entire contents of the DB.
- key_for_index(db_map)[source]
Returns the key for this parent in the index.
- Parameters
db_map (DatabaseMapping) –
- Returns
Any
- handle_items_added(db_map_data)[source]
Called by SpineDBWorker when items are added to the DB.
- Parameters
db_map_data (dict) – Mapping DatabaseMapping instances to list of dict-items for which
accepts_item()
returns True.
- handle_items_removed(db_map_data)[source]
Called by SpineDBWorker when items are removed from the DB.
- Parameters
db_map_data (dict) – Mapping DatabaseMapping instances to list of dict-items for which
accepts_item()
returns True.
- handle_items_updated(db_map_data)[source]
Called by SpineDBWorker when items are updated in the DB.
- Parameters
db_map_data (dict) – Mapping DatabaseMapping instances to list of dict-items for which
accepts_item()
returns True.
- accepts_item(item, db_map)[source]
Called by the associated SpineDBWorker whenever items are fetched and also added/updated/removed. Returns whether this parent accepts that item as a children.
In case of modifications, the SpineDBWorker will call one or more of
handle_items_added()
,handle_items_updated()
, orhandle_items_removed()
with all the items that pass this test.- Parameters
item (dict) – The item
db_map (DatabaseMapping) –
- Returns
bool
- class spinetoolbox.fetch_parent.FetchIndex[source]
Bases:
dict
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object’s
(key, value) pairs
- dict(iterable) -> new dictionary initialized as if via:
d = {} for k, v in iterable:
d[k] = v
- dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
Initialize self. See help(type(self)) for accurate signature.
spinetoolbox.headless
Contains facilities to open and execute projects without GUI.
Module Contents
A |
|
A simple project that is available for modification script. |
|
A 'task' which opens Toolbox project and operates on it. |
|
Status codes returned from headless execution. |
|
Executes a project using |
|
Opens a project. |
|
Loads project item specification dictionaries. |
Makes given path object OS independent. |
- class spinetoolbox.headless.HeadlessLogger[source]
Bases:
PySide6.QtCore.QObject
A
LoggerInterface
compliant logger that uses Python’s standard logging facilities.- msg_proc[source]
Emits a message originating from a subprocess (usually something printed to stdout).
- msg_proc_error[source]
Emits an error message originating from a subprocess (usually something printed to stderr).
- class spinetoolbox.headless.ModifiableProject(project_dir, items_dict, connection_dicts)[source]
A simple project that is available for modification script.
- Parameters
project_dir (Path) – project directory
items_dict (dict) – project item dictionaries
connection_dicts (list of dict) – connection dictionaries
- find_connection(source_name, destination_name)[source]
Searches for a connection between given items.
- Parameters
source_name (str) – source item’s name
destination_name (str) – destination item’s name
- Returns
connection instance or None if there is no connection
- Return type
Connection
- find_item(name)[source]
Searches for a project item.
- Parameters
name (str) – item’s name
- Returns
item dict or None if no such item exists
- Return type
dict
- class spinetoolbox.headless.ActionsWithProject(args, startup_event_type, parent)[source]
Bases:
PySide6.QtCore.QObject
A ‘task’ which opens Toolbox project and operates on it.
The execution of this task is triggered by sending it a ‘startup’ QEvent using e.g. QCoreApplication.postEvent()
- Parameters
args (argparse.Namespace) – parsed command line arguments
startup_event_type (int) – expected type id for the event that starts this task
parent (QObject) – a parent object
- _start[source]
A private signal to actually start execution. Not to be used directly. Post a startup event instead.
- _check_project_version(project_dict)[source]
Checks project dict version.
- Parameters
project_dict (dict) – project dict
- Returns
status code
- Return type
- _exec_mod_script()[source]
Executes project modification script given in command line arguments.
- Returns
status code
- Return type
- _handle_node_execution_started(data)[source]
Starts collecting messages from given node.
- Parameters
data (dict) – execution start data
- _handle_node_execution_finished(data)[source]
Prints messages for finished nodes.
- Parameters
data (dict) – execution end data
- _handle_event_msg(data)[source]
Stores event messages for later printing.
- Parameters
data (dict) – event message data
- _handle_process_msg(data)[source]
Stores process messages for later printing.
- Parameters
data (dict) – process message data
- _handle_standard_execution_msg(data)[source]
Handles standard execution messages.
Currently, these messages are ignored.
- Parameters
data (dict) – execution message data
- _handle_persistent_execution_msg(data)[source]
Handles persistent execution messages.
- Parameters
data (dict) – execution message data
- _handle_kernel_execution_msg(data)[source]
Handles kernel messages.
Currently, these messages are ignored.
- Parameters
data (dict) – message data
- _read_server_config()[source]
Reads the user provided server settings file that the client requires to establish connection.
- Returns
Dictionary containing the EngineClient settings or None if the given config file does not exist.
- Return type
dict
- _insert_remote_engine_settings(settings)[source]
Inserts remote engine client settings into the settings dictionary that is delivered to the engine.
- Parameters
settings (dict) – Original settings dictionary
- Returns
Settings dictionary containing remote engine client settings
- Return type
dict
- _prepare_remote_execution()[source]
If remote execution is enabled, makes an EngineClient for pinging and uploading the project. If ping is successful, the project is uploaded to the server. If the upload is successful, the server responds with a Job id, which is later used by the client to make a ‘start execution’ request.
- Returns
- Job id if server is ready for remote execution, empty string if something went wrong
or “1” if local execution is enabled.
- Return type
str
- spinetoolbox.headless.headless_main(args)[source]
Executes a project using
QCoreApplication
.- Parameters
args (argparser.Namespace) – parsed command line arguments.
- Returns
exit status code; 0 for success, everything else for failure
- Return type
int
- spinetoolbox.headless.open_project(project_dict, project_dir, logger)[source]
Opens a project.
- Parameters
project_dict (dict) – a serialized project dictionary
project_dir (Path) – path to a directory containing the
.spinetoolbox
dirlogger (LoggerInterface) – a logger
- Returns
item dicts, specification dicts, connection dicts, jump dicts and a DagHandler object
- Return type
tuple
- spinetoolbox.headless._specification_dicts(project_dict, project_dir, logger)[source]
Loads project item specification dictionaries.
- Parameters
project_dict (dict) – a serialized project dictionary
project_dir (str) – path to a directory containing the
.spinetoolbox
dirlogger (LoggerInterface) – a logger
- Returns
a mapping from item type to a list of specification dicts
- Return type
dict
spinetoolbox.helpers
General helper functions and classes.
Module Contents
Graphics scene's link types. |
|
A class to manage icons for icon list widgets. |
|
Specialization of QIconEngine with transparent background. |
|
Specialization of QIconEngine used to draw font-based icons. |
|
QFileIconProvider that provides a Spine icon to the |
|
Event filter class for catching next and previous child key presses. |
|
A 'traffic light' that allows waiting for a signal to be emitted in another thread. |
|
HTML tag filter. |
|
A 'meta' command that does not store undo data but can be used in mergeWith methods of other commands. |
|
Returns user's home dir |
|
Adds color tags and optional time stamp to message. |
|
Decorator to change the mouse cursor to 'busy' while a function is processed. |
|
Create (input/output) directories recursively. |
|
Renames directory. |
|
Opens the given url in the appropriate Web browser for the user's desktop environment, |
Set application icon to Windows taskbar. |
|
Checks if reading .ico files is supported. |
|
Check that PySide6 version is at least 6.4. |
|
|
Returns date and time string for appending into Event Log messages. |
|
Function for copying files. Does not copy folders. |
|
Deletes a directory and all its contents without prompt. |
|
Copies everything from source directory to destination directory recursively. |
|
Change output of itemgetter to always be a tuple even for a single index. |
|
Returns a html unordered list from the given list of strings. |
|
Breaks a list of rows into a list of (row, count) tuples corresponding to chunks of successive rows. |
|
Creates and returns a QIcon corresponding to display_icon. |
|
|
|
Takes icon and color codes, and return equivalent integer. |
|
Takes a display icon id and returns an equivalent tuple of icon and color code. |
Creates a default icon id. |
|
|
Checks if window is on screen and if not, moves and resizes it to make it visible on the primary screen. |
Returns the first element in Iterable s that is not None. |
|
|
Calls QFileDialog.getSaveFileName in the directory that was selected last time the dialog was accepted. |
|
|
|
Tries to convert a string to integer or float. |
|
Returns True if the currently focused widget or one of its ancestors has the given callable. |
|
Calls the given callable on the currently focused widget or one of its ancestors. |
|
Shows file browser and inserts selected directory path to given line_edit. |
|
Opens file browser where user can select a Gams executable (i.e. gams.exe on Windows). |
|
Opens file browser where user can select a Julia executable (i.e. julia.exe on Windows). |
|
Shows directory browser and inserts selected julia project dir to given line_edit. |
|
Opens file browser where user can select a python interpreter (i.e. python.exe on Windows). |
|
Opens file browser where user can select a conda executable. |
|
Shows file browser and inserts selected certificate directory to given line edit. |
|
Returns the text in the given line edit. If no text, returns the |
|
Opens the native open file dialog on Windows. |
Checks that given path points to an existing file and the file name starts with 'conda'. |
|
|
Checks that given path is not a directory and that it's a file and it exists. |
|
Checks that given path is a directory. Needed in |
|
Converts Toolbox settings to a dictionary acceptable by Engine. |
|
|
|
|
|
|
|
Creates a unique name in the form prefix (xx) where xx is a counter value. |
|
Parses specification file. |
|
Returns an Item specification from a definition file. |
|
Returns item specification from a dictionary. |
|
Loads plugins. |
|
Loads plugin dict from plugin directory. |
|
Loads plugin's specifications. |
|
Loads specifications' project-specific data. |
|
Concatenates given information into parameter value identifier string. |
|
Disconnects signal for the duration of a 'with' block. |
|
Gives a context manager that waits for the emission of given Qt signal. |
|
Asks for indexed parameter's index name and updates model accordingly. |
|
|
|
Restores UI state from previous session. |
|
Saves UI state for next session. |
|
Finds insertion points for chunks of data using binary search. |
|
Loads project dictionary from project directory. |
|
Loads local project data. |
|
Merges two dictionaries that may contain nested dictionaries recursively. |
|
|
|
|
|
Identifies a database metadata record. |
|
Checks if two paths are equal. |
|
Returns the connection_file path, if it exists on this computer. If the path |
|
|
|
Turns plain strings into rich text. |
|
Turns a sequence of strings into rich text list. |
|
Turns plain strings into rich text and empty strings/Nones to None. |
Display string to separate items such as entity names. |
- spinetoolbox.helpers.format_log_message(msg_type, message, show_datetime=True)[source]
Adds color tags and optional time stamp to message.
- Parameters
msg_type (str) – message’s type; accepts only ‘msg’, ‘msg_success’, ‘msg_warning’, or ‘msg_error’
message (str) – message to format
show_datetime (bool) – True to add time stamp, False to omit it
- Returns
formatted message
- Return type
str
- spinetoolbox.helpers.busy_effect(func)[source]
Decorator to change the mouse cursor to ‘busy’ while a function is processed.
- Parameters
func (Callable) – Decorated function.
- spinetoolbox.helpers.create_dir(base_path, folder='', verbosity=False)[source]
Create (input/output) directories recursively.
- Parameters
base_path (str) – Absolute path to wanted dir
folder (str) – (Optional) Folder name. Usually short name of item.
verbosity (bool) – True prints a message that tells if the directory already existed or if it was created.
- Raises
OSError if operation failed. –
- spinetoolbox.helpers.rename_dir(old_dir, new_dir, toolbox, box_title)[source]
Renames directory.
- Parameters
old_dir (str) – Absolute path to directory that will be renamed
new_dir (str) – Absolute path to new directory
toolbox (ToolboxUI) – A toolbox to log messages and ask questions.
box_title (str) – The title of the message boxes, (e.g. “Undoing ‘rename DC1 to DC2’”)
- Returns
True if operation was successful, False otherwise
- Return type
bool
- spinetoolbox.helpers.open_url(url)[source]
Opens the given url in the appropriate Web browser for the user’s desktop environment, and returns true if successful; otherwise returns false.
If the URL is a reference to a local file (i.e., the URL scheme is “file”) then it will be opened with a suitable application instead of a Web browser.
Handle return value on caller side.
- Parameters
url (str) – URL to open
- Returns
True if successful, False otherwise
- Return type
bool
- spinetoolbox.helpers.pyside6_version_check()[source]
Check that PySide6 version is at least 6.4.
qt_version (str) is the Qt version used to compile PySide6. E.g. “6.4.1” qt_version_info (tuple) contains each version component separately e.g. (6, 4, 1)
- spinetoolbox.helpers.get_datetime(show, date=True)[source]
Returns date and time string for appending into Event Log messages.
- Parameters
show (bool) – True returns date and time string. False returns empty string.
date (bool) – Whether or not the date should be included in the result
- Returns
datetime string or empty string if show is False
- Return type
str
- spinetoolbox.helpers.copy_files(src_dir, dst_dir, includes=None, excludes=None)[source]
Function for copying files. Does not copy folders.
- Parameters
src_dir (str) – Source directory
dst_dir (str) – Destination directory
includes (list, optional) – Included files (wildcards accepted)
excludes (list, optional) – Excluded files (wildcards accepted)
- Returns
Number of files copied
- Return type
count (int)
- spinetoolbox.helpers.erase_dir(path, verbosity=False)[source]
Deletes a directory and all its contents without prompt.
- Parameters
path (str) – Path to directory
verbosity (bool) – Print logging messages or not
- Returns
True if operation was successful, False otherwise
- Return type
bool
- spinetoolbox.helpers.recursive_overwrite(logger, src, dst, ignore=None, silent=True)[source]
Copies everything from source directory to destination directory recursively. Overwrites existing files.
- Parameters
logger (LoggerInterface) – Enables e.g. printing to Event Log
src (str) – Source directory
dst (str) – Destination directory
ignore (Callable, optional) – Ignore function
silent (bool) – If False, messages are sent to Event Log, If True, copying is done in silence
- spinetoolbox.helpers.tuple_itemgetter(itemgetter_func, num_indexes)[source]
Change output of itemgetter to always be a tuple even for a single index.
- Parameters
itemgetter_func (Callable) – item getter function
num_indexes (int) – number of indexes
- Returns
getter function that works with a single index
- Return type
Callable
- spinetoolbox.helpers.format_string_list(str_list)[source]
Returns a html unordered list from the given list of strings. Intended to print error logs as returned by spinedb_api.
- Parameters
str_list (list of str) – list of strings to format
- Returns
formatted list
- Return type
str
- spinetoolbox.helpers.rows_to_row_count_tuples(rows)[source]
Breaks a list of rows into a list of (row, count) tuples corresponding to chunks of successive rows.
- Parameters
rows (Iterable of int) – rows
- Returns
row count tuples
- Return type
list of tuple
- class spinetoolbox.helpers.IconListManager(icon_size)[source]
A class to manage icons for icon list widgets.
- Parameters
icon_size (QSize) – icon’s size
- spinetoolbox.helpers.object_icon(display_icon)[source]
Creates and returns a QIcon corresponding to display_icon.
- Parameters
display_icon (int) – icon id
- Returns
requested icon
- Return type
QIcon
- class spinetoolbox.helpers.TransparentIconEngine[source]
Bases:
PySide6.QtGui.QIconEngine
Specialization of QIconEngine with transparent background.
- class spinetoolbox.helpers.CharIconEngine(char, color=None)[source]
Bases:
TransparentIconEngine
Specialization of QIconEngine used to draw font-based icons.
- Parameters
char (str) – character to use as the icon
color (QColor, optional) –
- class spinetoolbox.helpers.ColoredIcon(icon_file_name, icon_color, icon_size, colored=None)[source]
Bases:
PySide6.QtGui.QIcon
- class spinetoolbox.helpers.ColoredIconEngine(icon_file_name, icon_color, icon_size, colored=None)[source]
Bases:
PySide6.QtGui.QIconEngine
- spinetoolbox.helpers.make_icon_id(icon_code, color_code)[source]
Takes icon and color codes, and return equivalent integer.
- Parameters
icon_code (int) – icon’s code
color_code (int) – color code
- Returns
icon id
- Return type
int
- spinetoolbox.helpers.interpret_icon_id(display_icon)[source]
Takes a display icon id and returns an equivalent tuple of icon and color code.
- Parameters
display_icon (int, optional) – icon id
- Returns
icon’s code, color code
- Return type
tuple
- spinetoolbox.helpers.default_icon_id()[source]
Creates a default icon id.
- Returns
default icon’s id
- Return type
int
- class spinetoolbox.helpers.ProjectDirectoryIconProvider[source]
Bases:
PySide6.QtWidgets.QFileIconProvider
QFileIconProvider that provides a Spine icon to the Open Project Dialog when a Spine Toolbox project directory is encountered.
- spinetoolbox.helpers.ensure_window_is_on_screen(window, size)[source]
Checks if window is on screen and if not, moves and resizes it to make it visible on the primary screen.
- Parameters
window (QWidget) – a window to check
size (QSize) – desired window size if the window is moved
- spinetoolbox.helpers.first_non_null(s)[source]
Returns the first element in Iterable s that is not None.
- spinetoolbox.helpers.get_save_file_name_in_last_dir(qsettings, key, parent, caption, given_dir, filter_='')[source]
Calls QFileDialog.getSaveFileName in the directory that was selected last time the dialog was accepted.
- Parameters
qsettings (QSettings) – A QSettings object where the last directory is stored
key (string) – The name of the entry in the above QSettings
parent – Args passed to QFileDialog.getSaveFileName
caption – Args passed to QFileDialog.getSaveFileName
given_dir – Args passed to QFileDialog.getSaveFileName
filter – Args passed to QFileDialog.getSaveFileName
- Returns
filename str: selected filter
- Return type
str
- spinetoolbox.helpers.get_open_file_name_in_last_dir(qsettings, key, parent, caption, given_dir, filter_='')[source]
- spinetoolbox.helpers.try_number_from_string(text)[source]
Tries to convert a string to integer or float.
- Parameters
text (str) – string to convert
- Returns
converted value or text if conversion failed
- Return type
int or float or str
- spinetoolbox.helpers.focused_widget_has_callable(parent, callable_name)[source]
Returns True if the currently focused widget or one of its ancestors has the given callable.
- spinetoolbox.helpers.call_on_focused_widget(parent, callable_name)[source]
Calls the given callable on the currently focused widget or one of its ancestors.
- class spinetoolbox.helpers.ChildCyclingKeyPressFilter[source]
Bases:
PySide6.QtCore.QObject
Event filter class for catching next and previous child key presses. Used in filtering the Ctrl+Tab and Ctrl+Shift+Tab key presses in the Item Properties tab widget.
- spinetoolbox.helpers.select_work_directory(parent, line_edit)[source]
Shows file browser and inserts selected directory path to given line_edit.
- Parameters
parent (QWidget, optional) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_gams_executable(parent, line_edit)[source]
Opens file browser where user can select a Gams executable (i.e. gams.exe on Windows). File browser initial dir priority:
current path in line edit (first text, then placeholder text)
Gams path from registry
home_dir()
- Parameters
parent (QWidget, optional) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_julia_executable(parent, line_edit)[source]
Opens file browser where user can select a Julia executable (i.e. julia.exe on Windows).
- Parameters
parent (QWidget, optional) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_julia_project(parent, line_edit)[source]
Shows directory browser and inserts selected julia project dir to given line_edit.
- Parameters
parent (QWidget, optional) – Parent of QFileDialog
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_python_interpreter(parent, line_edit)[source]
Opens file browser where user can select a python interpreter (i.e. python.exe on Windows).
- Parameters
parent (QWidget) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_conda_executable(parent, line_edit)[source]
Opens file browser where user can select a conda executable.
- Parameters
parent (QWidget) – Parent widget for the file dialog and message boxes
line_edit (QLineEdit) – Line edit where the selected path will be inserted
- spinetoolbox.helpers.select_certificate_directory(parent, line_edit)[source]
Shows file browser and inserts selected certificate directory to given line edit.
- Parameters
parent (QWidget, optional) – Parent of QFileDialog
line_edit (QLineEdit) – Line edit where the selected dir path will be inserted
- spinetoolbox.helpers.get_current_path(le)[source]
Returns the text in the given line edit. If no text, returns the placeholder text if it is a valid path. If it’s not a valid path, Returns None.
- spinetoolbox.helpers.get_path_from_native_open_file_dialog(parent, current_path, title, initial_path=None)[source]
Opens the native open file dialog on Windows.
- Parameters
parent (QWidget, optional) – Parent widget for the file dialog
current_path (str) – If not None, the open file dialog initial dir is set according to the ‘File’ keyword. If None, initial dir set according to the ‘InitialDir’ keyword.
title (str) – Dialog title
initial_path (str) – Initial dir if something else than home_dir()
- Returns
[0] is the selected path, [1] is the calling function, [2] is the error message
- Return type
tuple
- spinetoolbox.helpers.is_valid_conda_executable(p)[source]
Checks that given path points to an existing file and the file name starts with ‘conda’.
- Parameters
p (str) – Absolute path to a file
- spinetoolbox.helpers.file_is_valid(parent, file_path, msgbox_title, extra_check=None)[source]
Checks that given path is not a directory and that it’s a file and it exists. In addition, can be used to check if the file name in given file path starts with the given extra_check string. Needed in SettingsWidget and KernelEditor because the QLineEdits are editable. Returns True when file_path is an empty string so that we can use default values (e.g. from line edit place holder text). Returns also True when file_path is just ‘python’ or ‘julia’ so that user’s can use the python or julia in PATH.
- Parameters
parent (QWidget) – Parent widget for the message boxes
file_path (str) – Path to check
msgbox_title (str) – Title for message boxes
extra_check (str, optional) – String that must match the file name of the given file_path (without extension)
- Returns
True if given path is an empty string or if path is valid, False otherwise
- Return type
bool
- spinetoolbox.helpers.dir_is_valid(parent, dir_path, msgbox_title)[source]
Checks that given path is a directory. Needed in SettingsWdiget and KernelEditor because the QLineEdits are editable. Returns True when dir_path is an empty string so that we can use default values (e.g. from line edit place holder text)
- Parameters
parent (QWidget) – Parent widget for the message box
dir_path (str) – Directory path to check
msgbox_title (str) – Message box title
- Returns
True if given path is an empty string or if path is an existing directory, False otherwise
- Return type
bool
- spinetoolbox.helpers.make_settings_dict_for_engine(app_settings)[source]
Converts Toolbox settings to a dictionary acceptable by Engine.
- Parameters
app_settings (QSettings) – Toolbox settings
- Returns
Engine-compatible settings
- Return type
dict
- spinetoolbox.helpers.unique_name(prefix, existing)[source]
Creates a unique name in the form prefix (xx) where xx is a counter value. When prefix already contains a counter (xx), the value xx is updated.
- Parameters
prefix (str) – name prefix
existing (Iterable of str) – existing names
- Returns
unique name
- Return type
str
- spinetoolbox.helpers.parse_specification_file(spec_path, logger)[source]
Parses specification file.
- Parameters
spec_path (str) – path to specification file
logger (LoggerInterface) – a logger
- Returns
specification dict or None if the operation failed
- Return type
dict
- spinetoolbox.helpers.load_specification_from_file(spec_path, local_data_dict, spec_factories, app_settings, logger)[source]
Returns an Item specification from a definition file.
- Parameters
spec_path (str) – Path of the specification definition file
local_data_dict (dict) – specifications local data dict
spec_factories (dict) – Dictionary mapping specification type to ProjectItemSpecificationFactory
app_settings (QSettings) – Toolbox settings
logger (LoggerInterface) – a logger
- Returns
item specification or None if reading the file failed
- Return type
ProjectItemSpecification
- spinetoolbox.helpers.specification_from_dict(spec_dict, local_data_dict, spec_factories, app_settings, logger)[source]
Returns item specification from a dictionary.
- Parameters
spec_dict (dict) – Dictionary with the specification
local_data_dict (dict) – specifications local data
spec_factories (dict) – Dictionary mapping specification name to ProjectItemSpecificationFactory
app_settings (QSettings) – Toolbox settings
logger (LoggerInterface) – a logger
- Returns
specification or None if factory isn’t found.
- Return type
ProjectItemSpecification or NoneType
- spinetoolbox.helpers.plugins_dirs(app_settings)[source]
Loads plugins.
- Parameters
app_settings (QSettings) – Toolbox settings
- Returns
plugin directories
- Return type
list of str
- spinetoolbox.helpers.load_plugin_dict(plugin_dir, logger)[source]
Loads plugin dict from plugin directory.
- Parameters
plugin_dir (str) – path of plugin dir with “plugin.json” in it
logger (LoggerInterface) – a logger
- Returns
plugin dict or None if the operation failed
- Return type
dict
- spinetoolbox.helpers.load_plugin_specifications(plugin_dict, local_data_dict, spec_factories, app_settings, logger)[source]
Loads plugin’s specifications.
- Parameters
plugin_dict (dict) – plugin dict
local_data_dict (dict) – specifications local data dictionary
spec_factories (dict) – Dictionary mapping specification name to ProjectItemSpecificationFactory
app_settings (QSettings) – Toolbox settings
logger (LoggerInterface) – a logger
- Returns
mapping from plugin name to list of specifications or None if the operation failed
- Return type
dict
- spinetoolbox.helpers.load_specification_local_data(config_dir)[source]
Loads specifications’ project-specific data.
- Parameters
config_dir (str or Path) – project config dir
- Returns
specifications local data
- Return type
dict
- spinetoolbox.helpers.DB_ITEM_SEPARATOR = ' ǀ '[source]
Display string to separate items such as entity names.
- spinetoolbox.helpers.parameter_identifier(database, parameter, names, alternative)[source]
Concatenates given information into parameter value identifier string.
- Parameters
database (str, optional) – database’s code name
parameter (str) – parameter’s name
names (list of str) – name of the entity or class that holds the value
alternative (str or NoneType) – name of the value’s alternative
- spinetoolbox.helpers.disconnect(signal, *slots)[source]
Disconnects signal for the duration of a ‘with’ block.
- Parameters
signal (Signal) – signal to disconnect
*slots – slots to disconnect from
- class spinetoolbox.helpers.SignalWaiter(condition=None, timeout=None)[source]
Bases:
PySide6.QtCore.QObject
A ‘traffic light’ that allows waiting for a signal to be emitted in another thread.
- Parameters
condition (function, optional) – receiving the self.args and returning whether to stop waiting.
timeout (float, optional) – timeout in seconds; wait will raise after timeout
- spinetoolbox.helpers.signal_waiter(signal, condition=None, timeout=None)[source]
Gives a context manager that waits for the emission of given Qt signal.
- Parameters
signal (Any) – signal to wait
condition (Callable, optional) – a callable that takes the signal’s parameters and returns True to stop waiting
timeout (float, optional) – timeout in seconds; if None, wait indefinitely
- Yields
SignalWaiter – waiter instance
- class spinetoolbox.helpers.CustomSyntaxHighlighter(*arg, **kwargs)[source]
Bases:
PySide6.QtGui.QSyntaxHighlighter
- spinetoolbox.helpers.inquire_index_name(model, column, title, parent_widget)[source]
Asks for indexed parameter’s index name and updates model accordingly.
- Parameters
model (IndexedValueTableModel or ArrayModel) – a model with header that contains index names
column (int) – column index
title (str) – input dialog’s title
parent_widget (QWidget) – dialog’s parent widget
- spinetoolbox.helpers.restore_ui(window, app_settings, settings_group)[source]
Restores UI state from previous session.
- Parameters
window (QMainWindow) –
app_settings (QSettings) –
settings_group (str) –
- spinetoolbox.helpers.save_ui(window, app_settings, settings_group)[source]
Saves UI state for next session.
- Parameters
window (QMainWindow) –
app_settings (QSettings) –
settings_group (str) –
- spinetoolbox.helpers.bisect_chunks(current_data, new_data, key=None)[source]
Finds insertion points for chunks of data using binary search.
- Parameters
current_data (list) – sorted list where to insert new data
new_data (list) – data to insert
key (Callable, optional) – sort key
- Returns
sorted chunk of new data, insertion position
- Return type
tuple
- spinetoolbox.helpers.load_project_dict(project_config_dir, logger)[source]
Loads project dictionary from project directory.
- Parameters
project_config_dir (str) – project’s .spinetoolbox directory
logger (LoggerInterface) – a logger
- Returns
project dictionary
- Return type
dict
- spinetoolbox.helpers.load_local_project_data(project_config_dir, logger)[source]
Loads local project data.
- Parameters
project_config_dir (Path or str) – project’s .spinetoolbox directory
logger (LoggerInterface) – a logger
- Returns
project’s local data
- Return type
dict
- spinetoolbox.helpers.merge_dicts(source, target)[source]
Merges two dictionaries that may contain nested dictionaries recursively.
- Parameters
source (dict) – dictionary that will be merged to
target
target (dict) – target dictionary
- spinetoolbox.helpers._is_metadata_item(item)[source]
Identifies a database metadata record.
- Parameters
item (dict) – database item
- Returns
True if item is metadata item, False otherwise
- Return type
bool
- class spinetoolbox.helpers.HTMLTagFilter[source]
Bases:
html.parser.HTMLParser
HTML tag filter.
Initialize and reset this instance.
If convert_charrefs is True (the default), all character references are automatically converted to the corresponding Unicode characters.
- spinetoolbox.helpers.same_path(path1, path2)[source]
Checks if two paths are equal.
This is a lightweight version of os.path.samefile(): it doesn’t check if the paths point to the same file system object but rather takes into account file system case-sensitivity and such.
- Parameters
path1 (str) – a path
path2 (str) – a path
- Returns
True if paths point to the same
- Return type
bool
- spinetoolbox.helpers.solve_connection_file(connection_file, connection_file_dict)[source]
Returns the connection_file path, if it exists on this computer. If the path doesn’t exist, assume that it points to a path on another computer, in which case store the contents of connection_file_dict into a tempfile.
- Parameters
connection_file (str) – Path to a connection file
connection_file_dict (dict) –
- Returns
Path to a connection file on this computer.
- Return type
str
- class spinetoolbox.helpers.SealCommand(command_id=1)[source]
Bases:
PySide6.QtGui.QUndoCommand
A ‘meta’ command that does not store undo data but can be used in mergeWith methods of other commands.
- Parameters
command_id (int) – command id
- spinetoolbox.helpers.plain_to_rich(text)[source]
Turns plain strings into rich text.
- Parameters
text (str) – string to convert
- Returns
rich text string
- Return type
str
spinetoolbox.kernel_fetcher
Contains a class for fetching kernel specs in a thread.
Module Contents
Worker class for retrieving local kernels. |
- class spinetoolbox.kernel_fetcher.KernelFetcher(conda_path, fetch_mode=1)[source]
Bases:
PySide6.QtCore.QThread
Worker class for retrieving local kernels.
- Parameters
conda_path (str) – Path to (mini)conda executable
fetch_mode (int) – 1: Fetch all kernels, 2: Fetch regular and Conda Python kernels, 3: Fetch only regular Python kernels, 4: Fetch only regular Julia kernels, 5: Fetch kernels that are neither Python nor Julia
- run()[source]
Finds kernel specs based on selected fetch mode. Sends found kernels one-by-one via signals.
- static get_icon(p)[source]
Retrieves the kernel’s icon. First tries to find the .svg icon then .png’s.
- Parameters
p (str) – Path to Kernel’s resource directory
- Returns
Kernel’s icon or a null icon if icon was not found.
- Return type
QIcon
- static get_kernel_deats(kernel_path)[source]
Reads kernel.json from given kernel’s resource dir and returns the details in a dictionary.
- Parameters
kernel_path (str) – Full path to kernel resource directory
- Returns
language (str), path to executable (str), display name (str), project (str) (NA for Python kernels)
- Return type
dict
spinetoolbox.link
Classes for drawing graphics items on QGraphicsScene.
Module Contents
Base class for Link and LinkDrawer. |
|
Base class for icons to show over a Link. |
|
An SVG icon to show over a Link. |
|
A font awesome icon to show over a Link. |
|
A font awesome icon to show over a Link. |
|
Base class for Jump and Link. |
|
A graphics item to represent the connection between two project items. |
|
A graphics icon to represent a jump connection between items. |
|
A base class for items intended for drawing links between project items. |
|
An item for drawing connection links between project items. |
|
An item for drawing jump connections between project items. |
|
- class spinetoolbox.link.LinkBase(toolbox, src_connector, dst_connector)[source]
Bases:
PySide6.QtWidgets.QGraphicsPathItem
Base class for Link and LinkDrawer.
Mainly provides the
update_geometry
method for ‘drawing’ the link on the scene.- Parameters
toolbox (ToolboxUI) – main UI class instance
src_connector (ConnectorButton, optional) – Source connector button
dst_connector (ConnectorButton) – Destination connector button
- moveBy(_dx, _dy)[source]
Does nothing. This item is not moved the regular way, but follows the ConnectorButtons it connects.
- _find_new_point(points, target)[source]
Finds a new point that approximates points to target in a smooth trajectory. Returns the new point, or None if no need for approximation.
- Parameters
points (list(QPointF)) –
target (QPointF) –
- Returns
QPointF or None
- class spinetoolbox.link._IconBase(x, y, w, h, parent, tooltip=None, active=True)[source]
Bases:
PySide6.QtWidgets.QGraphicsEllipseItem
Base class for icons to show over a Link.
- class spinetoolbox.link._SvgIcon(parent, extent, path, tooltip=None, active=False)[source]
Bases:
_IconBase
An SVG icon to show over a Link.
- class spinetoolbox.link._TextIcon(parent, extent, char, tooltip=None, active=False)[source]
Bases:
_IconBase
A font awesome icon to show over a Link.
- class spinetoolbox.link._WarningTextIcon(parent, extent, char, tooltip)[source]
Bases:
_TextIcon
A font awesome icon to show over a Link.
- class spinetoolbox.link.JumpOrLink(toolbox, src_connector, dst_connector)[source]
Bases:
LinkBase
Base class for Jump and Link.
- Parameters
toolbox (ToolboxUI) – main UI class instance
src_connector (ConnectorButton, optional) – Source connector button
dst_connector (ConnectorButton) – Destination connector button
- mousePressEvent(e)[source]
Ignores event if there’s a connector button underneath, to allow creation of new links.
- Parameters
e (QGraphicsSceneMouseEvent) – Mouse event
- contextMenuEvent(e)[source]
Selects the link and shows context menu.
- Parameters
e (QGraphicsSceneMouseEvent) – Mouse event
- class spinetoolbox.link.Link(toolbox, src_connector, dst_connector, connection)[source]
Bases:
JumpOrLink
A graphics item to represent the connection between two project items.
- Parameters
toolbox (ToolboxUI) – main UI class instance
src_connector (ConnectorButton) – Source connector button
dst_connector (ConnectorButton) – Destination connector button
connection (LoggingConnection) – connection this link represents
- class spinetoolbox.link.JumpLink(toolbox, src_connector, dst_connector, jump)[source]
Bases:
JumpOrLink
A graphics icon to represent a jump connection between items.
- Parameters
toolbox (ToolboxUI) – main UI class instance
src_connector (ConnectorButton) – Source connector button
dst_connector (ConnectorButton) – Destination connector button
jump (spine_engine.project_item.connection.Jump) – connection this link represents
- class spinetoolbox.link.LinkDrawerBase(toolbox)[source]
Bases:
LinkBase
A base class for items intended for drawing links between project items.
- Parameters
toolbox (ToolboxUI) – main UI class instance
- wake_up(src_connector)[source]
Sets the source connector, shows this item and adds it to the scene. After calling this, the scene is in link drawing mode.
- Parameters
src_connector (ConnectorButton) – source connector
- class spinetoolbox.link.ConnectionLinkDrawer(toolbox)[source]
Bases:
LinkDrawerBase
An item for drawing connection links between project items.
- Parameters
toolbox (ToolboxUI) – main UI class instance
- wake_up(src_connector)[source]
Sets the source connector, shows this item and adds it to the scene. After calling this, the scene is in link drawing mode.
- Parameters
src_connector (ConnectorButton) – source connector
- class spinetoolbox.link.JumpLinkDrawer(toolbox)[source]
Bases:
LinkDrawerBase
An item for drawing jump connections between project items.
- Parameters
toolbox (ToolboxUI) – main UI class instance
spinetoolbox.load_project_items
Functions to load project item modules.
Module Contents
|
Loads project item modules. |
- spinetoolbox.load_project_items.load_project_items(items_package_name)[source]
Loads project item modules.
- Parameters
items_package_name (str) – name of the package that contains the project items
- Returns
- two dictionaries; first maps item type to its category
while second maps item type to item factory
- Return type
tuple of dict
spinetoolbox.log_mixin
Contains LogMixin.
Module Contents
- class spinetoolbox.log_mixin.LogMixin[source]
- add_log_message(filter_id, message)[source]
Adds a message to the log document.
- Parameters
filter_id (str) – filter identifier
message (str) – formatted message
spinetoolbox.logger_interface
A logger interface.
Module Contents
Placeholder for signals that can be emitted to send messages to an output device. |
- class spinetoolbox.logger_interface.LoggerInterface[source]
Bases:
PySide6.QtCore.QObject
Placeholder for signals that can be emitted to send messages to an output device.
The signals should be connected to a concrete logging system.
Currently, this is just a ‘model interface’. ToolboxUI contains the same signals so it can be used as a drop-in replacement for this class.
- msg_proc[source]
Emits a message originating from a subprocess (usually something printed to stdout).
- msg_proc_error[source]
Emits an error message originating from a subprocess (usually something printed to stderr).
spinetoolbox.main
Provides the main() function.
Module Contents
|
Creates main window GUI and starts main event loop. |
Returns a command line argument parser configured for Toolbox use. |
|
Adds a directory to PATH on Windows that is required to make pywin32 work |
- spinetoolbox.main._make_argument_parser()[source]
Returns a command line argument parser configured for Toolbox use.
- Returns
Toolbox’ command line argument parser
- Return type
ArgumentParser
- spinetoolbox.main._add_pywin32_system32_to_path()[source]
Adds a directory to PATH on Windows that is required to make pywin32 work on (Conda) Python 3.8. See https://github.com/spine-tools/Spine-Toolbox/issues/1230.
spinetoolbox.metaobject
MetaObject class.
Module Contents
Class for an object which has a name, type, and some description. |
- class spinetoolbox.metaobject.MetaObject(name, description)[source]
Bases:
PySide6.QtCore.QObject
Class for an object which has a name, type, and some description.
- Parameters
name (str) – Object name
description (str) – Object description
spinetoolbox.plotting
Functions for plotting on PlotWidget.
Module Contents
Generic enumeration. |
|
Two-dimensional data for plotting. |
|
A labeled node in tree structure. |
|
Header section info for Database editor's parameter tables. |
|
Converts indexed values to tree nodes recursively. |
|
|
Constructs plottable data and indexes recursively. |
|
Raises an exception if data has different x axis labels. |
|
Raises an exception if the types of x data don't match. |
|
Removes redundant indexes from given XYData. |
|
Combines data with same data indexes into the same x axis. |
|
Returns True if a single y-axis should be used. |
|
Returns a plot widget with plots of the given data. |
|
Plots all data on single y-axis. |
|
Plots all data as stacked lines. |
|
Plots all data as bars. |
|
Plots all data on two y-axes. |
Converts x-axis values to something matplotlib can handle. |
|
|
Creates plot settings suitable for time series step plots. |
|
Decides plot method and default keyword arguments based on XYData. |
|
Tests if a type looks like time stamp. |
|
Plots bar chart on axes but returns patches instead of bar container. |
|
Gives data with same x small offsets to prevent bar stacking. |
|
Removes plots and legend from plot widget. |
|
Limits the number of x tick labels in case x-axis consists of strings. |
|
Calculates a human-readable row number. |
|
Returns a plot widget with plots of the selected indexes. |
|
Returns a plot widget with plots of the selected indexes. |
|
Returns a plot widget with plots of the selected indexes. |
|
Returns a plot widget with plots of database manager parameter value items. |
|
Checks if pivot source model has x column. |
|
Gets node from the contents of root_node adding a new node if necessary. |
|
Gets parsed value from model. |
|
Gathers index names from pivot table. |
|
Calculates display row for pivot table. |
Converts parameter value to leaf TreeElement. |
|
|
Adds row information to PlottingError if it is raised in the with block. |
|
Adds an array plot to a plot widget. |
|
Adds a time series step plot to a plot widget. |
- class spinetoolbox.plotting.PlotType[source]
Bases:
enum.Enum
Generic enumeration.
Derive from this class to define new enumerations.
- exception spinetoolbox.plotting.PlottingError[source]
Bases:
Exception
An exception signalling failure in plotting.
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.plotting.ParameterTableHeaderSection[source]
Header section info for Database editor’s parameter tables.
- spinetoolbox.plotting.convert_indexed_value_to_tree(value)[source]
Converts indexed values to tree nodes recursively.
- Parameters
value (IndexedValue) – value to convert
- Returns
root node of the converted tree
- Return type
- Raises
ValueError – raised when leaf value couldn’t be converted to float
- spinetoolbox.plotting.turn_node_to_xy_data(root_node, y_label_position, index_names=None, indexes=None)[source]
Constructs plottable data and indexes recursively.
- Parameters
root_node (TreeNode) – root node
y_label_position (int, optional) – position of y label in indexes
index_names (list of IndexName, optional) – list of current index names
indexes (list) – list of current indexes
- Yields
XYData – plot data
- spinetoolbox.plotting.raise_if_not_common_x_labels(data_list)[source]
Raises an exception if data has different x axis labels.
- Parameters
data_list (list of XYData) – data to check
- Raises
PlottingError – raised if x axis labels don’t match.
- spinetoolbox.plotting.raise_if_incompatible_x(data_list)[source]
Raises an exception if the types of x data don’t match.
- Parameters
data_list (list of XYData) – data to check
- Raises
PlottingError – raised if x data types don’t match.
- spinetoolbox.plotting.reduce_indexes(data_list)[source]
Removes redundant indexes from given XYData.
- Parameters
data_list (list of XYData) – data to reduce
- Returns
reduced data list and list of common data indexes
- Return type
tuple
- spinetoolbox.plotting.combine_data_with_same_indexes(data_list)[source]
Combines data with same data indexes into the same x axis.
- Parameters
data_list (list of XYData) – data to combine
- Returns
combined data
- Return type
list of XYData
- spinetoolbox.plotting._always_single_y_axis(plot_type)[source]
Returns True if a single y-axis should be used.
- Parameters
plot_type (PlotType) – plot type
- Returns
True if single y-axis is required, False otherwise
- Return type
bool
- spinetoolbox.plotting.plot_data(data_list, plot_widget=None, plot_type=None)[source]
Returns a plot widget with plots of the given data.
- Parameters
data_list (list of XYData) – data to plot
plot_widget (PlotWidget, optional) – an existing plot widget to draw into or None to create a new widget
plot_type (PlotType, optional) – plot type
- Returns
a PlotWidget object
- spinetoolbox.plotting._plot_single_y_axis(data_list, y_label, axes, plot_type)[source]
Plots all data on single y-axis.
- Parameters
data_list (list of XYData) – data to plot
y_label (str) – y-axis label
axes (Axes) – plot axes
plot_type (PlotType) – plot type
- Returns
legend handles
- Return type
list
- spinetoolbox.plotting._plot_stacked_line(data_list, y_label, axes)[source]
Plots all data as stacked lines.
- Parameters
data_list (list of XYData) – data to plot
y_label (str) – y-axis label
axes (Axes) – plot axes
- Returns
legend handles
- Return type
list
- spinetoolbox.plotting._plot_bar(data_list, y_label, axes)[source]
Plots all data as bars.
- Parameters
data_list (list of XYData) – data to plot
y_label (str) – y-axis label
axes (Axes) – plot axes
- Returns
legend handles
- Return type
list
- spinetoolbox.plotting._plot_double_y_axis(data_list, y_labels, plot_widget, plot_type)[source]
Plots all data on two y-axes.
- Parameters
data_list (list of XYData) – data to plot
y_labels (list of str) – y-axis labels
plot_widget (PlotWidget) – plot widget
plot_type (PlotType) – plot type
- Returns
legend handles
- Return type
list
- spinetoolbox.plotting._make_x_plottable(xs)[source]
Converts x-axis values to something matplotlib can handle.
- Parameters
xs (list) – x values
- Returns
x values
- Return type
list
- spinetoolbox.plotting._make_time_series_settings(plot_settings)[source]
Creates plot settings suitable for time series step plots.
- Parameters
plot_settings (dict) – base plot settings
- Returns
time series step plot settings
- Return type
dict
- spinetoolbox.plotting._make_plot_function(plot_type, x_data_type, axes)[source]
Decides plot method and default keyword arguments based on XYData.
- Parameters
plot_type (PlotType) – plot type
x_data_type (Type) – data type of x-axis
axes (Axes) – plot axes
- Returns
plot method
- Return type
Callable
- spinetoolbox.plotting._is_time_stamp_type(data_type)[source]
Tests if a type looks like time stamp.
- Parameters
data_type (Type) – data type to test
- Returns
True if type is a time stamp type, False otherwise
- Return type
bool
- spinetoolbox.plotting._bar(x, y, axes, **kwargs)[source]
Plots bar chart on axes but returns patches instead of bar container.
- Parameters
x (Any) – x data
y (Any) – y data
axes (Axes) – plot axes
**kwargs – keyword arguments passed to bar()
- Returns
patches
- Return type
list of Patch
- spinetoolbox.plotting._group_bars(data_list)[source]
Gives data with same x small offsets to prevent bar stacking.
- Parameters
data_list (List of XYData) – squeezed data
- Returns
grouped data, bar width and x ticks
- Return type
tuple
- spinetoolbox.plotting._clear_plot(plot_widget)[source]
Removes plots and legend from plot widget.
- Parameters
plot_widget (PlotWidget) – plot widget
- spinetoolbox.plotting._limit_string_x_tick_labels(data, plot_widget)[source]
Limits the number of x tick labels in case x-axis consists of strings.
Matplotlib tries to plot every single x tick label if they are strings. This can become very slow if the labels are numerous.
- Parameters
data (list of XYData) – plot data
plot_widget (PlotWidget) – plot widget
- spinetoolbox.plotting._table_display_row(row)[source]
Calculates a human-readable row number.
- Parameters
row (int) – model row
- Returns
row number
- Return type
int
- spinetoolbox.plotting.plot_parameter_table_selection(model, model_indexes, table_header_sections, value_section_label, plot_widget=None)[source]
Returns a plot widget with plots of the selected indexes.
- Parameters
model (QAbstractTableModel) – a model
model_indexes (Iterable of QModelIndex) – a list of QModelIndex objects for plotting
table_header_sections (list of ParameterTableHeaderSection) – table header labels
value_section_label (str) – value column’s header label
plot_widget (PlotWidget, optional) – an existing plot widget to draw into or None to create a new widget
- Returns
a PlotWidget object
- Return type
- spinetoolbox.plotting.plot_value_editor_table_selection(model, model_indexes, plot_widget=None)[source]
Returns a plot widget with plots of the selected indexes.
- Parameters
model (QAbstractTableModel) – a model
model_indexes (Iterable of QModelIndex) – a list of QModelIndex objects for plotting
plot_widget (PlotWidget, optional) – an existing plot widget to draw into or None to create a new widget
- Returns
a PlotWidget object
- Return type
- spinetoolbox.plotting.plot_pivot_table_selection(model, model_indexes, plot_widget=None)[source]
Returns a plot widget with plots of the selected indexes.
- Parameters
model (QAbstractTableModel) – a model
model_indexes (Iterable of QModelIndex) – a list of QModelIndex objects for plotting
plot_widget (PlotWidget, optional) – an existing plot widget to draw into or None to create a new widget
- Returns
a PlotWidget object
- Return type
- spinetoolbox.plotting.plot_db_mngr_items(items, db_maps, plot_widget=None)[source]
Returns a plot widget with plots of database manager parameter value items.
- Parameters
items (list of dict) – parameter value items
db_maps (list of DatabaseMapping) – database mappings corresponding to items
plot_widget (PlotWidget, optional) – widget to add plots to
- spinetoolbox.plotting._has_x_column(model, source_model)[source]
Checks if pivot source model has x column.
- Parameters
model (PivotTableSortFilterProxy) – proxy pivot model
source_model (PivotTableModelBase) – pivot table model
- Returns
True if x pivot table has column, False otherwise
- Return type
bool
- spinetoolbox.plotting._set_default_node(root_node, key, label)[source]
Gets node from the contents of root_node adding a new node if necessary.
- spinetoolbox.plotting._get_parsed_value(model_index, display_row)[source]
Gets parsed value from model.
- Parameters
model_index (QModelIndex) – model index
display_row (Callable) – callable that returns a display row
- Returns
parsed value
- Return type
Any
- Raises
PlottingError – raised if parsing of value failed
- spinetoolbox.plotting._pivot_index_names(indexes)[source]
Gathers index names from pivot table.
- Parameters
indexes (tuple of str) – “path” of indexes
- Returns
names corresponding to given indexes
- Return type
tuple of str
- spinetoolbox.plotting._pivot_display_row(row, source_model)[source]
Calculates display row for pivot table.
- Parameters
row (int) – row in source table model
source_model (QAbstractItemModel) – pivot model
- Returns
human-readable row number
- Return type
int
- spinetoolbox.plotting._convert_to_leaf(y)[source]
Converts parameter value to leaf TreeElement.
- Parameters
y (Any) – parameter value
- Returns
leaf element
- Return type
float or datetime or TreeNode
- spinetoolbox.plotting.add_row_to_exception(row, display_row)[source]
Adds row information to PlottingError if it is raised in the with block.
- Parameters
row (int) – row
display_row (Callable) – function to convert row to display row
- spinetoolbox.plotting.add_array_plot(plot_widget, value)[source]
Adds an array plot to a plot widget.
- Parameters
plot_widget (PlotWidget) – a plot widget to modify
value (Array) – the array to plot
- spinetoolbox.plotting.add_time_series_plot(plot_widget, value)[source]
Adds a time series step plot to a plot widget.
- Parameters
plot_widget (PlotWidget) – a plot widget to modify
value (TimeSeries) – the time series to plot
spinetoolbox.plugin_manager
Contains PluginManager class.
Module Contents
Class for managing plugins. |
|
|
|
|
- class spinetoolbox.plugin_manager.PluginManager(toolbox)[source]
Class for managing plugins.
- Parameters
toolbox (ToolboxUI) – Toolbox instance.
- load_installed_plugins()[source]
Loads installed plugins and adds their specifications to toolbars.
- load_individual_plugin(plugin_dir, specification_local_data)[source]
Loads plugin from directory.
- Parameters
plugin_dir (str) – path of plugin dir with “plugin.json” in it.
specification_local_data (dict) – specification local data
- _install_plugin(plugin_name)[source]
Installs plugin from the registry and loads it.
- Parameters
plugin_name (str) – plugin name
spinetoolbox.project
Spine Toolbox project class.
Module Contents
Generic enumeration. |
|
Class for Spine Toolbox projects. |
Returns a dict mapping nodes in topological order to a list of successors. |
|
|
Calculates node ranks. |
- class spinetoolbox.project.ItemNameStatus[source]
Bases:
enum.Enum
Generic enumeration.
Derive from this class to define new enumerations.
- class spinetoolbox.project.SpineToolboxProject(toolbox, p_dir, plugin_specs, app_settings, settings, logger)[source]
Bases:
spinetoolbox.metaobject.MetaObject
Class for Spine Toolbox projects.
- Parameters
toolbox (ToolboxUI) – toolbox of this project
p_dir (str) – Project directory
plugin_specs (Iterable of ProjectItemSpecification) – specifications available as plugins
app_settings (QSettings) – Toolbox settings
settings (ProjectSettings) – project settings
logger (LoggerInterface) – a logger instance
- has_items()[source]
Returns True if project has project items.
- Returns
True if project has items, False otherwise
- Return type
bool
- get_item(name)[source]
Returns project item.
- Parameters
name (str) – Item’s name
- Returns
Project item
- Return type
- get_items()[source]
Returns all project items.
- Returns
All project items
- Return type
list of ProjectItem
- get_items_by_type(_type)[source]
Returns all project items with given _type.
- Parameters
_type (str) – Project Item type
- Returns
Project Items with given type or an empty list if none found
- Return type
list of ProjectItem
- _create_project_structure(directory)[source]
Makes the given directory a Spine Toolbox project directory. Creates directories and files that are common to all projects.
- Parameters
directory (str) – Abs. path to a directory that should be made into a project directory
- Returns
True if project structure was created successfully, False otherwise
- Return type
bool
- set_description(description)[source]
Set object description.
- Parameters
description (str) – Object description
- save()[source]
Collects project information and objects into a dictionary and writes it to a JSON file.
- _save_all_specifications(local_path)[source]
Writes all specifications except plugins to disk.
Local specification data is also written to disk, including local data from plugins.
- Parameters
local_path (Path) –
- Returns
specification local data that is supposed to be stored in a project specific place
- Return type
dict
- _pop_local_data_from_items_dict(items_dict)[source]
Pops local data from project items dict.
- Parameters
items_dict (dict) – items dict
- Returns
local project item data
- Return type
dict
- static _dump(target_dict, out_stream)[source]
Dumps given dict into output stream.
- Parameters
target_dict (dict) – dictionary to dump
out_stream (IOBase) – output stream
- load(spec_factories, item_factories)[source]
Loads project from its project directory.
- Parameters
spec_factories (dict) – Dictionary mapping specification name to ProjectItemSpecificationFactory
item_factories (dict) – mapping from item type to ProjectItemFactory
- Returns
True if the operation was successful, False otherwise
- Return type
bool
- static _merge_local_data_to_project_info(local_data_dict, project_info)[source]
Merges local data into project info.
- Parameters
local_data_dict (dict) – local data
project_info (dict) – project dict
- add_specification(specification, save_to_disk=True)[source]
Adds a specification to the project.
- Parameters
specification (ProjectItemSpecification) – specification to add
save_to_disk (bool) – if True, save the specification to disk
- Returns
A unique identifier for the specification or None if the operation was unsuccessful
- Return type
int
- is_specification_name_reserved(name)[source]
Checks if specification exists.
- Parameters
name (str) – specification’s name
- Returns
True if project has given specification, False otherwise
- Return type
bool
- specifications()[source]
Yields project’s specifications.
- Yields
ProjectItemSpecification – specification
- get_specification(name_or_id)[source]
Returns project item specification.
- Parameters
name_or_id (str or int) – specification’s name or id
- Returns
specification or None if specification was not found
- Return type
ProjectItemSpecification
- specification_name_to_id(name)[source]
Returns identifier for named specification.
- Parameters
name (str) – specification’s name
- Returns
specification’s id or None if no such specification exists
- Return type
int
- remove_specification(id_or_name)[source]
Removes a specification from project.
- Parameters
id_or_name (int or str) – specification’s id or name
- replace_specification(name, specification, save_to_disk=True)[source]
Replaces an existing specification.
Refreshes the spec in all items that use it.
- Parameters
name (str) – name of the specification to replace
specification (ProjectItemSpecification) – a specification
save_to_disk (bool) – If True, saves the given specification to disk
- Returns
True if operation was successful, False otherwise
- Return type
bool
- save_specification_file(specification, previous_name=None)[source]
Saves the given project item specification.
Save path is determined by specification directory and specification’s name.
- Parameters
specification (ProjectItemSpecification) – specification to save
previous_name (str, optional) – specification’s earlier name if it has been renamed/replaced
- Returns
True if operation was successful, False otherwise
- Return type
bool
- _update_specification_local_data_store(specification, local_data, previous_name)[source]
Updates the file containing local data of project’s specifications.
- Parameters
specification (ProjectItemSpecification) – specification
local_data (dict) – local data serialized into dict
previous_name (str, optional) – specification’s earlier name if it has been renamed/replaced
- _default_specification_file_path(specification)[source]
Determines a path inside project directory to save a specification.
- Parameters
specification (ProjectItemSpecification) – specification
- Returns
valid path or None if operation failed
- Return type
str
- add_item(item)[source]
Adds a project item to project.
- Parameters
item (ProjectItem) – item to add
- rename_item(previous_name, new_name, rename_data_dir_message)[source]
Renames a project item
- Parameters
previous_name (str) – item’s current name
new_name (str) – item’s new name
rename_data_dir_message (str) – message to show when renaming item’s data directory
- Returns
True if item was renamed successfully, False otherwise
- Return type
bool
- validate_project_item_name(name)[source]
Validates item name.
- Parameters
name (str) – proposed project item’s name
- Returns
validation result
- Return type
- find_connection(source_name, destination_name)[source]
Searches for a connection between given items.
- Parameters
source_name (str) – source item’s name
destination_name (str) – destination item’s name
- Returns
connection instance or None if there is no connection
- Return type
Connection
- connections_for_item(item_name)[source]
Returns connections that have given item as source or destination.
- Parameters
item_name (str) – item’s name
- Returns
connections connected to item
- Return type
list of Connection
- add_connection(*args, silent=False, notify_resource_changes=True)[source]
Adds a connection to the project.
A single argument is expected to be the
Logging connection
instance. Optionally, source name and position, and destination name and position can be provided instead.- Parameters
*args – connection to add
silent (bool) – If False, prints ‘Link establ…’ msg to Event Log
notify_resource_changes (bool) – If True, updates resources of successor and predecessor items
- Returns
True if connection was added successfully, False otherwise
- Return type
bool
- _notify_rsrc_changes(destination, source)[source]
Notifies connection destination and connection source item that resources may have changed.
- Parameters
destination (ProjectItem) – Destination item
source (ProjectItem) – Source item
- remove_connection(connection)[source]
Removes a connection from the project.
- Parameters
connection (LoggingConnection) – connection to remove
- update_connection(connection, source_position, destination_position)[source]
Updates existing connection between items.
Updating does not trigger any updates to the DAG or project items.
- Parameters
connection (LoggingConnection) – connection to update
source_position (str) – link’s position on source item’s icon
destination_position (str) – link’s position on destination item’s icon
- jumps_for_item(item_name)[source]
Returns jumps that have given item as source or destination.
- Parameters
item_name (str) – item’s name
- Returns
jumps connected to item
- Return type
list of Jump
- add_jump(jump, silent=False)[source]
Adds a jump to project.
- Parameters
jump (Jump) – jump to add
silent (bool) – if True, don’t log messages
- find_jump(source_name, destination_name)[source]
Searches for a jump between given items.
- Parameters
source_name (str) – source item’s name
destination_name (str) – destination item’s name
- Returns
connection instance or None if there is no jump
- Return type
Jump
- update_jump(jump, source_position, destination_position)[source]
Updates an existing jump between items.
- Parameters
jump (LoggingJump) – jump to update
source_position (str) – link’s position on source item’s icon
destination_position (str) – link’s position on destination item’s icon
- jump_issues(jump)[source]
Checks if jump is OK.
- Parameters
jump (Jump) – jump to check
- Returns
list of issues, if any
- Return type
list of str
- dag_with_node(node)[source]
Returns the DiGraph that contains the given node (project item) name (str).
- restore_project_items(items_dict, item_factories)[source]
Restores project items from dictionary.
- Parameters
items_dict (dict) – a mapping from item name to item dict
item_factories (dict) – a mapping from item type to ProjectItemFactory
- remove_item_by_name(item_name, delete_data=False)[source]
Removes project item by its name.
- Parameters
item_name (str) – Item’s name
delete_data (bool) – If set to True, deletes the directories and data associated with the item
- execute_dags(dags, execution_permits_list, msg)[source]
Executes given dags.
- Parameters
dags (list of DiGraph) – List of DAGs
execution_permits_list (list of dict) –
msg (str) – Message to log before execution
- create_engine_worker(dag, execution_permits, dag_identifier, settings, job_id)[source]
Creates and returns a SpineEngineWorker to execute given validated dag.
- Parameters
dag (DiGraph) – The dag
execution_permits (dict) – mapping item names to a boolean indicating whether to execute it or skip it
dag_identifier (str) – A string identifying the dag, for logging
settings (dict) – project and app settings to send to the spine engine.
job_id (str) – job id
- Returns
SpineEngineWorker
- execute_selected(names)[source]
Executes DAGs corresponding to given project items.
- Parameters
names (Iterable of str) – Names of selected items
- _split_to_subdags(dag, selected_items)[source]
Checks if given dag contains weakly connected components. If it does, the weakly connected components are split into their own (sub)dags. If not, the dag is returned unaltered.
- Parameters
dag (DiGraph) – Dag that is checked if it needs to be split into subdags
selected_items (list) – Names of selected items
- Returns
List of dags, ready for execution
- Return type
list of DiGraph
- _validate_dags(dags)[source]
Validates dags and logs error messages.
- Parameters
dags (Iterable) – dags to validate
- Returns
validated dag
- Return type
list
- notify_resource_changes_to_predecessors(item)[source]
Updates resources for direct predecessors of given item.
- Parameters
item (ProjectItem) – item whose resources have changed
- notify_resource_changes_to_successors(item)[source]
Updates resources for direct successors and outgoing connections of given item.
- Parameters
item (ProjectItem) – item whose resources have changed
- _notify_resource_changes(trigger_name, target_names, provider_connections, update_resources, trigger_resources)[source]
Updates resources in given direction for immediate neighbours of an item.
- Parameters
trigger_name (str) – item whose resources have changed
target_names (Iterable of str) – items to be notified
provider_connections (Callable) – function that receives a target item name and returns a list of Connections from resource providers
update_resources (Callable) – function that takes an item name, a list of provider names, and a dictionary of resources, and does the updating
trigger_resources (list of ProjectItemResource) – resources from the trigger item
- notify_resource_replacement_to_successors(item, old, new)[source]
Replaces resources for direct successors and outgoing connections of given item.
- Parameters
item (ProjectItem) – item whose resources have changed
old (list of ProjectItemResource) – old resource
new (list of ProjectItemResource) – new resource
- notify_resource_replacement_to_predecessors(item, old, new)[source]
Replaces resources for direct predecessors.
- Parameters
item (ProjectItem) – item whose resources have changed
old (list of ProjectItemResource) – old resources
new (list of ProjectItemResource) – new resources
- _update_item_resources(target_item, direction)[source]
Updates up or downstream resources for a single project item. Called in both directions after removing a Connection.
- Parameters
target_item (ProjectItem) – item whose resource need update
direction (ExecutionDirection) – FORWARD updates resources from upstream, BACKWARD from downstream
- predecessor_names(name)[source]
Collects direct predecessor item names.
- Parameters
name (str) – name of the project item whose predecessors to collect
- Returns
direct predecessor names
- Return type
set of str
- successor_names(name)[source]
Collects direct successor item names.
- Parameters
name (str) – name of the project item whose successors to collect
- Returns
direct successor names
- Return type
set of str
- descendant_names(name)[source]
Yields descendant item names.
- Parameters
name (str) – name of the project item whose descendants to collect
- Yields
str – descendant name
- outgoing_connections(name)[source]
Collects outgoing connections.
- Parameters
name (str) – name of the project item whose connections to collect
- Returns
outgoing connections
- Return type
set of Connection
- _outgoing_jumps(name)[source]
Collects outgoing jumps.
- Parameters
name (str) – name of the project item whose jumps to collect
- Returns
outgoing jumps
- Return type
set of Jump
- _outgoing_connections_and_jumps(name)[source]
Collects outgoing connections and jumps.
- Parameters
name (str) – name of the project item whose connections and jumps to collect
- Returns
outgoing connections and jumps
- Return type
set of Connection/Jump
- incoming_connections(name)[source]
Collects incoming connections.
- Parameters
name (str) – name of the project item whose connections to collect
- Returns
incoming connections
- Return type
set of Connection
- _incoming_jumps(name)[source]
Collects incoming jumps.
- Parameters
name (str) – name of the project item whose jumps to collect
- Returns
incoming jumps
- Return type
set of Jump
- _incoming_connections_and_jumps(name)[source]
Collects incoming connections and jumps.
- Parameters
name (str) – name of the project item whose connections and jumps to collect
- Returns
incoming connections
- Return type
set of Connection/Jump
- prepare_remote_execution()[source]
Pings the server and sends the project as a zip-file to server.
- Returns
- Job Id if server is ready for remote execution, empty string if something went wrong
or LOCAL_EXECUTION_JOB_ID if local execution is enabled.
- Return type
str
spinetoolbox.project_commands
QUndoCommand subclasses for modifying the project.
Module Contents
Command to set the specification for a project item. |
|
Command to move icons in the Design view. |
|
Command to set the project description. |
|
Command to add items. |
|
Command to remove all items from project. |
|
Command to remove items. |
|
Command to rename project items. |
|
Command to add connection between project items. |
|
Command to remove links. |
|
Command to add a jump between project items. |
|
Command to remove jumps. |
|
Command to set jump condition. |
|
Command to update Jump command line args. |
|
Command to toggle filter value. |
|
Command to set connection's default filter online status. |
|
Command to enable and disable connection's filter types. |
|
Command to set connection options. |
|
Command to add item specification to a project. |
|
Command to replace item specification in project. |
|
Command to remove specs from a project. |
|
Command to remove item specs from a project. |
- class spinetoolbox.project_commands.SpineToolboxCommand[source]
Bases:
PySide6.QtGui.QUndoCommand
- class spinetoolbox.project_commands.SetItemSpecificationCommand(item_name, spec, old_spec, project)[source]
Bases:
SpineToolboxCommand
Command to set the specification for a project item.
- Parameters
item_name (str) – item’s name
spec (ProjectItemSpecification) – the new spec
old_spec (ProjectItemSpecification) – the old spec
project (SpineToolboxProject) – project
- class spinetoolbox.project_commands.MoveIconCommand(icon, project)[source]
Bases:
SpineToolboxCommand
Command to move icons in the Design view.
- Parameters
icon (ProjectItemIcon) – the icon
project (SpineToolboxProject) – project
- class spinetoolbox.project_commands.SetProjectDescriptionCommand(project, description)[source]
Bases:
SpineToolboxCommand
Command to set the project description.
- Parameters
project (SpineToolboxProject) – the project
description (str) – The new description
- class spinetoolbox.project_commands.AddProjectItemsCommand(project, items_dict, item_factories)[source]
Bases:
SpineToolboxCommand
Command to add items.
- Parameters
project (SpineToolboxProject) – the project
items_dict (dict) – a mapping from item name to item dict
item_factories (dict) – a mapping from item type to ProjectItemFactory
silent (bool) – If True, suppress messages
- class spinetoolbox.project_commands.RemoveAllProjectItemsCommand(project, item_factories, delete_data=False)[source]
Bases:
SpineToolboxCommand
Command to remove all items from project.
- Parameters
project (SpineToolboxProject) – the project
item_factories (dict) – a mapping from item type to ProjectItemFactory
delete_data (bool) – If True, deletes the directories and data associated with the items
- class spinetoolbox.project_commands.RemoveProjectItemsCommand(project, item_factories, item_names, delete_data=False)[source]
Bases:
SpineToolboxCommand
Command to remove items.
- Parameters
project (SpineToolboxProject) – The project
item_factories (dict) – a mapping from item type to ProjectItemFactory
item_names (list of str) – Item names
delete_data (bool) – If True, deletes the directories and data associated with the item
- class spinetoolbox.project_commands.RenameProjectItemCommand(project, previous_name, new_name)[source]
Bases:
SpineToolboxCommand
Command to rename project items.
- Parameters
project (SpineToolboxProject) – the project
previous_name (str) – item’s previous name
new_name (str) – the new name
- class spinetoolbox.project_commands.AddConnectionCommand(project, source_name, source_position, destination_name, destination_position)[source]
Bases:
SpineToolboxCommand
Command to add connection between project items.
- Parameters
project (SpineToolboxProject) – project
source_name (str) – source item’s name
source_position (str) – link’s position on source item’s icon
destination_name (str) – destination item’s name
destination_position (str) – link’s position on destination item’s icon
- class spinetoolbox.project_commands.RemoveConnectionsCommand(project, connections)[source]
Bases:
SpineToolboxCommand
Command to remove links.
- Parameters
project (SpineToolboxProject) – project
connections (list of LoggingConnection) – the connections
- class spinetoolbox.project_commands.AddJumpCommand(project, source_name, source_position, destination_name, destination_position)[source]
Bases:
SpineToolboxCommand
Command to add a jump between project items.
- Parameters
project (SpineToolboxProject) – project
source_name (str) – source item’s name
source_position (str) – link’s position on source item’s icon
destination_name (str) – destination item’s name
destination_position (str) – link’s position on destination item’s icon
- class spinetoolbox.project_commands.RemoveJumpsCommand(project, jumps)[source]
Bases:
SpineToolboxCommand
Command to remove jumps.
- Parameters
project (SpineToolboxProject) – project
jumps (list of LoggingJump) – the jumps
- class spinetoolbox.project_commands.SetJumpConditionCommand(project, jump, jump_properties, condition)[source]
Bases:
SpineToolboxCommand
Command to set jump condition.
- Parameters
project (SpineToolboxProject) – project
jump (Jump) – target jump
jump_properties (JumpPropertiesWidget) – jump’s properties tab
condition (dict) – jump condition
- class spinetoolbox.project_commands.UpdateJumpCmdLineArgsCommand(project, jump, jump_properties, cmd_line_args)[source]
Bases:
SpineToolboxCommand
Command to update Jump command line args.
- Parameters
project (SpineToolboxProject) – project
jump (Jump) – jump
jump_properties (JumpPropertiesWidget) – the item
cmd_line_args (list) – list of command line args
- class spinetoolbox.project_commands.SetFiltersOnlineCommand(project, connection, resource, filter_type, online)[source]
Bases:
SpineToolboxCommand
Command to toggle filter value.
- Parameters
project (SpineToolboxProject) – project
connection (Connection) – connection
resource (str) – resource label
filter_type (str) – filter type identifier
online (dict) – mapping from scenario/tool id to online flag
- class spinetoolbox.project_commands.SetConnectionDefaultFilterOnlineStatus(project, connection, default_status)[source]
Bases:
SpineToolboxCommand
Command to set connection’s default filter online status.
- Parameters
project (SpineToolboxProject) – project
connection (LoggingConnection) – connection
default_status (bool) – default filter online status
- class spinetoolbox.project_commands.SetConnectionFilterTypeEnabled(project, connection, filter_type, enabled)[source]
Bases:
SpineToolboxCommand
Command to enable and disable connection’s filter types.
- Parameters
project (SpineToolboxProject) – project
connection (LoggingConnection) – connection
filter_type (str) – filter type
enabled (bool) – whether filter type is enabled
- class spinetoolbox.project_commands.SetConnectionOptionsCommand(project, connection, options)[source]
Bases:
SpineToolboxCommand
Command to set connection options.
- Parameters
project (SpineToolboxProject) – project
connection (LoggingConnection) – project
options (dict) – containing options to be set
- class spinetoolbox.project_commands.AddSpecificationCommand(project, specification, save_to_disk)[source]
Bases:
SpineToolboxCommand
Command to add item specification to a project.
- Parameters
project (ToolboxUI) – the toolbox
specification (ProjectItemSpecification) – the spec
save_to_disk (bool) – If True, save the specification to disk
- class spinetoolbox.project_commands.ReplaceSpecificationCommand(project, name, specification)[source]
Bases:
SpineToolboxCommand
Command to replace item specification in project.
- Parameters
project (ToolboxUI) – the toolbox
name (str) – the name of the spec to be replaced
specification (ProjectItemSpecification) – the new spec
- class spinetoolbox.project_commands.RemoveSpecificationCommand(project, name)[source]
Bases:
SpineToolboxCommand
Command to remove specs from a project.
- Parameters
project (SpineToolboxProject) – the project
name (str) – specification’s name
- class spinetoolbox.project_commands.SaveSpecificationAsCommand(project, name, path)[source]
Bases:
SpineToolboxCommand
Command to remove item specs from a project.
- Parameters
project (SpineToolboxProject) – the project
name (str) – specification’s name
path (str) – new specification file location
spinetoolbox.project_item_icon
Classes for drawing graphics items on QGraphicsScene.
Module Contents
Base class for project item icons drawn in Design View. |
|
Connector button graphics item. Used for Link drawing between project items. |
|
An icon to show information about the item's execution. |
|
An icon to notify that a ProjectItem is missing some configuration. |
|
An icon to show the rank of a ProjectItem within its DAG. |
- class spinetoolbox.project_item_icon.ProjectItemIcon(toolbox, icon_file, icon_color)[source]
Bases:
PySide6.QtWidgets.QGraphicsPathItem
Base class for project item icons drawn in Design View.
- Parameters
toolbox (ToolboxUI) – QMainWindow instance
icon_file (str) – Path to icon resource
icon_color (QColor) – Icon’s color
- add_specification_icon(spec_icon_path)[source]
Adds an SVG icon to bottom left corner of the item icon based on Tool Specification type.
- Parameters
spec_icon_path (str) – Path to icon resource file.
- finalize(name, x, y)[source]
Names the icon and moves it by a given amount.
- Parameters
name (str) – icon’s name
x (int) – horizontal offset
y (int) – vertical offset
- name()[source]
Returns name of the item that is represented by this icon.
- Returns
icon’s name
- Return type
str
- update_name_item(new_name)[source]
Sets a new text to name item.
- Parameters
new_name (str) – icon’s name
- conn_button(position='left')[source]
Returns item’s connector button.
- Parameters
position (str) – “left”, “right” or “bottom”
- Returns
connector button
- Return type
QWidget
- outgoing_connection_links()[source]
Collects outgoing connection links.
- Returns
outgoing links
- Return type
list of LinkBase
- incoming_links()[source]
Collects incoming connection links.
- Returns
outgoing links
- Return type
list of LinkBase
- _update_link_drawer_destination(pos=None)[source]
Updates link drawer destination. If pos is None, then the link drawer would have no destination. Otherwise, the destination would be the connector button closest to pos.
- hoverEnterEvent(event)[source]
Sets a drop shadow effect to icon when mouse enters its boundaries.
- Parameters
event (QGraphicsSceneMouseEvent) – Event
- hoverLeaveEvent(event)[source]
Disables the drop shadow when mouse leaves icon boundaries.
- Parameters
event (QGraphicsSceneMouseEvent) – Event
- update_links_geometry()[source]
Updates geometry of connected links to reflect this item’s most recent position.
- mouseReleaseEvent(event)[source]
Clears pre-bump rects, and pushes a move icon command if necessary.
- contextMenuEvent(event)[source]
Show item context menu.
- Parameters
event (QGraphicsSceneMouseEvent) – Mouse event
- itemChange(change, value)[source]
Reacts to item removal and position changes.
In particular, destroys the drop shadow effect when the item is removed from a scene and keeps track of item’s movements on the scene.
- Parameters
change (GraphicsItemChange) – a flag signalling the type of the change
value – a value related to the change
- Returns
Whatever super() does with the value parameter
- set_pos_without_bumping(pos)[source]
Sets position without bumping other items. Needed for undoing move operations.
- Parameters
pos (QPointF) –
- make_room_for_item(other)[source]
Makes room for another item.
- Parameters
item (ProjectItemIcon) –
- class spinetoolbox.project_item_icon.ConnectorButton(toolbox, parent, position='left')[source]
Bases:
PySide6.QtWidgets.QGraphicsPathItem
Connector button graphics item. Used for Link drawing between project items.
- Parameters
toolbox (ToolboxUI) – QMainWindow instance
parent (ProjectItemIcon) – parent graphics item
position (str) – Either “top”, “left”, “bottom”, or “right”
- project_item()[source]
Returns the project item this connector button is attached to.
- Returns
project item
- Return type
- mousePressEvent(event)[source]
Connector button mouse press event.
- Parameters
event (QGraphicsSceneMouseEvent) – Event
- set_friend_connectors_enabled(enabled)[source]
Enables or disables all connectors in the parent.
This is called by LinkDrawer to disable invalid connectors while drawing and reenabling them back when done.
- Parameters
enabled (bool) – True to enable connectors, False to disable
- hoverEnterEvent(event)[source]
Sets a darker shade to connector button when mouse enters its boundaries.
- Parameters
event (QGraphicsSceneMouseEvent) – Event
- class spinetoolbox.project_item_icon.ExecutionIcon(parent)[source]
Bases:
PySide6.QtWidgets.QGraphicsEllipseItem
An icon to show information about the item’s execution.
- Parameters
parent (ProjectItemIcon) – the parent item
- class spinetoolbox.project_item_icon.ExclamationIcon(parent)[source]
Bases:
PySide6.QtWidgets.QGraphicsTextItem
An icon to notify that a ProjectItem is missing some configuration.
- Parameters
parent (ProjectItemIcon) – the parent item
- clear_other_notifications(subtext)[source]
Remove notifications that don’t include the given subtext.
spinetoolbox.project_settings
Contains project-specific settings.
Module Contents
Spine Toolbox project settings. |
- class spinetoolbox.project_settings.ProjectSettings[source]
Spine Toolbox project settings.
- to_dict()[source]
Serializes the settings into a dictionary.
- Returns
serialized settings
- Return type
dict
spinetoolbox.project_upgrader
Contains ProjectUpgrader class used in upgrading and converting projects and project dicts from earlier versions to the latest version.
Module Contents
Class to upgrade/convert projects from earlier versions to the current version. |
|
Replaces '1d array' with 'array' for parameter type in Importer mappings. |
- class spinetoolbox.project_upgrader.ProjectUpgrader(toolbox)[source]
Class to upgrade/convert projects from earlier versions to the current version.
- Parameters
toolbox (ToolboxUI) – App main window instance
- upgrade(project_dict, project_dir)[source]
Upgrades the project described in given project dictionary to the latest version.
- Parameters
project_dict (dict) – Project configuration dictionary
project_dir (str) – Path to current project directory
- Returns
Latest version of the project info dictionary
- Return type
dict
- upgrade_to_latest(v, project_dict, project_dir)[source]
Upgrades the given project dictionary to the latest version.
- Parameters
v (int) – Current version of the project dictionary
project_dict (dict) – Project dictionary (JSON) to be upgraded
project_dir (str) – Path to current project directory
- Returns
Upgraded project dictionary
- Return type
dict
- static upgrade_v1_to_v2(old, factories)[source]
Upgrades version 1 project dictionary to version 2.
- Changes:
objects -> items, tool_specifications -> specifications store project item dicts under [“items”][<project item name>] instead of using their categories as keys specifications must be a dict instead of a list Add specifications[“Tool”] that must be a dict Remove “short name” from all project items
- Parameters
old (dict) – Version 1 project dictionary
factories (dict) – Mapping of item type to item factory
- Returns
Version 2 project dictionary
- Return type
dict
- upgrade_v2_to_v3(old, project_dir, factories)[source]
Upgrades version 2 project dictionary to version 3.
- Changes:
Move “specifications” from “project” -> “Tool” to just “project”
The “mappings” from importer items are used to build Importer specifications
- Parameters
old (dict) – Version 2 project dictionary
project_dir (str) – Path to current project directory
factories (dict) – Mapping of item type to item factory
- Returns
Version 3 project dictionary
- Return type
dict
- static upgrade_v3_to_v4(old)[source]
Upgrades version 3 project dictionary to version 4.
- Changes:
Rename “Exporter” item type to “GdxExporter”
- Parameters
old (dict) – Version 3 project dictionary
- Returns
Version 4 project dictionary
- Return type
dict
- static upgrade_v4_to_v5(old)[source]
Upgrades version 4 project dictionary to version 5.
- Changes:
Get rid of “Combiner” items.
- Parameters
old (dict) – Version 4 project dictionary
- Returns
Version 5 project dictionary
- Return type
dict
- static upgrade_v5_to_v6(old, project_dir)[source]
Upgrades version 5 project dictionary to version 6.
- Changes:
Data store URL labels do not have ‘{‘ and ‘}’ anymore
Importer stores resource labels instead of serialized paths in “file_selection”.
Gimlet’s “selections” is now called “file_selection”
Gimlet stores resource labels instead of serialized paths in “file_selection”.
Gimlet and Tool store command line arguments as serialized CmdLineArg objects, not serialized paths
- Parameters
old (dict) – Version 5 project dictionary
project_dir (str) – Path to current project directory
- Returns
Version 6 project dictionary
- Return type
dict
- static upgrade_v6_to_v7(old)[source]
Upgrades version 6 project dictionary to version 7.
- Changes:
Introduces Mergers in between DS -> DS links.
- Parameters
old (dict) – Version 6 project dictionary
- Returns
Version 7 project dictionary
- Return type
dict
- static upgrade_v7_to_v8(old)[source]
Upgrades version 7 project dictionary to version 8.
- Changes:
Move purge settings from items to their outgoing connections.
- Parameters
old (dict) – Version 7 project dictionary
- Returns
Version 8 project dictionary
- Return type
dict
- static upgrade_v8_to_v9(old)[source]
Upgrades version 8 project dictionary to version 9.
- Changes:
Remove [“project”][“name”] key
- Parameters
old (dict) – Version 8 project dictionary
- Returns
Version 9 project dictionary
- Return type
dict
- static upgrade_v9_to_v10(old)[source]
Upgrades version 9 project dictionary to version 10.
- Changes:
Remove connections from Gimlets and GDXExporters
Remove Gimlet items
- Parameters
old (dict) – Version 9 project dictionary
- Returns
Version 10 project dictionary
- Return type
dict
- static upgrade_v10_to_v11(old)[source]
Upgrades version 10 project dictionary to version 11.
- Changes:
Add [“project”][“settings”] key
- Parameters
old (dict) – Version 10 project dictionary
- Returns
Version 11 project dictionary
- Return type
dict
- static upgrade_v11_to_v12(old)[source]
Upgrades version 11 project dictionary to version 12.
- Changes:
1. Julia’s execution settings are now Tool Spec settings instead of global settings Execution settings are local user settings so this only updates the project version to make sure that these projects cannot be opened with an older Toolbox version.
- Parameters
old (dict) – Version 11 project dictionary
- Returns
Version 12 project dictionary
- Return type
dict
- static upgrade_v12_to_v13(old)[source]
Upgrades version 12 project dictionary to version 13.
- Changes:
1. Connections now have enabled filter types field. Old projects should open just fine so this only updates the project version to make sure that these projects cannot be opened with an older Toolbox version.
- Parameters
old (dict) – Version 12 project dictionary
- Returns
Version 13 project dictionary
- Return type
dict
- get_project_directory()[source]
Asks the user to select a new project directory. If the selected directory is already a Spine Toolbox project directory, asks if overwrite is ok. Used when opening a project from an old style project file (.proj).
- Returns
Path to project directory or an empty string if operation is canceled.
- Return type
str
- is_valid(v, p)[source]
Checks given project dict if it is valid for given version.
- Parameters
v (int) – project version to validate against
p (dict) – project dictionary
- Returns
True if project is valid, False otherwise
- Return type
bool
- is_valid_v1(p)[source]
Checks that the given project JSON dictionary contains a valid version 1 Spine Toolbox project. Valid meaning, that it contains all required keys and values are of the correct type.
- Parameters
p (dict) – Project information JSON
- Returns
True if project is a valid version 1 project, False if it is not
- Return type
bool
- is_valid_v2_to_v8(p, v)[source]
Checks that the given project JSON dictionary contains a valid version 2 to 8 Spine Toolbox project. Valid meaning, that it contains all required keys and values are of the correct type.
- Parameters
p (dict) – Project information JSON
v (int) – Version
- Returns
True if project is a valid version 2 to version 8 project, False if it is not
- Return type
bool
- is_valid_v9_to_v10(p)[source]
Checks that the given project JSON dictionary contains a valid version 9 or 10 Spine Toolbox project. Valid meaning, that it contains all required keys and values are of the correct type.
- Parameters
p (dict) – Project information JSON
- Returns
True if project is a valid version 9 and 10 project, False otherwise
- Return type
bool
- is_valid_v11_to_v12(p)[source]
Checks that the given project JSON dictionary contains a valid version 11 or 12 Spine Toolbox project. Valid meaning, that it contains all required keys and values are of the correct type.
- Parameters
p (dict) – Project information JSON
- Returns
True if project is a valid version 11 or 12 project, False otherwise
- Return type
bool
spinetoolbox.qthread_pool_executor
Qt-based thread pool executor.
Module Contents
A Qt-based clone of queue.Queue. |
|
A Qt-based clone of concurrent.futures.Future. |
|
A Qt-based clone of threading.Thread. |
|
A Qt-based clone of concurrent.futures.ThreadPoolExecutor |
|
|
- exception spinetoolbox.qthread_pool_executor.TimeOutError[source]
Bases:
Exception
An exception to raise when a timeouts expire
Initialize self. See help(type(self)) for accurate signature.
- class spinetoolbox.qthread_pool_executor._CustomQSemaphore[source]
Bases:
PySide6.QtCore.QSemaphore
- class spinetoolbox.qthread_pool_executor.QtBasedFuture[source]
A Qt-based clone of concurrent.futures.Future.
- class spinetoolbox.qthread_pool_executor.QtBasedThread(target=None, args=())[source]
Bases:
PySide6.QtCore.QThread
A Qt-based clone of threading.Thread.
- class spinetoolbox.qthread_pool_executor.QtBasedThreadPoolExecutor(max_workers=None)[source]
A Qt-based clone of concurrent.futures.ThreadPoolExecutor
spinetoolbox.spine_db_commands
QUndoCommand subclasses for modifying the db.
Module Contents
|
|
Base class for all commands that modify a Spine DB. |
|
Base class for all commands that modify a Spine DB. |
|
Base class for all commands that modify a Spine DB. |
|
Base class for all commands that modify a Spine DB. |
|
Base class for all commands that modify a Spine DB. |
- class spinetoolbox.spine_db_commands.AgedUndoCommand(parent=None, identifier=-1)[source]
Bases:
PySide6.QtGui.QUndoCommand
- Parameters
parent (QUndoCommand, optional) – The parent command, used for defining macros.
- class spinetoolbox.spine_db_commands.SpineDBCommand(db_mngr, db_map, **kwargs)[source]
Bases:
AgedUndoCommand
Base class for all commands that modify a Spine DB.
- Parameters
db_mngr (SpineDBManager) – SpineDBManager instance
db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance
- class spinetoolbox.spine_db_commands.AddItemsCommand(db_mngr, db_map, item_type, data, check=True, **kwargs)[source]
Bases:
SpineDBCommand
Base class for all commands that modify a Spine DB.
- Parameters
db_mngr (SpineDBManager) – SpineDBManager instance
db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance
data (list) – list of dict-items to add
item_type (str) – the item type
- class spinetoolbox.spine_db_commands.UpdateItemsCommand(db_mngr, db_map, item_type, data, check=True, **kwargs)[source]
Bases:
SpineDBCommand
Base class for all commands that modify a Spine DB.
- Parameters
db_mngr (SpineDBManager) – SpineDBManager instance
db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance
item_type (str) – the item type
data (list) – list of dict-items to update
- class spinetoolbox.spine_db_commands.AddUpdateItemsCommand(db_mngr, db_map, item_type, data, check=True, **kwargs)[source]
Bases:
SpineDBCommand
Base class for all commands that modify a Spine DB.
- Parameters
db_mngr (SpineDBManager) – SpineDBManager instance
db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance
item_type (str) – the item type
data (list) – list of dict-items to add-update
- class spinetoolbox.spine_db_commands.RemoveItemsCommand(db_mngr, db_map, item_type, ids, check=True, **kwargs)[source]
Bases:
SpineDBCommand
Base class for all commands that modify a Spine DB.
- Parameters
db_mngr (SpineDBManager) – SpineDBManager instance
db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance
item_type (str) – the item type
ids (set) – set of ids to remove
spinetoolbox.spine_db_icon_manager
Provides SpineDBIconManager.
Module Contents
A class to manage object_class icons for spine db editors. |
|
Specialization of QIconEngine used to draw scene-based icons. |
|
|
|
- class spinetoolbox.spine_db_icon_manager._SceneSvgRenderer(scene)[source]
Bases:
PySide6.QtSvg.QSvgRenderer
- class spinetoolbox.spine_db_icon_manager.SpineDBIconManager[source]
A class to manage object_class icons for spine db editors.
- update_icon_caches(classes)[source]
Called after adding or updating entity classes. Stores display_icons and clears obsolete entries from the relationship class and entity group renderer caches.
- Parameters
classes (list) – List of entity classes that were updated.
- update_multi_classes(name, dimension_name_list, id_)[source]
Updates the multi class renderers when their members change
- class spinetoolbox.spine_db_icon_manager.SceneIconEngine(scene)[source]
Bases:
spinetoolbox.helpers.TransparentIconEngine
Specialization of QIconEngine used to draw scene-based icons.
spinetoolbox.spine_db_manager
The SpineDBManager class.
Module Contents
Class to manage DBs within a project. |
Creates a new spine database at the given url. |
- spinetoolbox.spine_db_manager.do_create_new_spine_database(url)[source]
Creates a new spine database at the given url.
- class spinetoolbox.spine_db_manager.SpineDBManager(settings, parent, synchronous=False)[source]
Bases:
PySide6.QtCore.QObject
Class to manage DBs within a project.
- Parameters
settings (QSettings) – Toolbox settings
parent (QObject, optional) – parent object
synchronous (bool) – If True, fetch database synchronously
- items_added[source]
Emitted whenever items are added to a DB.
- Parameters
str – item type, such as “object_class”
dict – mapping DatabaseMapping to list of added dict-items.
- items_updated[source]
Emitted whenever items are updated in a DB.
- Parameters
str – item type, such as “object_class”
dict – mapping DatabaseMapping to list of updated dict-items.
- items_removed[source]
Emitted whenever items are removed from a DB.
- Parameters
str – item type, such as “object_class”
dict – mapping DatabaseMapping to list of updated dict-items.
- _get_worker(db_map)[source]
Returns a worker.
- Parameters
db_map (DatabaseMapping) – database mapping
- Returns
worker for the db_map
- Return type
- register_fetch_parent(db_map, parent)[source]
Registers a fetch parent.
- Parameters
db_map (DatabaseMapping) – target database mapping
parent (FetchParent) – fetch parent
- can_fetch_more(db_map, parent)[source]
Whether or not we can fetch more items of given type from given db.
- Parameters
db_map (DatabaseMapping) –
parent (FetchParent) – The object that requests the fetching and that might want to react to further DB modifications.
- Returns
bool
- fetch_more(db_map, parent)[source]
Fetches more items of given type from given db.
- Parameters
db_map (DatabaseMapping) –
parent (FetchParent) – The object that requests the fetching.
- get_icon_mngr(db_map)[source]
Returns an icon manager for given db_map.
- Parameters
db_map (DatabaseMapping) –
- Returns
SpineDBIconManager
- static db_map_key(db_map)[source]
Creates an identifier for given db_map.
- Parameters
db_map (DatabaseMapping) – database mapping
- Returns
identification key
- Return type
int
- db_map_from_key(key)[source]
Returns database mapping that corresponds to given identification key.
- Parameters
key (int) – identification key
- Returns
database mapping
- Return type
DatabaseMapping
- Raises
KeyError – raised if database map is not found
- db_map(url)[source]
Returns a database mapping for given URL.
- Parameters
url (str) – a database URL
- Returns
a database map or None if not found
- Return type
DatabaseMapping
- close_session(url)[source]
Pops any db map on the given url and closes its connection.
- Parameters
url (str) –
- get_db_map(url, logger, ignore_version_error=False, window=False, codename=None, create=False)[source]
Returns a DatabaseMapping instance from url if possible, None otherwise. If needed, asks the user to upgrade to the latest db version.
- Parameters
url (str, URL) –
logger (LoggerInterface) –
ignore_version_error (bool, optional) –
window (bool, optional) –
codename (str, NoneType, optional) –
create (bool, optional) –
- Returns
DatabaseMapping, NoneType
- _do_get_db_map(url, **kwargs)[source]
Returns a memorized DatabaseMapping instance from url. Called by get_db_map.
- Parameters
url (str, URL) –
codename (str, NoneType) –
upgrade (bool) –
create (bool) –
- Returns
DatabaseMapping
- register_listener(listener, *db_maps)[source]
Register given listener for all given db_map’s signals.
- Parameters
listener (object) –
*db_maps –
- unregister_listener(listener, *db_maps, dirty_db_maps=None, commit_dirty=False, commit_msg='')[source]
Unregisters given listener from given db_map signals. If any of the db_maps becomes an orphan and is dirty, prompts user to commit or rollback.
- Parameters
listener (object) –
*db_maps –
commit_dirty (bool) – True to commit dirty database mapping, False to roll back
commit_msg (str) – commit message
- Returns
All the db maps that failed to commit
- Return type
failed_db_maps (list)
- update_data_store_db_maps()[source]
Updates the db maps of the dict that maps db_maps to Data Stores
- is_dirty(db_map)[source]
Returns True if mapping has pending changes.
- Parameters
db_map (DatabaseMapping) – database mapping
- Returns
True if db_map has pending changes, False otherwise
- Return type
bool
- dirty(*db_maps)[source]
Filters clean mappings from given database maps.
- Parameters
*db_maps – mappings to check
- Returns
dirty mappings
- Return type
list of DatabaseMapping
- dirty_and_without_editors(listener, *db_maps)[source]
Checks which of the given database mappings are dirty and have no editors.
- Parameters
listener (Any) – a listener object
*db_maps – mappings to check
- Returns
mappings that are dirty and don’t have editors
- Return type
list of DatabaseMapping
- commit_session(commit_msg, *dirty_db_maps, cookie=None)[source]
Commits the current session.
- Parameters
commit_msg (str) – commit message for all database maps
*dirty_db_maps – dirty database maps to commit
cookie (object, optional) – a free form identifier which will be forwarded to
SpineDBWorker.commit_session
- _do_commit_session(db_map, commit_msg, cookie=None)[source]
Commits session for given db.
- Parameters
db_map (DatabaseMapping) – db map
commit_msg (str) – commit message
cookie (Any) – a cookie to include in receive_session_committed call
- Returns
bool
- notify_session_committed(cookie, *db_maps)[source]
Notifies manager and listeners when a commit has taken place by a third party.
- Parameters
cookie (Any) – commit cookie
*db_maps – database maps that were committed
- rollback_session(*dirty_db_maps)[source]
Rolls back the current session.
- Parameters
*dirty_db_maps – dirty database maps to commit
- _do_rollback_session(db_map)[source]
Rolls back session for given db.
- Parameters
db_map (DatabaseMapping) – db map
- entity_class_renderer(db_map, entity_class_id, for_group=False, color=None)[source]
Returns an icon renderer for a given entity class.
- Parameters
db_map (DatabaseMapping) – database map
entity_class_id (int) – entity class id
for_group (bool) – if True, return the group object icon instead
color (QColor, optional) – icon color
- Returns
requested renderer or None if no entity class was found
- Return type
QSvgRenderer
- entity_class_icon(db_map, entity_class_id, for_group=False)[source]
Returns an appropriate icon for a given entity class.
- Parameters
db_map (DatabaseMapping) – database map
entity_class_id (int) – entity class’ id
for_group (bool) – if True, return the group object icon instead
- Returns
requested icon or None if no entity class was found
- Return type
QIcon
- static get_item(db_map, item_type, id_)[source]
Returns the item of the given type in the given db map that has the given id, or an empty dict if not found.
- Parameters
db_map (DatabaseMapping) –
item_type (str) –
id (TempId) –
- Returns
the item
- Return type
PublicItem
- static get_items(db_map, item_type)[source]
Returns a list of the items of the given type in the given db map.
- Parameters
db_map (DatabaseMapping) –
item_type (str) –
- Returns
list
- get_items_by_field(db_map, item_type, field, value)[source]
Returns a list of items of the given type in the given db map that have the given value for the given field.
- Parameters
db_map (DatabaseMapping) –
item_type (str) –
field (str) –
value –
- Returns
list
- get_item_by_field(db_map, item_type, field, value)[source]
Returns the first item of the given type in the given db map that has the given value for the given field Returns an empty dictionary if none found.
- Parameters
db_map (DatabaseMapping) –
item_type (str) –
field (str) –
value –
- Returns
dict
- static display_data_from_parsed(parsed_data)[source]
Returns the value’s database representation formatted for Qt.ItemDataRole.DisplayRole.
- static tool_tip_data_from_parsed(parsed_data)[source]
Returns the value’s database representation formatted for Qt.ItemDataRole.ToolTipRole.
- get_value(db_map, item, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the value or default value of a parameter.
- Parameters
db_map (DatabaseMapping) – database mapping
item (PublicItem) – parameter value item, parameter definition item, or list value item
role (Qt.ItemDataRole) – data role
- Returns
any
- get_value_from_data(data, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the value or default value of a parameter directly from data. Used by
EmptyParameterModel.data()
.- Parameters
data (str) – joined value and type
role (int, optional) –
- Returns
any
- _format_value(parsed_value, role=Qt.ItemDataRole.DisplayRole)[source]
Formats the given value for the given role.
- Parameters
parsed_value (object) – A python object as returned by spinedb_api.from_database
role (int, optional) –
- get_value_indexes(db_map, item_type, id_)[source]
Returns the value or default value indexes of a parameter.
- Parameters
db_map (DatabaseMapping) –
item_type (str) – either “parameter_definition” or “parameter_value”
id (int) – The parameter_value or definition id
- get_value_index(db_map, item_type, id_, index, role=Qt.ItemDataRole.DisplayRole)[source]
Returns the value or default value of a parameter for a given index.
- Parameters
db_map (DatabaseMapping) –
item_type (str) – either “parameter_definition” or “parameter_value”
id (int) – The parameter_value or definition id
index – The index to retrieve
role (int, optional) –
- get_value_list_item(db_map, id_, index, role=Qt.ItemDataRole.DisplayRole)[source]
Returns one value item of a parameter_value_list.
- Parameters
db_map (DatabaseMapping) –
id (int) – The parameter_value_list id
index (int) – The value item index
role (int, optional) –
- get_parameter_value_list(db_map, id_, role=Qt.ItemDataRole.DisplayRole)[source]
Returns a parameter_value_list formatted for the given role.
- Parameters
db_map (DatabaseMapping) –
id (int) – The parameter_value_list id
role (int, optional) –
- import_data(db_map_data, command_text='Import data')[source]
Imports the given data into given db maps using the dedicated import functions from spinedb_api. Condenses all in a single command for undo/redo.
- Parameters
db_map_data (dict(DatabaseMapping, dict())) – Maps dbs to data to be passed as keyword arguments to get_data_for_import
command_text (str, optional) – What to call the command that condenses the operation.
- add_alternatives(db_map_data)[source]
Adds alternatives to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_scenarios(db_map_data)[source]
Adds scenarios to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_entity_classes(db_map_data)[source]
Adds entity classes to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_entities(db_map_data)[source]
Adds entities to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_entity_groups(db_map_data)[source]
Adds entity groups to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_entity_alternatives(db_map_data)[source]
Adds entity alternatives to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_parameter_definitions(db_map_data)[source]
Adds parameter definitions to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_parameter_values(db_map_data)[source]
Adds parameter values to db without checking integrity.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_parameter_value_lists(db_map_data)[source]
Adds parameter_value lists to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_list_values(db_map_data)[source]
Adds parameter_value list values to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_metadata(db_map_data)[source]
Adds metadata to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_entity_metadata(db_map_data)[source]
Adds entity metadata to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_parameter_value_metadata(db_map_data)[source]
Adds parameter value metadata to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_ext_entity_metadata(db_map_data)[source]
Adds entity metadata together with all necessary metadata to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- add_ext_parameter_value_metadata(db_map_data)[source]
Adds parameter value metadata together with all necessary metadata to db.
- Parameters
db_map_data (dict) – lists of items to add keyed by DatabaseMapping
- update_alternatives(db_map_data)[source]
Updates alternatives in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_scenarios(db_map_data)[source]
Updates scenarios in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_entity_classes(db_map_data)[source]
Updates entity classes in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_entities(db_map_data)[source]
Updates entities in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_entity_alternatives(db_map_data)[source]
Updates entity alternatives in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_parameter_definitions(db_map_data)[source]
Updates parameter definitions in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_parameter_values(db_map_data)[source]
Updates parameter values in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_expanded_parameter_values(db_map_data)[source]
Updates expanded parameter values in db.
- Parameters
db_map_data (dict) – lists of expanded items to update keyed by DatabaseMapping
- update_parameter_value_lists(db_map_data)[source]
Updates parameter_value lists in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_list_values(db_map_data)[source]
Updates parameter_value list values in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_metadata(db_map_data)[source]
Updates metadata in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_entity_metadata(db_map_data)[source]
Updates entity metadata in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_parameter_value_metadata(db_map_data)[source]
Updates parameter value metadata in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_ext_entity_metadata(db_map_data)[source]
Updates entity metadata in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- update_ext_parameter_value_metadata(db_map_data)[source]
Updates parameter value metadata in db.
- Parameters
db_map_data (dict) – lists of items to update keyed by DatabaseMapping
- set_scenario_alternatives(db_map_data)[source]
Sets scenario alternatives in db.
- Parameters
db_map_data (dict) – lists of items to set keyed by DatabaseMapping
- static get_data_to_set_scenario_alternatives(db_map, scenarios)[source]
Returns data to add and remove, in order to set wide scenario alternatives.
- Parameters
db_map (DatabaseMapping) – the db_map
scenarios –
One or more wide scenario
dict
objects to set. Each item must include the following keys:”id”: integer scenario id
”alternative_id_list”: list of alternative ids for that scenario
- Returns
list: scenario_alternative
dict
objects to add. set: integer scenario_alternative ids to remove
- purge_items(db_map_item_types, **kwargs)[source]
Purges selected items from given database.
- Parameters
db_map_item_types (dict) – mapping from database map to list of purgable item types
**kwargs – keyword arguments passed to
remove_items()
- add_items(item_type, db_map_data, identifier=None, **kwargs)[source]
Pushes commands to add items to undo stack.
- update_items(item_type, db_map_data, identifier=None, **kwargs)[source]
Pushes commands to update items to undo stack.
- add_update_items(item_type, db_map_data, identifier=None, **kwargs)[source]
Pushes commands to add_update items to undo stack.
- remove_items(db_map_typed_ids, identifier=None, **kwargs)[source]
Pushes commands to remove items to undo stack.
- do_remove_items(db_map, item_type, ids, check=True)[source]
Removes items from database.
- Parameters
db_map – DatabaseMapping instance
item_type (str) – database item type
ids (set) – ids to remove
- do_restore_items(db_map, item_type, ids)[source]
Restores items in database.
- Parameters
db_map – DatabaseMapping instance
item_type (str) – database item type
ids (set) – ids to restore
- find_cascading_entity_classes(db_map_ids)[source]
Finds and returns cascading entity classes for the given dimension ids.
- find_cascading_entities(db_map_ids)[source]
Finds and returns cascading entities for the given element ids.
- find_cascading_parameter_data(db_map_ids, item_type)[source]
Finds and returns cascading parameter definitions or values for the given entity_class ids.
- find_cascading_parameter_values_by_entity(db_map_ids)[source]
Finds and returns cascading parameter values for the given entity ids.
- find_cascading_parameter_values_by_definition(db_map_ids)[source]
Finds and returns cascading parameter values for the given parameter_definition ids.
- find_cascading_scenario_alternatives_by_scenario(db_map_ids)[source]
Finds and returns cascading scenario alternatives for the given scenario ids.
- duplicate_entity(orig_name, dup_name, class_name, db_maps)[source]
Duplicates entity, its parameter values and related multidimensional entities.
- Parameters
orig_name (str) – original entity’s name
dup_name (str) – duplicate’s name
class_name (str) – entity class name
db_maps (Iterable of DatabaseMapping) – database mappings where duplication should take place
- static export_to_json(file_path, data_for_export, caller)[source]
Exports given data into JSON file.
- static export_to_excel(file_path, data_for_export, caller)[source]
Exports given data into Excel file.
- static get_all_multi_spine_db_editors()[source]
Yields all instances of MultiSpineDBEditor currently open.
- Yields
MultiSpineDBEditor
- get_all_spine_db_editors()[source]
Yields all instances of SpineDBEditor currently open.
- Yields
SpineDBEditor
- open_db_editor(db_url_codenames, reuse_existing_editor)[source]
Opens a SpineDBEditor with given urls. Uses an existing MultiSpineDBEditor if any. Also, if the same urls are open in an existing SpineDBEditor, just raises that one instead of creating another.
- Parameters
db_url_codenames (dict) – mapping url to codename
reuse_existing_editor (bool) – if True and the same URL is already open, just raise the existing window
spinetoolbox.spine_db_parcel
SpineDBParcel class.
Module Contents
A class to create parcels of data from a Spine db. |
- class spinetoolbox.spine_db_parcel.SpineDBParcel(db_mngr)[source]
A class to create parcels of data from a Spine db. Mainly intended for the Export selection action in the Spine db editor:
push
methods push items with everything they need to live in a standalone db.full_push
andinner_push
methods do something more specific
Initializes the parcel object.
- Parameters
db_mngr (SpineDBManager) –
- _get_field_values(db_map, item_type, field, ids)[source]
Returns a list of field values for items of given type, having given ids.
- full_push_entity_class_ids(db_map_ids)[source]
Pushes parameter definitions associated with given entity classes. This essentially full_pushes the entity classes, their parameter definitions, and their member entity classes.
- full_push_entity_ids(db_map_ids)[source]
Pushes parameter values associated with entities and their elements. This essentially full_pushes entities, all the parameter values, and all the necessary classes, definitions, and lists.
- inner_push_entity_ids(db_map_ids)[source]
Pushes entity ids, cascading entity ids, and the associated parameter values, but not any entity classes or parameter definitions. Mainly intended for the Duplicate entity action.
spinetoolbox.spine_db_worker
The SpineDBWorker class.
Module Contents
Does all the communication with a certain DB for SpineDBManager, in a non-GUI thread. |
- class spinetoolbox.spine_db_worker.SpineDBWorker(db_mngr, db_url, synchronous=False)[source]
Bases:
PySide6.QtCore.QObject
Does all the communication with a certain DB for SpineDBManager, in a non-GUI thread.
- register_fetch_parent(parent)[source]
Registers the given parent.
- Parameters
parent (FetchParent) – parent to add
- _iterate_mapping(parent)[source]
Iterates the in-memory mapping for given parent while updating its
position
property. Iterated items are added to the parent if it accepts them.- Parameters
parent (FetchParent) – the parent.
- Returns
Whether the parent can stop fetching from now
- Return type
bool
- can_fetch_more(parent)[source]
Returns whether more data can be fetched for parent. Also, registers the parent to notify it of any relevant DB modifications later on.
- Parameters
parent (FetchParent) – fetch parent
- Returns
True if more data is available, False otherwise
- Return type
bool
- fetch_more(parent)[source]
Fetches items from the database.
- Parameters
parent (FetchParent) – fetch parent
- add_items(item_type, orig_items, check)[source]
Adds items to db.
- Parameters
item_type (str) – item type
orig_items (list) – dict-items to add
check (bool) – Whether to check integrity
- update_items(item_type, orig_items, check)[source]
Updates items in db.
- Parameters
item_type (str) – item type
orig_items (list) – dict-items to update
check (bool) – Whether or not to check integrity
- add_update_items(item_type, orig_items, check)[source]
Add-updates items in db.
- Parameters
item_type (str) – item type
orig_items (list) – dict-items to update
check (bool) – Whether or not to check integrity
- remove_items(item_type, ids, check)[source]
Removes items from database.
- Parameters
item_type (str) – item type
ids (set) – ids of items to remove
spinetoolbox.spine_engine_manager
Contains SpineEngineManagerBase.
Module Contents
Responsible for remote project execution. |
|
Returns either a Local or a remote Spine Engine Manager based on settings. |
- class spinetoolbox.spine_engine_manager.SpineEngineManagerBase[source]
- abstract run_engine(engine_data)[source]
Runs an engine with given data.
- Parameters
engine_data (dict) – The engine data.
- abstract get_engine_event()[source]
Gets next event from a running engine.
- Returns
two element tuple: event type identifier string, and event data dictionary
- Return type
tuple(str,dict)
- abstract answer_prompt(prompter_id, answer)[source]
Answers prompt.
- Parameters
prompter_id (int) – The id of the prompter
answer – The user’s decision.
- abstract restart_kernel(connection_file)[source]
Restarts the jupyter kernel associated to given connection file.
- Parameters
connection_file (str) – path of connection file
- abstract shutdown_kernel(connection_file)[source]
Shuts down the jupyter kernel associated to given connection file.
- Parameters
connection_file (str) – path of connection file
- abstract issue_persistent_command(persistent_key, command)[source]
Issues a command to a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
command (str) – command to issue
- Returns
stdin, stdout, and stderr messages (dictionaries with two keys: type, and data)
- Return type
generator
- abstract is_persistent_command_complete(persistent_key, command)[source]
Checks whether a command is complete.
- Parameters
key (tuple) – persistent identifier
cmd (str) – command to issue
- Returns
bool
- abstract restart_persistent(persistent_key)[source]
Restarts a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
- Returns
stdout and stderr messages (dictionaries with two keys: type, and data)
- Return type
generator
- abstract interrupt_persistent(persistent_key)[source]
Interrupts a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
- abstract kill_persistent(persistent_key)[source]
Kills a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
- class spinetoolbox.spine_engine_manager.LocalSpineEngineManager[source]
Bases:
SpineEngineManagerBase
- run_engine(engine_data)[source]
Runs an engine with given data.
- Parameters
engine_data (dict) – The engine data.
- get_engine_event()[source]
Gets next event from a running engine.
- Returns
two element tuple: event type identifier string, and event data dictionary
- Return type
tuple(str,dict)
- answer_prompt(prompter_id, answer)[source]
Answers prompt.
- Parameters
prompter_id (int) – The id of the prompter
answer – The user’s decision.
- restart_kernel(connection_file)[source]
Restarts the jupyter kernel associated to given connection file.
- Parameters
connection_file (str) – path of connection file
- shutdown_kernel(connection_file)[source]
Shuts down the jupyter kernel associated to given connection file.
- Parameters
connection_file (str) – path of connection file
- issue_persistent_command(persistent_key, command)[source]
Issues a command to a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
command (str) – command to issue
- Returns
stdin, stdout, and stderr messages (dictionaries with two keys: type, and data)
- Return type
generator
- is_persistent_command_complete(persistent_key, command)[source]
Checks whether a command is complete.
- Parameters
key (tuple) – persistent identifier
cmd (str) – command to issue
- Returns
bool
- restart_persistent(persistent_key)[source]
Restarts a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
- Returns
stdout and stderr messages (dictionaries with two keys: type, and data)
- Return type
generator
- interrupt_persistent(persistent_key)[source]
Interrupts a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
- kill_persistent(persistent_key)[source]
Kills a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
- class spinetoolbox.spine_engine_manager.RemoteSpineEngineManager(job_id='')[source]
Bases:
SpineEngineManagerBase
Responsible for remote project execution.
Initializer.
- make_engine_client(host, port, security, sec_folder, ping=True)[source]
Creates a client for connecting to Spine Engine Server.
- run_engine(engine_data)[source]
Makes an engine client for communicating with the engine server. Starts a thread for monitoring the DAG execution on server.
- Parameters
engine_data (dict) – The engine data.
- stop_engine()[source]
Sends a request to stop execution on Server then waits for _runner thread to end.
- _run()[source]
Sends a start execution request to server with the job Id. Sets up a subscribe socket according to the publish port received from server. Passes received events to SpineEngineWorker for processing. After execution has finished, downloads new files from server.
- is_persistent_command_complete(persistent_key, command)[source]
Checks whether a command is complete.
- Parameters
key (tuple) – persistent identifier
cmd (str) – command to issue
- Returns
bool
- issue_persistent_command(persistent_key, command)[source]
Issues a command to a persistent process.
- Parameters
persistent_key (tuple) – persistent identifier
command (str) – command to issue
- Returns
stdin, stdout, and stderr messages (dictionaries with two keys: type, and data)
- Return type
generator
- spinetoolbox.spine_engine_manager.make_engine_manager(remote_execution_enabled=False, job_id='')[source]
Returns either a Local or a remote Spine Engine Manager based on settings.
- Parameters
remote_execution_enabled (bool) – True returns a local Spine Engine Manager instance,
instance (False returns a remote Spine Engine Manager) –
job_id (str) – Server execution job Id
spinetoolbox.spine_engine_worker
Contains SpineEngineWorker.
Module Contents
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Fails all project items. |
- spinetoolbox.spine_engine_worker._handle_node_execution_finished(item, direction, item_state)[source]
- spinetoolbox.spine_engine_worker._handle_event_message_arrived(item, filter_id, msg_type, msg_text)[source]
- spinetoolbox.spine_engine_worker._handle_process_message_arrived(item, filter_id, msg_type, msg_text)[source]
- spinetoolbox.spine_engine_worker._mark_all_items_failed(items)[source]
Fails all project items.
- Parameters
items (list of ProjectItem) – project items
- class spinetoolbox.spine_engine_worker.SpineEngineWorker(engine_data, dag, dag_identifier, project_items, connections, logger, job_id)[source]
Bases:
PySide6.QtCore.QObject
- Parameters
engine_data (dict) – engine data
dag (DirectedGraphHandler) –
dag_identifier (str) –
project_items (dict) – mapping from project item name to
ProjectItem
connections (dict) – mapping from jump name to
LoggingConnection
orLoggingJump
logger (LoggerInterface) – a logger
job_id (str) – Job id for remote execution
- get_engine_data()[source]
Returns the engine data. Together with
self.set_engine_data()
it can be used to modify the workflow after it’s initially created. We use it at the moment for creating Julia sysimages.- Returns
dict
- set_engine_data(engine_data)[source]
Sets the engine data.
- Parameters
engine_data (dict) – New data
- start(silent=False)[source]
Connects log signals.
- Parameters
silent (bool, optional) – If True, log messages are not forwarded to the loggers but saved in internal dicts.
- _included_and_ignored_items()[source]
Returns two lists, where the first one contains project items that are about to be executed and the second one contains project items that are about to be ignored.
- _included_items(permitted_items, connections)[source]
Collects a list of project item names that are going to be executed in this DAG based on execution permits and connections in the DAG.
- Parameters
permitted_items (dict) – Mapping of item names to bool. True items have been selected by user for execution.
connections (list) – Serialized connections
- Returns
Project item names
- Return type
list
spinetoolbox.ui_main
Contains a class for the main window of Spine Toolbox.
Module Contents
Class for application main GUI functions. |
- class spinetoolbox.ui_main.ToolboxUI[source]
Bases:
PySide6.QtWidgets.QMainWindow
Class for application main GUI functions.
Initializes application and main window.
- static set_error_mode()[source]
Sets Windows error mode to show all error dialog boxes from subprocesses.
See https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-seterrormode for documentation.
- _update_execute_selected_enabled()[source]
Enables or disables execute selected action based on the number of selected items.
- update_window_modified(clean)[source]
Updates window modified status and save actions depending on the state of the undo stack.
- set_work_directory(new_work_dir=None)[source]
Creates a work directory if it does not exist or changes the current work directory to given.
- Parameters
new_work_dir (str, optional) – If given, changes the work directory to given and creates the directory if it does not exist.
- project()[source]
Returns current project or None if no project open.
- Returns
current project or None
- Return type
- item_specification_factories()[source]
Returns project item specification factories.
- Returns
specification factories
- Return type
list of ProjectItemSpecificationFactory
- init_project(project_dir)[source]
Initializes project at application start-up.
Opens the last project that was open when app was closed (if enabled in Settings) or starts the app without a project.
- Parameters
project_dir (str) – project directory
- new_project()[source]
Opens a file dialog where user can select a directory where a project is created. Pops up a question box if selected directory is not empty or if it already contains a Spine Toolbox project. Initial project name is the directory name.
- create_project(proj_dir)[source]
Creates new project and sets it active.
- Parameters
proj_dir (str) – Path to project directory
- open_project(load_dir=None)[source]
Opens project from a selected or given directory.
- Parameters
load_dir (str, optional) – Path to project base directory. If default value is used, a file explorer dialog is opened where the user can select the project to open.
- Returns
True when opening the project succeeded, False otherwise
- Return type
bool
- restore_project(project_dir, ask_confirmation=True)[source]
Initializes UI, Creates project, models, connections, etc., when opening a project.
- Parameters
project_dir (str) – Project directory
ask_confirmation (bool) – True closes the previous project with a confirmation box if user has enabled this
- Returns
True when restoring project succeeded, False otherwise
- Return type
bool
- _disable_project_actions()[source]
Disables all project-related actions, except New project, Open project and Open recent. Called in the constructor and when closing a project.
- _enable_project_actions()[source]
Enables all project-related actions. Called when a new project is created and when a project is opened.
Updates and sets up the recent projects menu to File-Open recent menu item.
- save_project_as()[source]
Asks user for a new project directory and duplicates the current project there. The name of the duplicated project will be the new directory name. The duplicated project is activated.
- close_project(ask_confirmation=True, clear_event_log=True)[source]
Closes the current project.
- Parameters
ask_confirmation (bool) – if False, no confirmation whatsoever is asked from user
clear_event_log (bool) – if True, the event log is cleared after closing the project
- Returns
True when no project open or when it’s closed successfully, False otherwise.
- Return type
bool
- set_project_description(_=False)[source]
Opens a dialog where the user can enter a new description for the project.
- add_project_items(items_dict)[source]
Pushes an AddProjectItemsCommand to the undo stack.
- Parameters
items_dict (dict) – mapping from item name to item dictionary
- supports_specifications(item_type)[source]
Returns True if given project item type supports specifications.
- Returns
True if item supports specifications, False otherwise
- Return type
bool
- undo_critical_commands()[source]
Undoes critical commands in the undo stack.
- Returns
False if any critical commands aren’t successfully undone
- Return type
Bool
- overwrite_check(project_dir)[source]
Checks if given directory is a project directory and/or empty And asks the user what to do in that case.
- Parameters
project_dir (str) – Abs. path to a directory
- Returns
True if user wants to overwrite an existing project or if the directory is not empty and the user wants to make it into a Spine Toolbox project directory anyway. False if user cancels the action.
- Return type
bool
- _set_active_project_item(active_project_item)[source]
Activates given project item.
- Parameters
active_project_item (ProjectItemBase or NoneType) – Active project item
- _set_active_link_item(active_link_item)[source]
Activates given link and connects it to the corresponding Properties widget.
- Parameters
active_link_item (LoggingConnection or LoggingJump, optional) – Active link
- _get_active_properties_widget()[source]
Returns the active item’s or link’s properties widget or None if no item or link is active.
- import_specification()[source]
Opens a file dialog where the user can select an existing specification definition file (.json). If file is valid, pushes AddSpecificationCommand to undo stack.
- replace_specification(name, specification)[source]
Pushes an ReplaceSpecificationCommand to undo stack.
- repair_specification(name)[source]
Repairs specification if it is broken.
- Parameters
name (str) – Specification’s name
- prompt_save_location(title, proposed_path, file_filter)[source]
Shows a dialog for the user to select a path to save a file.
- Parameters
title (str) – Dialog window title
proposed_path (str) – Proposed location.
file_filter (str) – File extension filter
- Returns
Absolute path or None if dialog was cancelled
- Return type
str
- _log_specification_saved(name, path)[source]
Prints a message in the event log, saying that given spec was saved in a certain location, together with a clickable link to change the location.
- Parameters
name (str) – Specification’s name
path (str) – Specification’s file path
- register_anchor_callback(url, callback)[source]
Registers a callback for a given anchor in event log, see
open_anchor()
. Used byToolFactory.repair_specification()
.- Parameters
url (str) – Anchor url
callback (function) – Function to call when the anchor is clicked
- open_anchor(qurl)[source]
Open file explorer in the directory given in qurl.
- Parameters
qurl (QUrl) – The url to open
- _change_specification_file_location(name)[source]
Prompts user for new location for a project item specification.
Delegates saving to project if one is open by pushing a command to the undo stack, otherwise tries to find the specification from the plugin manager.
- Parameters
name (str) – Specification’s name
Context menu for item specifications.
- Parameters
ind (QModelIndex) – In the ProjectItemSpecificationModel
global_pos (QPoint) – Mouse position
- edit_specification(index, item)[source]
Opens a specification editor widget.
- Parameters
index (QModelIndex) – Index of the item (from double-click or context menu signal)
item (ProjectItem, optional) –
- remove_specification(index)[source]
Removes specification from project.
- Parameters
index (QModelIndex) – Index of the specification item
- open_specification_file(index)[source]
Open the specification definition file in the default (.json) text-editor.
- Parameters
index (QModelIndex) – Index of the item
- _handle_zoom_reset_pressed()[source]
Slot for handling case when ‘reset zoom’ button in menu is pressed.
- restore_dock_widgets()[source]
Dock all floating and or hidden QDockWidgets back to the main window.
Adds extra actions to Edit and View menu.
- toggle_properties_tabbar_visibility()[source]
Shows or hides the tab bar in properties dock widget. For debugging purposes.
- update_datetime()[source]
Returns a boolean, which determines whether date and time is prepended to every Event Log message.
- add_message(msg)[source]
Appends a regular message to the Event Log.
- Parameters
msg (str) – String written to QTextBrowser
- add_success_message(msg)[source]
Appends a message with green text to the Event Log.
- Parameters
msg (str) – String written to QTextBrowser
- add_error_message(msg)[source]
Appends a message with red color to the Event Log.
- Parameters
msg (str) – String written to QTextBrowser
- add_warning_message(msg)[source]
Appends a message with yellow (golden) color to the Event Log.
- Parameters
msg (str) – String written to QTextBrowser
- add_process_message(msg)[source]
Writes message from stdout to the Event Log.
- Parameters
msg (str) – String written to QTextBrowser
- add_process_error_message(msg)[source]
Writes message from stderr to the Event Log.
- Parameters
msg (str) – String written to QTextBrowser
- _override_console()[source]
Sets the jupyter console of the active project item in Jupyter Console and updates title.
- _override_execution_list()[source]
Displays executions of the active project item in Executions and updates title.
- _refresh_console_execution_list()[source]
Refreshes console executions as the active project item starts new executions.
- _select_console_execution(current, _previous)[source]
Sets the console of the selected execution in Console.
- supports_specification(item_type)[source]
Returns True if given item type supports specifications.
- Parameters
item_type (str) – Item’s type
- Returns
True if item supports specifications, False otherwise
- Return type
bool
- show_specification_form(item_type, specification=None, item=None, **kwargs)[source]
Shows specification widget.
- Parameters
item_type (str) – Item’s type
specification (ProjectItemSpecification, optional) – Specification
item (ProjectItem, optional) – Project item
**kwargs – Parameters passed to the specification widget
Creates and shows the project item context menu.
- Parameters
pos (QPoint) – Mouse position
item (ProjectItem, optional) – Project item or None
Shows the Context menu for connection links.
- Parameters
pos (QPoint) – Mouse position
link (Link(QGraphicsPathItem)) – The link in question
- refresh_edit_action_states()[source]
Sets the enabled/disabled state for copy, paste, duplicate, remove and rename actions in File-Edit menu, project tree view context menu, and in Design View context menus just before the menus are shown to user.
- enable_edit_actions()[source]
Enables project item edit actions after a QMenu has been shown. This is needed to enable keyboard shortcuts (e.g. Ctrl-C & del) again.
- _tasks_before_exit()[source]
Returns a list of tasks to perform before exiting the application.
Possible tasks are:
“prompt exit”: prompt user if quitting is really desired
“prompt save”: prompt user if project should be saved before quitting
“save”: save project before quitting
- Returns
Zero or more tasks in a list
- Return type
list
- _perform_pre_exit_tasks()[source]
Prompts user to confirm quitting and saves the project if necessary.
- Returns
True if exit should proceed, False if the process was cancelled
- Return type
bool
- _confirm_exit()[source]
Confirms exiting from user.
- Returns
True if exit should proceed, False if user cancelled
- Return type
bool
- _confirm_project_close()[source]
Confirms exit from user and saves the project if requested.
- Returns
True if exiting should proceed, False if user cancelled
- Return type
bool
- remove_path_from_recent_projects(p)[source]
Removes entry that contains given path from the recent project files list in QSettings.
- Parameters
p (str) – Full path to a project directory
- update_recent_projects()[source]
Adds a new entry to QSettings variable that remembers twenty most recent project paths.
- closeEvent(event)[source]
Method for handling application exit.
- Parameters
event (QCloseEvent) – PySide6 event
- _serialize_selected_items()[source]
Serializes selected project items into a dictionary.
The serialization protocol tries to imitate the format in which projects are saved.
- Returns
a dict containing serialized version of selected project items
- Return type
dict
- _deserialized_item_position_shifts(item_dicts)[source]
Calculates horizontal and vertical shifts for project items being deserialized.
If the mouse cursor is on the Design view we try to place the items unders the cursor. Otherwise, the items will get a small shift, so they don’t overlap a possible item below. In case the items don’t fit the scene rect we clamp their coordinates within it.
- Parameters
item_dicts (dict) – Dictionary of serialized items being deserialized
- Returns
a tuple of (horizontal shift, vertical shift) in scene’s coordinates
- Return type
tuple
- static _set_deserialized_item_position(item_dict, shift_x, shift_y, scene_rect)[source]
Moves item’s position by shift_x and shift_y while keeping it within the limits of scene_rect.
- _deserialize_items(items_dict, duplicate_files=False)[source]
Deserializes project items from a dictionary and adds them to the current project.
- Parameters
items_dict (dict) – Serialized project items
- project_item_from_clipboard(duplicate_files=False)[source]
Adds project items in system’s clipboard to the current project.
- Parameters
duplicate_files (bool) – Duplicate files boolean
- set_icon_and_properties_ui(item_name)[source]
Adds properties UI to given project item.
- Parameters
item_name (str) – Item’s name
- project_item_properties_ui(item_type)[source]
Returns the properties tab widget’s ui.
- Parameters
item_type (str) – Project item’s type
- Returns
Item’s properties tab widget
- Return type
QWidget
- _open_project_item_directory(_)[source]
Opens active project item’s directory in system’s file browser.
- _remove_selected_items(_)[source]
Pushes commands to remove selected project items and links from project.
Creates a context menu for project items.
- Parameters
additional_actions (list of QAction) – Actions to be prepended to the menu
- Returns
Project item context menu
- Return type
QMenu
- start_detached_jupyter_console(kernel_name, icon, conda)[source]
Launches a new detached Console with the given kernel name or activates an existing Console if the kernel is already running.
- Parameters
kernel_name (str) – Requested kernel name
icon (QIcon) – Icon representing the kernel language
conda (bool) – Is this a Conda kernel?
- _setup_jupyter_console(item, filter_id, kernel_name, connection_file, connection_file_dict)[source]
Sets up jupyter console, eventually for a filter execution.
- Parameters
item (ProjectItem) – Item
filter_id (str) – Filter identifier
kernel_name (str) – Jupyter kernel name
connection_file (str) – Path to connection file
connection_file_dict (dict) – Contents of connection file when kernel manager runs on Spine Engine Server
- _handle_kernel_shutdown(item, filter_id)[source]
Closes the kernel client when kernel manager has been shutdown due to an enabled ‘Kill consoles at the end of execution’ option.
- Parameters
item (ProjectItem) – Item
filter_id (str) – Filter identifier
- _setup_persistent_console(item, filter_id, key, language)[source]
Sets up persistent console, eventually for a filter execution.
- Parameters
item (ProjectItem) – Item
filter_id (str) – Filter identifier
key (tuple) – Key
language (str) – Language (e.g. ‘python’ or ‘julia’)
- _make_jupyter_console(item, kernel_name, connection_file)[source]
Creates a new JupyterConsoleWidget for given connection file if none exists yet, and returns it.
- Parameters
item (ProjectItem) – Item that owns the console
kernel_name (str) – Name of the kernel
connection_file (str) – Path of kernel connection file
- Returns
JupyterConsoleWidget
- _make_persistent_console(item, key, language)[source]
Creates a new PersistentConsoleWidget for given process key.
- Parameters
item (ProjectItem) – Item that owns the console
key (tuple) – persistent process key in spine engine
language (str) – for syntax highlighting and prompting, etc.
- Returns
PersistentConsoleWidget
- _cleanup_jupyter_console(conn_file)[source]
Removes reference to a Jupyter Console and closes the kernel manager on Engine.
- _shutdown_engine_kernels()[source]
Shuts down all persistent and Jupyter kernels managed by Spine Engine.
spinetoolbox.version
Version info for Spine Toolbox package. Inspired by python sys.version and sys.version_info.
Module Contents
A class for a named tuple containing the five components of the version number: major, minor, |
- class spinetoolbox.version.VersionInfo[source]
Bases:
NamedTuple
A class for a named tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is ‘dev’, ‘alpha’, ‘beta’, ‘candidate’, or ‘final’.
- 1
Created with sphinx-autoapi