Welcome to Spine Toolbox’s User Guide!

_images/spinetoolbox_on_wht.svg

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/)

## [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:

  • Project provides a more concise view of your project, including the Items that are currently in the project, grouped by category: Data Stores, Data Connections, Tools, Views, Importers, Exporters and Manipulators.

  • 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 downward_triangle icon next to the Tool icon tool_icon, to reveal the Tool specification list. Since there are none in the project yet, click on the black_plus 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 file_regular 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:

_images/getting_started_tool_spec_editor.png

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.

_images/getting_started_first_tool_spec_created.png

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 (plus) 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 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, and also as an entry in the Project dock widget, under the ‘Tools’ category. It should look similar to this:

_images/getting_started_first_tool_created.png

Another way to do the same thing is to drag the tool_icon 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.

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:

_images/getting_started_tool_properties.png

Press execute project execute 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.

_images/getting_started_after_first_execution.png

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 by right clicking the ‘say hello world’ -item in the Project dock widget and selecting Specification… -> Edit specification, or from the Tool Properties by clicking the Tool specification options button (wrench) next to the specification and selecting Edit specification.

In Input & Output files dock widget, click the plus 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:

_images/getting_started_added_input_file.png

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 execute in the Toolbar. The execution will fail because the file input.txt is not made available for the Tool:

_images/getting_started_say_hello_world_failed.png

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 (dc_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, and also as an entry in the Project dock widgets items list, under the ‘Data Connections’ category.

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:

_images/getting_started_dc_properties.png

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:

_images/getting_started_dc_with_an_input_file.png

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:

_images/getting_started_dc_to_tool_connected.png

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

_images/getting_started_final_execution_successful.png

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

  1. 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.

  2. Start Spine Toolbox

  3. Create a new project (File -> New project…)

  4. Select File -> Settings from the main menu and open the Tools page.

  5. Set a path to a Julia executable to the appropriate line edit (e.g. C:/Julia-1.6.0/bin/julia.exe). Your selections should look similar to this now.

    _images/settings_tools_default.png
  6. [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).

  7. 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.

    _images/spineopt_install_wizard_successful.png

    Close the wizard.

  8. Click Ok to close the Settings window

  9. Back in the main window, select Plugins -> Install plugin… from the menu

  10. 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 straight. 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 (play) 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 play to execute it.

Note

The Python settings on the Tools page in File -> Settings are the default settings for new 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) 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 below the Julia executable line edit.

Note

The Julia settings are global application settings. All Julia Tools are executed with the settings selected on the Tools page in File -> Settings. In upcoming versions, the Julia settings will be consistent with the Python settings, in a way that you can select a specific Julia executable and Julia project for each Julia Tool Spec separately.

Jupyter Consoles

Jupyter Console appears to the Console dock widget in the main window when you execute (play) 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:/Python39/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.

_images/python_jupyter_console_selected.png

Once the ipykernel package is installed, the wizard runs the ipykernel install command, which creates the kernel specs directory on your system. You can quickly open the kernel spec directory from the Select Python Kernel… combo box’s context-menu (mouse right-click menu). Once the process finishes, click Close, and the newly created kernel spec (python39 in this case) should be selected automatically. Click Ok to close the Settings widget and to save your selections.

_images/python_kernel_specification_creator.png

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 python39 --display-name python39_spinetoolbox

Make sure to use the --user argument to make sure that the kernel specs are discoverable by Spine Toolbox.

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.

Important

If you want to have access to spinedb_api, you need to install it manually for the Python you select here.

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.

_images/julia_jupyter_console_selected.png

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.

_images/julia_kernel_specification_creator.png

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.

  1. Open Anaconda Prompt and make a new Conda environment:

    conda create -n test python=3.10
    
  2. Activate the environment:

    conda activate test
    
  3. Install ipykernel:

    pip install ipykernel
    
  4. 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.

_images/start_jupyter_console_menu_listing.png

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.

_images/executable_tool_spec_dir_runner.png

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.

_images/main_window_no_project.png

The application main window contains four dock widgets (Project, Properties, Event Log, Console), a Toolbar, a Design View, and a menu bar with File, Edit, View, Plugins, Consoles, Server and Help menus. The Project dock widget contains a list of project items in the project. 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 GAMS and executable programs. Also things like whether an item’s execution was successful and when the project or an item specification is saved are shown.

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 where you build your project. The play-all button executes all Directed Acyclic Graphs (DAG) in the project in a row. The play-selected button executes the selected project items only. The stop 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.

Below is an example on how you can customize the main window. In the picture, a user has created a project New Project and created one project item from each of the eight categories. A Data Connection called Data files, a Data Store called Database, a Data Transformer called Data Transformer, an Exporter called Exporter, an Importer called Importer, a Merger called Merger, a Tool called Julia model and a View called View. The project items are also listed in the Project dock widget. Some of the dock widgets have also been moved from their original places.

_images/main_window_new_project_with_project_items.png

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 execute or execute-selected 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 folder-open 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.

View

A View item is meant for plotting preselected parameter values from multiple sources.

Tool Specification Editor

This section describes how to make a new Tool specification and how to edit existing Tool specifications.

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.

_images/open_tool_specification_editor.png

When you press New… the following form pops up;

_images/edit_tool_specification_blank.png

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 file-regular button, or you can browse to find an existing main program file by pressing the folder_open 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 folder_open_solid 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

_images/minimal_tool_specification.png

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.

_images/toolbar_with_one_tool_specification.png

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 play-all or play-selected button.

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 Project button (play-all) to execute the whole project, or by pressing the Selection button (play-selected) to only execute selected items. Next to these buttons is the Stop button (stop), 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. A DAG is traversed using the breadth-first-search algorithm.

Rules of DAGs:

  1. A single project item with no connections is a DAG.

  2. 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.

  3. 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.

_images/example_dags.png
  • 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 play-all 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.

_images/dag_broken.png

You can also execute only the selected parts of a project by multi-selecting the items you want to execute and pressing the play-selected button in the tool bar. For example, to execute only items b, d and f, select the items in Design View or in the project item list in Project dock widget and then press the play-selected 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.

_images/execution_data_connection_selected.png

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.

_images/execution_julia_tool_selected.png

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 play-all 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

_images/settings_general.png

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.

_images/settings_tools_default.png

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 open-folder 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.

  • 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.

  • 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.

Note

These Julia settings are global application settings. All Julia Tools are executed with the settings selected here.

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.

  • 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.

Note

These Python settings are just the default settings for new Python Tool Specs. You can select a specific Python kernel for each Python Tool Spec separately using the Tool Specification Editor.

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

_images/settings_db_editor.png

This tab contains settings for the Spine Database editor. The same settings can be accessed directly from the Database editor itself.

  • 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.

  • Sticky selection in entity trees Controls how selecting items in Spine database editor’s Object and Relationships trees 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.

  • Move relationships along with objects in Entity graph This controls how relationship nodes behave on the Graph view when object nodes are moved around. If checked, connected relationship nodes move along with the object node. If unchecked, connected relationship nodes remain where they are when objects nodes are moved.

  • Smooth Entity graph zoom Checking this enables smooth zoom on the Graph view.

  • Smooth Entity graph rotation Checking this enables smooth rotation on the Graph view.

  • Auto-expand objects by default in Entity graph This checkbox controls which relationship nodes to show on the Graph view. If checked, all relationships that contain a visible object node are included. If unchecked, relationship nodes are included only if all their objects are show on the Graph view.

  • Merge databases by default in Entity graph If checked, Graph view will combine all databases that are open on the same table into a single graph if they contains common object nodes. If unchecked, a separate graph will be drawn for each database.

Spec. editor Settings

_images/settings_specification_editors.png

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

_images/settings_engine.png

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.

Spine data structure

Main features

Spine data structure follows entity-attribute-value (EAV) with classes and relationships data model (Wikipedia). It is an open schema where the data structure is defined through data (and not through database structure). Spine Toolbox also adds an ability to hold alternative parameter values for the same parameter of a particular entity. This allows the creation of scenarios. A potential weakness of EAV is that each parameter value needs a separate row in the database which could make the parameter table large and slow. In Spine Toolbox this is circumvented by allowing different datatypes like time series and maps to be represented in the parameter field and thus greatly reducing the number of rows required to present large systems.

Definitions
  1. Entity: an object (one dimension) or a relationship (n-dimensions)

  2. Attribute: parameter name

  3. Value: parameter value

  4. Entity class: a category for entities (e.g. ‘unit’ is an object class while ‘coal_power_plant’ is an entity of ‘unit’ class)

  5. Alternative: Each parameter value belongs to one alternative

  6. Scenario: Combines alternatives into a single scenario

Getting started

Launching the editor

From Spine Toolbox

To open a single database in Spine database editor:

  1. Create a Data Store project item.

  2. Select the Data Store.

  3. Enter the url of the database in Data Store Properties.

  4. Press the Open editor… button in Data Store Properties or double-click the Data Store project item.

To open multiple SQLite databases in Spine database editor:

  1. Open a database in Database editor as explained above.

  2. Select Add… from the ☰ menu.

  3. Open the SQLite file.

From the command line

To open a single database in Spine database editor, use the spine-db-editor application which comes with Spine Toolbox:

spine-db-editor "...url of the database..."

Note that for e.g. an SQLite database, the url should start with ‘sqlite:’.

Knowing the UI

The form has the following main UI components:

  • Entity trees (Object tree and Relationship tree): they present the structure of classes and entities in all databases in the shape of a tree.

  • Stacked tables (Object parameter value, Object parameter definition, Relationship parameter value, and Relationship parameter definition): they present object and relationship parameter 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.

  • Entity graph: it presents the structure of classes and entities in the shape of a graph.

  • Tool/Feature tree: it presents tools, features, and methods defined in the databases.

  • Parameter value list: it presents parameter value lists available in the databases.

  • Alternative tree: it presents alternatives defined in the databases.

  • Scenario tree: it presents scenarios defined in the databases.

  • 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 and Pivot sections in the hamburger ☰ menu.

Viewing data

This section describes the available tools to view data.

Viewing entities and classes

Using Entity trees

Entity trees present the structure of classes and entities in all databases in the shape of a tree:

_images/object_tree.png

In Object tree:

  • To view all object classes from all databases, expand the root item (automatically expanded when loading the form).

  • To view all objects of a class, expand the corresponding object class item.

  • To view all relationship classes involving an object class, expand any objects of that class.

  • To view all relationships of a class involving a given object, expand the corresponding relationship class item under the corresponding object item.

In Relationship tree:

  • To view all relationship classes from all databases, expand the root item (automatically expanded when loading the form).

  • To view all relationships of a class, expand the corresponding relationship class item.

Note

To expand an item in Object tree or Relationship tree, double-click on the item or press the right arrow while it’s active. 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 while it’s active.

Tip

To expand or collapse an item and all its descendants in Object tree or Relationship tree, right click on the item to display the context menu, and select Fully expand or Fully collapse.

Tip

In Object tree, the same relationship appears in many places (as many as it has dimensions). To jump to the next occurrence of a relationship item, either double-click on the item, or right-click on it to display the context menu, and select Find next.

Using Entity graph

Entity graph presents the structure of classes and entities from one database in the shape of a graph:

_images/entity_graph.png

Tip

To see it in action, check out this video.

Building the graph

To build the graph, select any number of items in either Object tree or Relationship tree. What is included in the graph depends on the specific selection you make:

  • To include all objects and relationships from the database, select the root item in either Object tree or Relationship tree.

  • To include all objects of a class, select the corresponding class item in Object tree.

  • To include all relationships of a class, select the corresponding class item in Relationship tree.

  • To include all relationships of a specific class involving a specific object, select the corresponding relationship class item under the corresponding object item in Object tree.

  • To include specific objects or relationships, select the corresponding item in either Object tree or Relationship tree.

Note

In Entity graph, a small unnamed vertex represents a relationship, whereas a bigger named vertex represents an object. An arc between a relationship and an object indicates that the object is a member in that relationship.

The graph automatically includes relationships whenever all the member objects are included (even if these relationships are not selected in Object tree or Relationship tree). You can change this behavior to automatically include relationships whenever any of the member objects are included. To do this, enable Auto-expand objects via the Graph menu, or via Entity graph’s context menu.

Tip

To extend the selection in Object tree or Relationship tree, press and hold the Ctrl key while clicking on the items.

Tip

Object tree and Relationship tree also support 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.

Manipulating the graph

You can move items in the graph by dragging them with your mouse. By default, each items moves individually. To make relationship items move along with their member objects, select Settings from the hamburger menu and check the box next to Move relationships along with objects in Entity graph.

To display Entity graph’s context menu, just right-click on an empty space in the graph.

  • To save the position of items into the database, select the items in the graph and choose Save positions from the context menu. To clear saved positions, select the items again and choose Clear saved positions from the context menu.

  • To hide part of the graph, select the items you want to hide and choose Hide from context menu. To show the hidden items again, select Show hidden from the context menu.

  • To prune the graph, select the items you want to prune and then choose Prune entities or Prune classes from the context menu. To restore specific pruned items, display the context menu, hover Restore and select the items you want to restore from the popup menu. To restore all pruned items at once, select Restore all from the context menu.

  • To zoom in and out, scroll your mouse wheel over Entity graph or use Zoom buttons in the context menu.

  • To rotate clockwise or anti-clockwise, press and hold the Shift key while scrolling your mouse wheel, or use the Rotate buttons in the context menu.

  • To adjust the arcs’ length, use the Arc length buttons in the context menu.

  • To rebuild the graph after moving items around, select Rebuild graph from the context menu.

  • To export the current graph as a PDF file, select Export graph as PDF from the context menu.

Note

Entity graph 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, press and hold Ctrl while dragging your mouse around the items you want to select.

Note

Pruned items are remembered across graph builds.

To display an object or relationship item’s context menu, just right-click on it.

  • To expand or collapse relationships for an object item, hover Expand or Collapse and select the relationship class from the popup menu.

Viewing parameter definitions and values

Using Stacked tables

Stacked tables present object and relationship parameter data from all databases in the form of stacked tables:

_images/object_parameter_value_table.png

To filter Stacked tables by any entities and/or classes, select the corresponding items in either Object tree, Relationship tree, or Entity graph. To remove all these filters, select the root item in either Object tree or Relationship tree.

Stacked tables can also be filtered by selecting alternatives or scenarios from Alternative tree and Scenario tree. This filter is orthogonal to the entity/class filter and can be used together with it. To remove all these filters, select the root items or deselect all items from Alternative tree and Scenario tree.

All the filters described above can be cleared with the Clear all filters item available in the Stacked tables right-click context menu.

To apply a custom filter on a Stacked table, click on any horizontal header. A menu will pop up listing the items in the corresponding column:

_images/object_name_filter_menu.png

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 Stacked table 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 Stacked tables by dragging the headers with your mouse. The ordering will be remembered the next time you open Spine DB editor.

Viewing parameter values and relationships

Using Pivot table and Frozen table

Pivot table and Frozen table present data for an individual class from one database in the form of a pivot table, optionally with frozen dimensions:

_images/pivot_table.png

To populate the tables with data for a certain class, just select the corresponding class item in either Object tree or Relationship tree.

Selecting the input type

Pivot table and Frozen table support four different input types:

  • Parameter value (the default): it shows objects, parameter definitions, alternatives, and databases in the headers, and corresponding parameter values in the table body.

  • Index expansion: Similar to the above, but it also shows parameter indexes in the headers. Indexes are extracted from special parameter values, such as time-series.

  • Relationship: it shows objects, and databases in the headers, and corresponding relationships in the table body. It only works when selecting a relationship class in Relationship 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 table, header blocks in the top-left area indicate what is shown in each horizontal and vertical header. For example, in Parameter 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 object 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 table 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.

Filtering

To apply a custom filter on Pivot table, 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:

_images/object_name_filter_menu.png

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 table 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 tree:

_images/alternative_tree.png

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:

_images/scenario_tree.png

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 tools and features

You can find tools, features, and methods from all databases under Tool/Feature tree:

_images/tool_feature_tree.png

To view the features and tools from each database, expand the root item for that database. To view all features, expand the feature item. To view all tools, expand the tool item. To view the features for a particular tool, expand the tool_feature item under the corresponding tool item. To view the methods for a particular tool-feature, expand the tool_feature_method item under the corresponding tool-feature item.

Viewing parameter value lists

You can find parameter value lists from all databases under Parameter value list:

_images/parameter_value_list.png

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:

_images/metadata.png

See also Spine Metadata Description.

Viewing item metadata

You can find metadata for currently selected entities or parameter values under Item metadata:

_images/item_metadata.png

Adding data

This section describes the available tools to add new data.

Adding object classes

From Object tree

Right-click on the root item in Object tree to display the context menu, and select Add object classes.

The Add object classes dialog will pop up:

_images/add_object_classes_dialog.png

Enter the names of the classes you want to add under the object class name column. Optionally, you can enter a description for each class under the description column. To select icons for your classes, double click on the corresponding cell under the display icon column. Finally, select the databases where you want to add the classes under databases. When you’re ready, press Ok.

Adding objects

From Object tree or Entity graph

Right-click on an object class item in Object tree, or on an empty space in the Entity graph, and select Add objects from the context menu.

The Add objects dialog will pop up:

_images/add_objects_dialog.png

Enter the names of the object classes under object class name, and the names of the objects under object name. To display a list of available classes, start typing or double click on any cell under the object class name column. Optionally, you can enter a description for each object under the description column. Finally, select the databases where you want to add the objects under databases. When you’re ready, press Ok.

From Pivot table

To add an object to a specific class, bring the class to Pivot table using any input type (see Using Pivot table and Frozen table). Then, enter the object name in the last cell of the header corresponding to that class.

Duplicating objects

To duplicate an existing object with all its relationships and parameter values, right-click over the corresponding object item in Object tree to display the context menu, and select Duplicate object. Enter a name for the duplicate and press Ok.

Adding object groups

Right-click on an object class item in Object tree, and select Add object group from the context menu.

The Add object group dialog will pop up:

_images/add_object_group_dialog.png

Enter the name of the group, and select the database where you want the group to be created. Select the member objects under Non members, and press the button in the middle that has a plus sign. Multiple selection works.

When you’re happy with your selections, press Ok to add the group to the database.

Adding relationship classes

From Object tree or Relationship tree

Right-click on an object class item in Object tree, or on the root item in Relationship tree, and select Add relationship classes from the context menu.

The Add relationship classes dialog will pop up:

_images/add_relationship_classes_dialog.png

Select the number of dimensions using the spinbox at the top; then, enter the names of the object classes for each dimension under each object class name column, and the names of the relationship classes under relationship class name. To display a list of available object classes, start typing or double click on any cell under the object class name columns. Optionally, you can enter a description for each relationship class under the description column. Finally, select the databases where you want to add the relationship classes under databases. When you’re ready, press Ok.

Adding relationships

From Object tree or Relationship tree

Right-click on a relationship class item either in Object tree or Relationship tree, and select Add relationships from the context menu.

The Add relationships dialog will pop up:

_images/add_relationships_dialog.png

Select the relationship class from the combo box at the top; then, enter the names of the objects for each member object class under the corresponding column, and the name of the relationship under relationship name. To display a list of available objects for a member class, start typing or double click on any cell under that class’s column. Finally, select the databases where you want to add the relationships under databases. When you’re ready, press Ok.

From Pivot table

To add a relationship for a specific class, bring the class to Pivot table using the Relationship input type (see Using Pivot table and Frozen table). The Pivot table headers will be populated with all possible combinations of objects across the member classes. Locate the objects you want as members in the new relationship, and check the corresponding box in the table body.

From Entity graph

Make sure all the objects you want as members in the new relationship are in the graph. To start the relationship, either double click on one of the object items, or right click on it to display the context menu, and choose Add relationships. A menu will pop up showing the available relationship classes. Select the class you want; the mouse cursor will adopt a cross-hairs shape. Click on each of the remaining member objects, one by one and in the right order, to add them to the relationship. Once you’ve added enough objects for the relationship class, a dialog will pop up. Check the boxes next to the relationships you want to add, and press Ok.

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 parameter definitions

From Stacked tables

To add new parameter definitions for an object class, just fill the last empty row of Object parameter definition. Enter the name of the class under object_class_name, and the name of the parameter under parameter_name. To display a list of available object classes, start typing or double click under the object_class_name column. Optionally, you can also specify a default value, a parameter value list, or any number of parameter tags under the appropriate columns. The parameter is added when the background of the cells under object_class_name and parameter_name become gray.

To add new parameter definitions for a relationship class, just fill the last empty row of Relationship parameter definition, following the same guidelines as above.

From Pivot table

To add a new parameter definition for a class, bring the corresponding class to Pivot table using the Parameter value input type (see Using Pivot table and Frozen table). The parameter header of Pivot table 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 Stacked tables

To add new parameter values for an object, just fill the last empty row of Object parameter value. Enter the name of the class under object_class_name, the name of the object under object_name, 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. To display a list of available object classes, objects, 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 object_class_name, object_name, and parameter_name become gray.

To add new parameter values for a relationship class, just fill the last empty row of Relationship parameter value, following the same guidelines as above.

Note

To add parameter values for an object, the object has to exist beforehand. However, when adding parameter values for a relationship, you can specify any valid combination of objects under object_name_list, and a relationship will be created among those objects if one doesn’t yet exist.

From Pivot table

To add parameter value for any object or relationship, bring the corresponding class to Pivot table using the Parameter value input type (see Using Pivot table and Frozen table). Then, enter the parameter value in the corresponding cell in the table body.

Tip

All Stacked tables and Pivot table support pasting tabular (e.g., spreadsheet) data from the clipboard. Just select any cell in the table and press Ctrl+V. If needed, Stacked tables 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 tools, features, and methods

To add a new feature, go to Tool/Feature tree and select the last item under feature in the appropriate database, start typing or press F2 to display available parameter definitions, and select the one you want to become a feature.

Note

Only parameter definitions that have associated a parameter value list can become features.

To add a new tool, just select the last item under tool in the appropriate database, and enter the name of the tool.

To add a feature for a particular tool, drag the feature item and drop it over the tool_feature list under the corresponding tool.

To add a new method for a tool-feature, select the last item under tool_feature_method (in the appropriate database), start typing or press F2 to display available methods, and select the one you want to add.

Adding alternatives

From Alternative tree

To add a new alternative, just select the last item appropriate database, and enter the name of the alternative.

You can also copy and paste alternatives between different databases.

From Pivot table

Select the Scenario input type (see Using Pivot table 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 tree 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 tree and pasted at the appropriate position in Scenario tree.

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.

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, or by pressing Ctrl+D. It is also possible to copy and paste scenarios between databases.

From Pivot table

Select the Scenario input type (see Using Pivot table 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 tree (using Ctrl and Shift while clicking the items), then right click to open a context menu. Select Generate scenarios…

_images/generate_scenarios.png

Give the scenario names a prefix. An index will be appended to the prefix automatically: prefix01, prefix02,… Select appropriate operation from the 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, 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 Open editor from the context menu.

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 Object tree, Relationship tree, or Entity graph

Select any number of entity and/or class items in Object tree or Relationship tree, or any number of object and/or relationship items in Entity graph. Then, right-click on the selection and choose Edit… from the context menu.

One separate Edit… dialog will pop up for each selected entity or class type, and the tables will be filled with the current data of selected items. E.g.:

_images/edit_object_classes_dialog.png

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 table

To rename an object of a specific class, bring the class to Pivot table using any input type (see Using Pivot table and Frozen table). Then, just edit the appropriate cell in the corresponding class header.

Updating parameter definitions and values

From Stacked tables

To update parameter data, just go to the appropriate Stacked table and edit the corresponding row.

From Pivot table

To rename parameter definitions for a class, bring the corresponding class to Pivot table using the Parameter value input type (see Using Pivot table and Frozen table). Then, just edit the appropriate cell in the parameter header.

To modify parameter values for an object or relationship, bring the corresponding class to Pivot table using the Parameter value input type (see Using Pivot table and Frozen table). Then, just edit the appropriate cell in the table body.

Updating alternatives

From Pivot table

Select the Scenario input type (see Using Pivot table and Frozen table). To rename an alternative, just edit the proper cell in the alternative header.

From Alternative tree

To rename an alternative, just edit the appropriate item in Alternative tree.

Updating scenarios

From Pivot table

Select the Scenario input type (see Using Pivot table 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 tools and features

To change a feature or method, or rename a tool, just edit the appropriate item in Tool/Feature tree.

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.

Removing entities and classes

From Object tree, Relationship tree, or Entity graph

Select the items in Object tree, Relationship tree, or Entity graph, 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:

_images/remove_entities_dialog.png

Specify the databases from where you want to remove each item under the databases column, and press Ok.

From Pivot table

To remove objects or relationships from a specific class, bring the class to Pivot table using the Parameter value input type (see Using Pivot table and Frozen table), and select the cells in the table headers corresponding to the objects and/or relationships you want to remove. Then, right-click on the selection and choose the corresponding Remove option from the context menu.

Alternatively, to remove relationships for a specific class, bring the class to Pivot table using the Relationship input type (see Using Pivot table and Frozen table). The Pivot table headers will be populated with all possible combinations of objects across the member classes. Locate the member objects of the relationship you want to remove, and uncheck the corresponding box in the table body.

Removing parameter definitions and values

From Stacked tables

To remove parameter definitions or values, go to the relevant Stacked table and select any cell in the row corresponding to the items you want to remove.s Then, right-click on the selection and choose the appropriate Remove option from the context menu.

From Pivot table

To remove parameter definitions and/or values for a certain class, bring the corresponding class to Pivot table using the Parameter value input type (see Using Pivot table and Frozen table). Then:

  1. 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

  2. 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.

Purging items

To remove all items of specific types, select Edit -> Purge from the hamburger menu. The Purge items dialog will pop up:

_images/mass_remove_items_dialog.png

Select the databases from where you want to remove the items under Databases, and the type of items you want to remove under Items. Then, press Ok.

Removing alternatives

From Pivot table

Select the Scenario input type (see Using Pivot table and Frozen table). To remove alternatives, just edit the proper cells in the alternative header, right-click on the selection and choose Remove from the context menu.

From Alternative tree

To remove an alternative, just select the corresponding items in Alternative tree, right-click on the selection and choose Remove from the context menu.

Removing scenarios

From Pivot table

Select the Scenario input type (see Using Pivot table and Frozen table). To remove scenarios, just select the proper cells in the scenario header, right-click on the selection and choose Remove 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, select the corresponding alternative items in Scenario tree, right-click on the selection and choose Remove from the context menu.

Removing tools and features

To remove a feature, tool, or method, just select the corresponding items in Tool/Feature 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 object groups

To modify object groups, expand the corresponding item in Object tree to display the members item, right-click on the latter and select Manage members from the context menu. The Manage parameter tags dialog will pop up:

_images/manage_members_dialog.png

To add new member objects, select them under Non members, and press the button in the middle that has a plus sign. To remove current member objects, select them under Members, and press the button in the middle that has a minus sign. Multiple selection works in both lists.

When you’re happy, press Ok.

Note

Changes made using the Manage members dialog are not applied to the database until you press Ok.

Managing relationships

Select Edit -> Manage relationships from the menu bar. The Manage relationships dialog will pop up:

_images/manage_relationships_dialog.png

To get started, select a relationship class and a database from the combo boxes at the top.

To add relationships, select the member objects for each class under Available objects and press the Add relationships button at the middle of the form. The relationships will appear at the top of the table under Existing relationships.

To add multiple relationships at the same time, select multiple objects for one or more of the classes.

Tip

To extend the selection of objects for a class, press and hold the Ctrl key while clicking on more items.

Note

The set of relationships to add is determined by applying the product operation over the objects selected for each class.

To remove relationships, select the appropriate rows under Existing relationships and press the Remove relationships button on the right.

When you’re happy with your changes, press Ok.

Note

Changes made using the Manage relationships 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 below.

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

The Excel format consists of one sheet per object and relationship class. Each sheet can have one of four different formats:

  1. Object class with scalar parameter data:

_images/excel_object_sheet.png
  1. Object class with indexed parameter data:

    _images/excel_object_sheet_timeseries.png
  2. Relationship class with scalar parameter data:

    _images/excel_relationship_sheet.png
  3. Relationship class with indexed parameter data:

    _images/excel_relationship_sheet_timeseries.png
JSON format

The JSON format consists of a single JSON object with the following OPTIONAL keys:

  • object_classes: the value of this key MUST be a JSON array, representing a list of object classes. Each element in this array MUST be itself a JSON array and MUST have three elements:

    • The first element MUST be a JSON string, indicating the object class name.

    • The second element MUST be either a JSON string, indicating the object class description, or null.

    • The third element MUST be either a JSON integer, indicating the object class icon code, or null.

  • relationship_classes: the value of this key MUST be a JSON array, representing a list of relationships classes. Each element in this array MUST be itself a JSON array and MUST have three elements:

    • The first element MUST be a JSON string, indicating the relationship class name.

    • The second element MUST be a JSON array, indicating the member object classes. Each element in this array MUST be a JSON string, indicating the object class name.

    • The third element MUST be either a JSON string, indicating the relationship class description, or null.

  • parameter_value_lists: the value of this key MUST be a JSON array, representing a list of parameter value lists. Each element in this array MUST be itself a JSON array and MUST have two elements:

    • The first element MUST be a JSON string, indicating the parameter value list name.

    • The second element MUST be a JSON array, indicating the values in the list. Each element in this array MUST be either a JSON object, string, number, or null, indicating the value.

  • object_parameters: the value of this key MUST be a JSON array, representing a list of object parameter definitions. Each element in this array MUST be itself a JSON array and MUST have five elements:

    • The first element MUST be a JSON string, indicating the object 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 last element MUST be either a JSON string, indicating the parameter description, or null.

  • relationship_parameters: the value of this key MUST be a JSON array, representing a list of relationship parameter definitions. Each element in this array MUST be itself a JSON array and MUST have five elements:

    • The first element MUST be a JSON string, indicating the relationship 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 last element MUST be either a JSON string, indicating the parameter description, or null.

  • objects: the value of this key MUST be a JSON array, representing a list of objects. Each element in this array MUST be itself a JSON array and MUST have three elements:

    • The first element MUST be a JSON string, indicating the object class name.

    • The second element MUST be a JSON string, indicating the object name.

    • The third element MUST be either a JSON string, indicating the object description, or null.

  • relationships: the value of this key MUST be a JSON array, representing a list of relationships. Each element in this array MUST be itself a JSON array and MUST have two elements:

    • The first element MUST be a JSON string, indicating the relationship class name.

    • The second element MUST be a JSON array, indicating the member objects. Each element in this array MUST be a JSON string, indicating the object name.

  • object_parameter_values: the value of this key MUST be a JSON array, representing a list of object parameter values. Each element in this array MUST be itself a JSON array and MUST have four elements:

    • The first element MUST be a JSON string, indicating the object class name.

    • The second element MUST be a JSON string, indicating the object 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.

  • relationship_parameter_values: the value of this key MUST be a JSON array, representing a list of relationship parameter values. Each element in this array MUST be itself a JSON array and MUST have four elements:

    • The first element MUST be a JSON string, indicating the relationship class name.

    • The second element MUST be a JSON array, indicating the relationship’s member objects. Each element in this array MUST be a JSON string, indicating the object 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.

Example:

{
    "object_classes": [
        ["connection", "An entity where an energy transfer takes place", 280378317271233],
        ["node", "An entity where an energy balance takes place", 280740554077951],
        ["unit", "An entity where an energy conversion process takes place", 281470681805429],
    ],
    "relationship_classes": [
        ["connection__node__node", ["connection", "node", "node"] , null],
        ["unit__from_node", ["unit", "node"], null],
        ["unit__to_node", ["unit", "node"], null],
    ],
    "parameter_value_lists": [
        ["balance_type_list", ["\"balance_type_node\"", "\"balance_type_group\"", "\"balance_type_none\""]],
        ["truth_value_list", ["\"value_false\"", "\"value_true\""]],
    ],
    "object_parameters": [
        ["connection", "connection_availability_factor", 1.0, null, null],
        ["node", "balance_type", "balance_type_node", "balance_type_list", null],
    ],
    "relationship_parameters": [
        ["connection__node__node", "connection_flow_delay", {"type": "duration", "data": "0h"}, null, null],
        ["unit__from_node", "unit_capacity", null, null, null],
        ["unit__to_node", "unit_capacity", null, null, null],
    ],
    "objects": [
        ["connection", "Bastusel_to_Grytfors_disch", null],
        ["node", "Bastusel_lower", null],
        ["node", "Bastusel_upper", null],
        ["node", "Grytfors_upper", null],
        ["unit", "Bastusel_pwr_plant", null],
    ],
    "relationships": [
        ["connection__node__node", ["Bastusel_to_Grytfors_disch", "Grytfors_upper", "Bastusel_lower"]],
        ["unit__from_node", ["Bastusel_pwr_plant", "Bastusel_upper"]],
        ["unit__to_node", ["Bastusel_pwr_plant", "Bastusel_lower"]],
    ],
    "object_parameter_values": [
        ["node", "Bastusel_upper", "demand", -0.2579768519],
        ["node", "Bastusel_upper", "fix_node_state", {"type": "time_series", "data": {"2018-12-31T23:00:00": 5581.44, "2019-01-07T23:00:00": 5417.28}}],
        ["node", "Bastusel_upper", "has_state", "value_true"],
    ],
    "relationship_parameter_values": [
        ["connection__node__node", ["Bastusel_to_Grytfors_disch", "Grytfors_upper", "Bastusel_lower"], "connection_flow_delay", {"type": "duration", "data": "1h"}],
        ["unit__from_node", ["Bastusel_pwr_plant", "Bastusel_upper"], "unit_capacity", 127.5],
    ]
}

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:

_images/mass_export_items_dialog.png

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 either Object tree and Relationship 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. To open the file in your registered program, press that button. To open the containing folder, click on the arrow next to the file name and select Open containing folder from the popup menu.

Committing and rolling back

Note

Changes are not immediately saved to the database(s). They need to be committed separately.

To commit your changes, select Session -> Commit from the hamburger menu, enter a commit message and press Commit. Any changes made in the current session will be saved into the database.

To undo all changes since the last commit, select Session -> Rollback from the hamburger menu.

Tip

To undo/redo individual changes, use the Edit -> Undo and Edit -> Redo actions from the hamburger menu.

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.

_images/plotting_popup_menu.png _images/plotting_window_single_column.png

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.

_images/plotting_popup_menu_plot_in_window.png _images/plotting_window_added_plot.png

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.

_images/right_click_options.png _images/plot_data.png

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.

_images/plotting_use_as_x_popup.png

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 object and relationship 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.

_images/value_editor_parameter_type.png

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.

_images/value_editor_plain.png

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.

_images/value_editor_map.png

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.

_images/value_editor_map_before_conversion.png

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

_images/value_editor_map_after_conversion.png

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.

_images/value_editor_time_series_fixed.png _images/value_editor_time_series_variable.png

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.

_images/value_editor_time_pattern.png

Time periods consist of the following elements:

  • An interval of time in a given time-unit. The format is Ua-b, where U is either Y (for year), M (for month), D (for day), WD (for weekday), h (for hour), m (for minute), or s (for second); and a and b are two integers corresponding to the lower and upper bound, respectively.

  • An intersection of intervals. The format is s1;s2;..., where s1, s2, …, are intervals as described above.

  • A union of ranges. The format is r1,r2,..., where r1, 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.

_images/value_editor_array.png

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.

_images/value_editor_datetime.png

Durations

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

_images/value_editor_duration.png

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 a path 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 include path, email, role and organization. Example:

"contributors": [{
  "title": "Joe Bloggs",
  "email": "joe@bloggs.com",
  "path": "http://www.bloggs.com",
  "role": "author"
}]

Role is one of author, publisher, maintainer, wrangler, or contributor.

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 a path property and may contain title. 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 wrench button in Importer’s Properties dock where existing specifications can also be selected or by double-clicking the item on the Design View.

_images/importer_properties.png

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

_images/importer_connector_type.png

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

The left side of the Importer Specification Editor contains four dock widgets that deal with the input source data. Source files contains the filepath to the current input file. Source tables contains the different tables the file has or that user has set up. Source options has a few options on how to handle the incoming data. The available options depend on the connector type. Source data allows for previewing of the data selected in Source files and also of the currently selected mapping.

The right side of the spec editor shows import mappings for the table selected in Source tables. Mappings lets you add, duplicate and remove mappings or select a mapping to modify its options. Mapping options allow you to specify things like what item type you are importing. In Mapping specification you can select the specific places in the source data where the object names, values etc. will be taken from.

_images/import_editor_window.png

All tables available in the file selected in Source files are listed in Source tables. 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.

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.

Source options contains options 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.

Source data shows the selected table’s data and a preview of how the selected mapping will import the data. 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.

_images/import_editor_column_data_type_menu.png

Under Mappings you can manage mappings by adding new ones and removing or duplicating existing ones. 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 relationship classes and object classes at the same time from a single table in a file.

Mapping options helps the importer get a feel for what kind of data it will be importing. The available item type options are Object class, Relationship class, Object group, Alternative, Scenario, Scenario alternative, Parameter value list, Feature, Tool, Tool feature and Tool feature method. The other available options are dependent on the Item type. Import objects allows to import objects alongside relationships or object 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 relationship 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.

Once everything in Mapping options is in order, the next step is to set the mapping specification. Mapping specification 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 Mapping specification 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.

_images/import_editor_preview_table_mapping_menu.png

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.

_images/importer_spec_editor_anonymous_mode.png

In anonymous mode new tables can be created in Source tables by double clicking <rename this to add table> and writing in a name for the new table. The Source data will contain 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 Source files dock.

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 wrench 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.

_images/exporter_properties.png

Specification used by the active Exporter item can be selected from the Specification combobox. The wrench 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 open-folder 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.

_images/exporter_specification_editor.png

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.

_images/exporter_mappings_dock.png

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.

_images/exporter_preview_docks.png

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 Object class, Relationship class, Relationship class with object parameter, Object group, Alternative, Scenario, Scenario alternative, Parameter value list, Feature, Tool, Tool feature and Tool feature method. The rest of the options besides Group function are item type specific and may not be available for all selections.

_images/exporter_mapping_options_dock.png

Checking the Always export header checkbox outputs a table that has fixed headers even if the table is otherwise empty. If Item type is Relationship class, the Relationship dimensions spinbox can be used to specify the maximum number of relationships’ dimensions that the mapping is able to handle. Selected dimensions option is only available for the Relationship class with object parameter item type and it is used to specify the relationship dimension where the object 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
_images/exporter_mapping_specification_dock.png

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: object class names, object 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 object classes as table names will generate one new table for every object class in the database, each named after the class. Each table in turn will contain the parameters and objects of the table’s object 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 object class is its objects; setting the object class to column header will write the name of the class as the objects’ 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 object classes and objects, only classes that have objects get written to output. However, sometimes it is useful to export ‘empty’ object 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 Objects would produce an output table with all object classes including ones without objects. The position where objects 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.

_images/select_url_for_remote_db_export.png

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 object 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 object 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. Interpreter setting in app settings (Tools page in File->Settings) is ignored. Basic Console runs the Julia that is found in PATH. See installation instructions below.

  • Julia Jupyter Console. Kernel spec setting in app settings (Tools page in File->Settings) 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

  1. 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

  2. Install IPython kernel spec (python3) to enable Jupyter Console execution of Python Tools

    • Run:

      python -m pip install ipykernel
      
  3. Install Julia 1.8

  4. 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

  5. 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)

  1. (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.

  2. Start Spine Toolbox and open a project

  3. 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

  4. Click play-all to execute the project

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 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

  • GdxExporter is a project item that allows exporting a Spine data structure from a Data Store into a .gdx file which can be used as an input file in a Tool.

  • 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.

  • 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.

  1. 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.

  2. 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.

  3. 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.

  4. 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:

  1. What version of the Python interpreter are you using? E.g. Python 2.7.3, Python 3.6?

  2. 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.

  3. 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.

  4. 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

  1. Click ‘Fork’ on Github, creating e.g. yourname/Spine-Toolbox

  2. Clone your project: git clone git@github.com:yourname/Spine-Toolbox

  3. cd Spine-Toolbox

  4. Create a virtual environment and install requirements

  5. Create a branch: git checkout -b foo-the-bars master

Making your Changes

  1. Add an entry to CHANGELOG.md.

  2. Write tests expecting the correct/fixed functionality; make sure they fail.

  3. Hack, hack, hack.

  4. Run tests again, making sure they pass.

  5. Commit your changes: git commit -m "Foo the bars"

Creating Pull Requests

  1. Push your commit to get it back up to your fork: git push origin HEAD

  2. Visit Github, click handy ‘Pull request‘ button that it will make upon noticing your new branch.

  3. 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).

  4. 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

1

n/a

File URLs

Data Store

2

Database URL

Database URL

Data Transformer

3

n/a

Database URL

Exporter

n/a

File URLs

Importer

n/a

n/a

Merger

n/a

n/a

Tool

4

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

5

File URLs

Database URL

Merger

Database URL

Database URL

Tool

6

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

  1. Check out the spine-conductor repo, and install it, either in a virtual environment or using pipx.

  2. 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"
    
  3. 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 corresponding pyproject.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.

  4. 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;
    }
    
  5. 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).

  1. 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 and spinedb-api are equivalent, the regex should accomodate that.

  2. 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.

  3. 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"
    
  4. 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:

  1. 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 be 0.6.19 and a minor release would be 0.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.

  2. 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 the Spine-Toolbox repo if you were to do a minor release, i.e. 0.6.180.7.0, the following change would be sufficient:

    Example edit to pyproject.toml for Spine-Toolbox
    diff --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]
    
  3. 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"
    
  4. Create a Git tag on the latest commit:

    git tag 0.7.0 HEAD
    
  5. Push the tags to GitHub. On sh-like shells like: bash, zsh, or git-bash (Windows):

    Recipe to push Git tags to GitHub on sh-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;
    }
    
  6. 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.

  7. 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. The build backend ensures build isolation, and reproducibility of the wheels given a source distribution.

    Build distribution archives and wheels
    python -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.

Module Contents
Classes

ArrayModel

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

array()[source]

Returns the array modeled by this model.

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

columnCount(parent=QModelIndex())[source]

Returns 2.

_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

data(index, role=Qt.ItemDataRole.DisplayRole)[source]

Returns model’s data for given role.

flags(index)[source]

Returns table cell’s flags.

headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]

Returns header data.

insertRows(row, count, parent=QModelIndex())[source]

Inserts rows to the array.

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

removeRows(row, count, parent=QModelIndex())[source]

Removes rows from the array.

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.

set_array_type(new_type)[source]

Changes the data type of array’s elements.

Parameters

new_type (Type) – new element type

setHeaderData(section, orientation, value, role=Qt.ItemDataRole.EditRole)[source]
setData(index, value, role=Qt.ItemDataRole.EditRole)[source]

Sets the value at given index.

spinetoolbox.mvcmodels.compound_table_model

Models that vertically concatenate two or more table models.

Module Contents
Classes

CompoundTableModel

A model that concatenates several sub table models vertically.

CompoundWithEmptyTableModel

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

refreshed[source]
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

item_at_row(row)[source]

Returns the item at given row.

Parameters

row (int) –

Returns

object

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

refresh()[source]

Refreshes the layout by computing a new row map.

_do_refresh()[source]

Recomputes the row and inverse row maps.

_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.

fetchMore(parent)[source]

Fetches the next sub model and increments the fetched counter.

flags(index)[source]

Return index flags.

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.

rowCount(parent=QModelIndex())[source]

Returns the sum of rows in all models.

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.

insertRows(row, count, parent=QModelIndex())[source]

Inserts count rows after the given row under the given parent. Localizes the appropriate submodel and calls insertRows on it.

removeRows(row, count, parent=QModelIndex())[source]

Removes count rows starting with the given row under parent. Localizes the appropriate submodels and calls removeRows on it.

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

property single_models[source]
property empty_model[source]
abstract _create_empty_model()[source]

Creates and returns an empty model.

Returns

model

Return type

EmptyRowModel

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.

_handle_empty_rows_inserted(parent, empty_first, empty_last)[source]

Runs when rows are inserted to the empty model. Updates row_map, then emits rowsInserted so the new rows become visible.

_handle_single_model_about_to_be_reset(model)[source]

Runs when given model is about to reset.

_handle_single_model_reset(model)[source]

Runs when given model is reset.

_refresh_single_model(model)[source]
_get_insert_position(model)[source]
_insert_single_model(model)[source]
_get_row_for_insertion(pos)[source]
_insert_row_map(pos, single_row_map)[source]
clear_model()[source]

Clears the model.

spinetoolbox.mvcmodels.empty_row_model

Contains a table model with an empty last row.

Module Contents
Classes

EmptyRowModel

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.

canFetchMore(_parent)[source]

Return True if the model hasn’t been fetched.

fetchMore(parent)[source]

Fetch data and use it to reset the model.

flags(index)[source]

Return default flags except if forcing defaults.

set_default_row(**kwargs)[source]

Set default row data.

clear()[source]

Clear all data in model.

reset_model(main_data=None)[source]

Reset model.

_handle_data_changed(top_left, bottom_right, roles=None)[source]

Insert a new last empty row in case the previous one has been filled with any data other than the defaults.

removeRows(row, count, parent=QModelIndex())[source]

Don’t remove the last empty row.

_handle_rows_inserted(parent, first, last)[source]

Handle rowsInserted signal.

set_rows_to_default(first, last=None)[source]

Set default data in newly inserted rows.

spinetoolbox.mvcmodels.file_list_models

Common models. Contains a generic File list model and an Item for that model. Used by the Importer and Tool project items but this may be handy for other project items as well.

Module Contents
Classes

FileListModel

A model for files to be shown in a file tree view.

CommandLineArgItem

NewCommandLineArgItem

CommandLineArgsModel

JumpCommandLineArgsModel

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

FileItem[source]
PackItem[source]
rowCount(parent=QModelIndex())[source]
columnCount(parent=QModelIndex())[source]
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.

flags(index)[source]
mimeData(indexes)[source]
resource(index)[source]

Returns the resource at given index.

Parameters

index (QModelIndex) – index

Returns

resource

Return type

ProjectItemResource

parent(index)[source]
index(row, column, parent=QModelIndex())[source]
update(resources)[source]

Updates the model according to given list of resources.

Parameters

resources (Iterable of ProjectItemResource) – resources

duplicate_paths()[source]

Checks if resources in the model have duplicate file paths.

Returns

set of duplicate file paths

Return type

set of str

_pack_index(pack_label)[source]

Finds a pack’s index in pack resources list.

Parameters

pack_label (str) – pack label

Returns

index to pack resources list

Return type

int

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

set_rank(rank)[source]
static _make_icon(rank=None)[source]
setData(value, role=Qt.ItemDataRole.UserRole + 1)[source]
class spinetoolbox.mvcmodels.file_list_models.NewCommandLineArgItem[source]

Bases: CommandLineArgItem

setData(value, role=Qt.ItemDataRole.UserRole + 1)[source]
class spinetoolbox.mvcmodels.file_list_models.CommandLineArgsModel(parent=None)[source]

Bases: PySide6.QtGui.QStandardItemModel

property args[source]
args_updated[source]
append_arg(arg)[source]
replace_arg(row, arg)[source]
mimeData(indexes)[source]
dropMimeData(data, drop_action, row, column, parent)[source]
static _reset_root(root, args, child_params, has_empty_row=True)[source]
class spinetoolbox.mvcmodels.file_list_models.JumpCommandLineArgsModel(parent=None)[source]

Bases: CommandLineArgsModel

reset_model(args)[source]
canDropMimeData(data, drop_action, row, column, parent)[source]
spinetoolbox.mvcmodels.filter_checkbox_list_model

Provides FilterCheckboxListModel for FilterWidget.

Module Contents
Classes

SimpleFilterCheckboxListModel

Init class.

LazyFilterCheckboxListModel

Extends SimpleFilterCheckboxListModel to allow for lazy loading in synch with another model.

DataToValueFilterCheckboxListModel

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

Init class.

Parameters

parent (QWidget) –

property _show_empty[source]
property _show_add_to_selection[source]
_SELECT_ALL_STR = '(Select all)'[source]
_SELECT_ALL_FILTERED_STR = '(Select all filtered)'[source]
_EMPTY_STR = '(Empty)'[source]
_ADD_TO_SELECTION_STR = 'Add current selection to filter'[source]
reset_selection()[source]
_handle_select_all_clicked()[source]
_check_all_selected()[source]
rowCount(parent=QModelIndex())[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]
_handle_index_clicked(index)[source]
set_list(data, all_selected=True)[source]
filter_by_condition(condition)[source]

Updates selected items by applying a condition.

Parameters

condition (function) – Filter acceptance condition.

set_selected(selected, select_empty=None)[source]
get_selected()[source]
get_not_selected()[source]
set_filter(filter_expression)[source]
search_filter_expression(item)[source]
apply_filter()[source]
_remove_and_add_filtered()[source]
_remove_and_replace_filtered()[source]
remove_filter()[source]
_do_add_items(data)[source]
add_items(data, selected=None)[source]
remove_items(data)[source]
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.

Init class.

Parameters
canFetchMore(_parent)[source]
fetchMore(_parent)[source]
_do_add_items(data)[source]

Adds items so the list is always sorted, while assuming that both existing and new items are sorted.

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.

Init class.

Parameters
  • parent (SpineDBEditor) –

  • data_to_value (method) – a method to translate item data to a value for display role

data(index, role=Qt.ItemDataRole.DisplayRole)[source]
search_filter_expression(item)[source]
spinetoolbox.mvcmodels.filter_execution_model

Contains FilterExecutionModel.

Module Contents
Classes

FilterExecutionModel

class spinetoolbox.mvcmodels.filter_execution_model.FilterExecutionModel[source]

Bases: PySide6.QtCore.QAbstractListModel

_filter_consoles[source]
reset_model(filter_consoles)[source]
rowCount(parent=QModelIndex())[source]
headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]
find_index(console_key)[source]
get_console(filter_id)[source]
spinetoolbox.mvcmodels.indexed_value_table_model

A model for indexed parameter values, used by the parameter_value editors.

Module Contents
Classes

IndexedValueTableModel

A base class for time pattern and time series models.

Attributes

EXPANSE_COLOR

spinetoolbox.mvcmodels.indexed_value_table_model.EXPANSE_COLOR[source]
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

property value[source]

Returns the parameter_value associated with the model.

columnCount(parent=QModelIndex())[source]

Returns the number of columns which is two.

data(index, role=Qt.ItemDataRole.DisplayRole)[source]

Returns the data at index for given role.

headerData(section, orientation=Qt.Orientation.Horizontal, role=Qt.ItemDataRole.DisplayRole)[source]

Returns a header.

is_expanse_row(row)[source]

Returns True if row is the expanse row.

Parameters

row (int) – a row

Returns

True if row is the expanse row, False otherwise

Return type

bool

reset(value)[source]

Resets the model.

rowCount(parent=QModelIndex())[source]

Returns the number of rows.

setHeaderData(section, orientation, value, role=Qt.ItemDataRole.EditRole)[source]
spinetoolbox.mvcmodels.map_model

A model for maps, used by the parameter_value editors.

Module Contents
Classes

MapModel

A model for Map type parameter values.

Functions

_rows_to_dict(rows)

Turns table into nested dictionaries.

_reconstruct_map(tree)

Constructs a Map from a nested dictionary.

_data_length(row)

Counts the number of non-empty elements at the beginning of row.

_gather_index_names(map_value)

Collects index names from Map.

_apply_index_names(map_value, index_names)

Applies index names to Map.

_numpy_string_to_python_strings(rows)

Converts instances of numpy.str_ to regular Python strings.

Attributes

empty

Sentinel for empty cells.

spinetoolbox.mvcmodels.map_model.empty[source]

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

append_column()[source]

Appends a new column to the right.

clear(indexes)[source]

Clears table cells.

Parameters

indexes (list of QModelIndex) – indexes to clear

columnCount(index=QModelIndex())[source]

Returns the number of columns in this model.

convert_leaf_maps()[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]

Returns the data associated with the given role.

flags(index)[source]

Returns flags at index.

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

reset(map_value)[source]

Resets the model to given map_value.

rowCount(parent=QModelIndex())[source]

Returns the number of rows.

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

setData(index, value, role=Qt.ItemDataRole.EditRole)[source]

Sets data in the map.

Parameters
  • index (QModelIndex) – an index to the model

  • value (object) – JSON representation of the value

  • role (int) – a role

Returns

True if the operation was successful

Return type

bool

setHeaderData(section, orientation, value, role=Qt.ItemDataRole.EditRole)[source]
trim_columns()[source]

Removes empty columns from the right.

value()[source]

Returns the Map.

index_name(index)[source]
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.map_model._apply_index_names(map_value, index_names)[source]

Applies index names to Map.

Parameters
  • map_value (Map) – target Map

  • index_names (list of str) – index names

spinetoolbox.mvcmodels.map_model._numpy_string_to_python_strings(rows)[source]

Converts instances of numpy.str_ to regular Python strings.

Parameters

rows (list of list) – table rows

Returns

converted rows

Return type

list of list

spinetoolbox.mvcmodels.minimal_table_model

Contains a minimal table model.

Module Contents
Classes

MinimalTableModel

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

clear()[source]

Clear all data in model.

flags(index)[source]

Return index flags.

canFetchMore(parent)[source]

Return True if the model hasn’t been fetched.

fetchMore(parent)[source]

Fetch data and use it to reset the model.

rowCount(parent=QModelIndex())[source]

Number of rows in the model.

columnCount(parent=QModelIndex())[source]

Number of columns in the model.

headerData(section, orientation=Qt.Orientation.Horizontal, role=Qt.ItemDataRole.DisplayRole)[source]

Returns headers.

set_horizontal_header_labels(labels)[source]

Set horizontal header labels.

insert_horizontal_header_labels(section, labels)[source]

Insert horizontal header labels at the given section.

horizontal_header_labels()[source]
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.

setData(index, value, role=Qt.ItemDataRole.EditRole)[source]

Set data in model.

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

reset_model(main_data=None)[source]

Reset model.

spinetoolbox.mvcmodels.minimal_tree_model

Models to represent items in a tree.

Module Contents
Classes

TreeItem

A tree item that can fetch its children.

MinimalTreeModel

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.

property model[source]
property children[source]
property parent_item[source]
property display_data[source]
property edit_data[source]
set_has_children_initially(has_children_initially)[source]
has_children()[source]

Returns whether this item has or could have children.

is_valid()[source]

Tests if item is valid.

Returns

True if item is valid, False otherwise

Return type

bool

child(row)[source]

Returns the child at given row or None if out of bounds.

last_child()[source]

Returns the last child.

child_count()[source]

Returns the number of children.

row_count()[source]

Returns the number of rows, which may be different from the number of children. This allows subclasses to hide children.

child_number()[source]

Returns the rank of this item within its parent or -1 if it’s an orphan.

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.

next_sibling()[source]

Returns the next sibling or None if it’s the last.

previous_sibling()[source]

Returns the previous sibling or None if it’s the first.

index()[source]
set_up()[source]
_do_set_up()[source]

Do stuff after the item has been inserted.

_polish_children(children)[source]

Polishes children just before inserting them.

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

append_children(children)[source]

Append children at the end.

tear_down()[source]

Do stuff after the item has been removed.

tear_down_recursively()[source]
remove_children(position, count)[source]

Removes count children starting from the given position.

Parameters
  • position (int) – position of the first child to remove

  • count (int) – number of children to remove

Returns

True if operation was successful, False otherwise

Return type

bool

flags(column)[source]

Enables the item and makes it selectable.

data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

can_fetch_more()[source]

Returns whether this item can fetch more.

fetch_more()[source]

Fetches more children.

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

class spinetoolbox.mvcmodels.minimal_tree_model.MinimalTreeModel(parent)[source]

Bases: PySide6.QtCore.QAbstractItemModel

Base class for all tree models.

Init class.

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.

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.

parent(index)[source]

Returns the parent of the model item with the given index.

columnCount(parent=QModelIndex())[source]
rowCount(parent=QModelIndex())[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]

Returns the data stored under the given role for the index.

setData(index, value, role=Qt.ItemDataRole.EditRole)[source]

Sets data for given index and role. Returns True if successful; otherwise returns False.

flags(index)[source]

Returns the item flags for the given index.

hasChildren(parent)[source]
canFetchMore(parent)[source]
fetchMore(parent)[source]
spinetoolbox.mvcmodels.project_item_model

Contains a class for storing project items.

Module Contents
Classes

ProjectItemModel

Class to store project tree items and ultimately project items in a tree structure.

class spinetoolbox.mvcmodels.project_item_model.ProjectItemModel(root, parent=None)[source]

Bases: PySide6.QtCore.QAbstractItemModel

Class to store project tree items and ultimately project items in a tree structure.

Parameters
  • root (RootProjectTreeItem) – Root item for the project item tree

  • parent (QObject) – parent object

root()[source]

Returns the root item.

connect_to_project(project)[source]

Connects the model to a project.

Parameters

project (SpineToolboxProject) – project to connect to

_add_leaf_item(name)[source]

Adds a leaf item to the model

Parameters

name (str) – project item’s name

_remove_leaf_item(name)[source]

Removes a leaf item from the model.

Parameters

name (str) – project item’s name

_rename_item(old_name, new_name)[source]

Renames a leaf item.

Parameters
  • old_name (str) – item’s old name

  • new_name (str) – item’s new name

rowCount(parent=QModelIndex())[source]

Reimplemented rowCount method.

Parameters

parent (QModelIndex) – Index of parent item whose children are counted.

Returns

Number of children of given parent

Return type

int

columnCount(parent=QModelIndex())[source]

Returns model column count which is always 1.

flags(index)[source]

Returns flags for the item at given index

Parameters

index (QModelIndex) – Flags of item at this index.

parent(index=QModelIndex())[source]

Returns index of the parent of given index.

Parameters

index (QModelIndex) – Index of item whose parent is returned

Returns

Index of parent item

Return type

QModelIndex

index(row, column, parent=QModelIndex())[source]

Returns index of item with given row, column, and parent.

Parameters
  • row (int) – Item row

  • column (int) – Item column

  • parent (QModelIndex) – Parent item index

Returns

Item index

Return type

QModelIndex

data(index, role=None)[source]

Returns data in the given index according to requested role.

Parameters
  • index (QModelIndex) – Index to query

  • role (int) – Role to return

Returns

Data depending on role.

Return type

object

item(index)[source]

Returns item at given index.

Parameters

index (QModelIndex) – Index of item

Returns

Item at given index or root project

item if index is not valid

Return type

RootProjectTreeItem, CategoryProjectTreeItem or LeafProjectTreeItem

find_category(category_name)[source]

Returns the index of the given category name.

Parameters

category_name (str) – Name of category item to find

Returns

index of a category item or None if it was not found

Return type

QModelIndex

find_item(name)[source]

Returns the QModelIndex of the leaf item with the given name

Parameters

name (str) – The searched project item (long) name

Returns

Index of a project item with the given name or None if not found

Return type

QModelIndex

get_item(name)[source]

Returns leaf item with given name or None if it doesn’t exist.

Parameters

name (str) – Project item name

Returns

LeafProjectTreeItem, NoneType

category_of_item(name)[source]

Returns the category item of the category that contains project item with given name

Parameters

name (str) – Project item name

Returns

category item or None if the category was not found

Return type

CategoryProjectTreeItem

insert_item(item, parent=QModelIndex())[source]

Adds a new item to model. Fails if given parent is not a category item nor a leaf item. New item is inserted as the last item of its branch.

Parameters
Returns

True if successful, False otherwise

Return type

bool

remove_item(item, parent=QModelIndex())[source]

Removes item from project.

Parameters
  • item (BaseProjectTreeItem) – Item to remove

  • parent (QModelIndex) – Parent of item that is to be removed

Returns

True if item removed successfully, False if item removing failed

Return type

bool

items(category_name=None)[source]

Returns a list of leaf items in model according to category name. If no category name given, returns all leaf items in a list.

Parameters

category_name (str) – Item category. Data Connections, Data Stores, Importers, Exporters, Tools or Views permitted.

Returns

obj:’list’ of :obj:’LeafProjectTreeItem’: Depending on category_name argument, returns all items or only items according to category. An empty list is returned if there are no items in the given category or if an unknown category name was given.

n_items()[source]

Returns the number of all items in the model excluding category items and root.

Returns

Number of items

Return type

int

item_names()[source]

Returns all leaf item names in a list.

Returns

‘list’ of obj:’str’: Item names

Return type

obj

items_per_category()[source]

Returns a dict mapping category indexes to a list of items in that category.

Returns

dict(QModelIndex,list(LeafProjectTreeItem))

leaf_indexes()[source]

Yields leaf indexes.

remove_leaves()[source]
spinetoolbox.mvcmodels.project_item_specification_models

Contains a class for storing Tool specifications.

Module Contents
Classes

ProjectItemSpecificationModel

Class to store specs that are available in a project e.g. GAMS or Julia models.

FilteredSpecificationModel

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.

specification_replaced[source]
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

clear()[source]
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

specification_row(name)[source]

Returns the row on which the given specification is located or -1 if it is not found.

specification_index(name)[source]

Returns the QModelIndex on which a specification with the given name is located or invalid index if it is not found.

class spinetoolbox.mvcmodels.project_item_specification_models.FilteredSpecificationModel(item_type)[source]

Bases: PySide6.QtCore.QSortFilterProxyModel

filterAcceptsRow(source_row, source_parent)[source]
get_mime_data_text(index)[source]
specifications()[source]

Yields all specs.

specification(row)[source]
spinetoolbox.mvcmodels.project_tree_item

Project Tree items.

Module Contents
Classes

BaseProjectTreeItem

Base class for all project tree items.

RootProjectTreeItem

Class for the root project tree item.

CategoryProjectTreeItem

Class for category project tree items.

LeafProjectTreeItem

Class for leaf items in the project item tree.

class spinetoolbox.mvcmodels.project_tree_item.BaseProjectTreeItem(name, description)[source]

Bases: spinetoolbox.metaobject.MetaObject

Base class for all project tree items.

Parameters
  • name (str) – Object name

  • description (str) – Object description

flags()[source]

Returns the item flags.

parent()[source]

Returns parent project tree item.

child_count()[source]

Returns the number of child project tree items.

children()[source]

Returns the children of this project tree item.

child(row)[source]

Returns child BaseProjectTreeItem on given row.

Parameters

row (int) – Row of child to return

Returns

item on given row or None if it does not exist

Return type

BaseProjectTreeItem

row()[source]

Returns the row on which this item is located.

abstract add_child(child_item)[source]

Base method that shall be overridden in subclasses.

remove_child(row)[source]

Remove the child of this BaseProjectTreeItem from given row. Do not call this method directly. This method is called by ProjectItemTreeModel when items are removed.

Parameters

row (int) – Row of child to remove

Returns

True if operation succeeded, False otherwise

Return type

bool

abstract custom_context_menu(toolbox)[source]

Returns the context menu for this item. Implement in subclasses as needed.

Parameters

toolbox (QWidget) – The widget that is controlling the menu

Returns

context menu

Return type

QMenu

class spinetoolbox.mvcmodels.project_tree_item.RootProjectTreeItem[source]

Bases: BaseProjectTreeItem

Class for the root project tree item.

Parameters
  • name (str) – Object name

  • description (str) – Object description

add_child(child_item)[source]

Adds given category item as the child of this root project tree item. New item is added as the last item.

Parameters

child_item (CategoryProjectTreeItem) – Item to add

Returns

True for success, False otherwise

abstract custom_context_menu(toolbox)[source]

See base class.

class spinetoolbox.mvcmodels.project_tree_item.CategoryProjectTreeItem(name, description)[source]

Bases: BaseProjectTreeItem

Class for category project tree items.

Parameters
  • name (str) – Object name

  • description (str) – Object description

flags()[source]

Returns the item flags.

add_child(child_item)[source]

Adds given project tree item as the child of this category item. New item is added as the last item.

Parameters

child_item (LeafProjectTreeTreeItem) – Item to add

Returns

True for success, False otherwise

custom_context_menu(toolbox)[source]

Returns the context menu for this item.

Parameters

toolbox (ToolboxUI) – Toolbox main window

Returns

context menu

Return type

QMenu

class spinetoolbox.mvcmodels.project_tree_item.LeafProjectTreeItem(project_item)[source]

Bases: BaseProjectTreeItem

Class for leaf items in the project item tree.

Parameters

project_item (ProjectItem) – the real project item this item represents

property project_item[source]

the project item linked to this leaf

abstract add_child(child_item)[source]

See base class.

flags()[source]

Returns the item flags.

custom_context_menu(toolbox)[source]

Returns the context menu for this item.

Parameters

toolbox (ToolboxUI) – Toolbox main window

Returns

context menu

Return type

QMenu

spinetoolbox.mvcmodels.resource_filter_model

Contains ResourceFilterModel.

Module Contents
Classes

ResourceFilterModel

param connection

connection whose resources to model

class spinetoolbox.mvcmodels.resource_filter_model.ResourceFilterModel(connection, project, undo_stack, logger)[source]

Bases: PySide6.QtGui.QStandardItemModel

Parameters
property connection[source]
tree_built[source]
_SELECT_ALL = 'Select all'[source]
_FILTER_TYPES[source]
_FILTER_TYPE_TO_TEXT[source]
build_tree()[source]

Rebuilds model’s contents.

fetch_filters()[source]
setData(index, value, role=Qt.ItemDataRole.EditRole)[source]
_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

_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.shared

Contains stuff that is used by more than one model

Module Contents
spinetoolbox.mvcmodels.shared.PARSED_ROLE[source]
spinetoolbox.mvcmodels.shared.DB_MAP_ROLE[source]
spinetoolbox.mvcmodels.time_pattern_model

A model for time patterns, used by the parameter_value editors.

Module Contents
Classes

TimePatternModel

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

flags(index)[source]

Returns flags at index.

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

batch_set_data(indexes, values)[source]

Sets data for several indexes at once.

Parameters
  • indexes (Sequence) – a sequence of model indexes

  • values (Sequence) – a sequence of time periods/floats corresponding to the indexes

spinetoolbox.mvcmodels.time_series_model_fixed_resolution

A model for fixed resolution time series, used by the parameter_value editors.

Module Contents
Classes

TimeSeriesModelFixedResolution

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

property indexes[source]

Returns the time stamps as an array.

property values[source]

Returns the values of the time series as an array.

flags(index)[source]

Returns flags at index.

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.

reset(value)[source]

Resets the model with new time series data.

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

batch_set_data(indexes, values)[source]

Sets data for several indexes at once.

Only the values of the series are modified as the time stamps are immutable.

Parameters
  • indexes (Sequence) – a sequence of model indexes

  • values (Sequence) – a sequence of floats corresponding to the indexes

set_ignore_year(ignore_year)[source]

Sets the ignore_year option of the time series.

set_repeat(repeat)[source]

Sets the repeat option of the time series.

set_resolution(resolution)[source]

Sets the resolution.

set_start(start)[source]

Sets the start datetime.

spinetoolbox.mvcmodels.time_series_model_variable_resolution

A model for variable resolution time series, used by the parameter_value editors.

Module Contents
Classes

TimeSeriesModelVariableResolution

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

property indexes[source]

Returns the time stamps as an array.

property values[source]

Returns the values of the time series as an array.

flags(index)[source]

Returns the flags for given model index.

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

reset(value)[source]

Resets the model with new time series data.

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

batch_set_data(indexes, values)[source]

Sets data for several indexes at once.

Parameters
  • indexes (Sequence) – a sequence of model indexes

  • values (Sequence) – a sequence of datetimes/floats corresponding to the indexes

set_ignore_year(ignore_year)[source]

Sets the ignore_year option of the time series.

set_repeat(repeat)[source]

Sets the repeat option of the time series.

spinetoolbox.project_item

This subpackage contains base classes for project items.

Submodules
spinetoolbox.project_item.logging_connection

Contains logging connection and jump classes.

Module Contents
Classes

HeadlessConnection

A project item connection that is compatible with headless mode.

LoggingConnection

A project item connection that is compatible with headless mode.

LoggingJump

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

property database_resources[source]

Connection’s database resources

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

_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().

static _constructor_args_from_dict(connection_dict)[source]

See base class.

classmethod from_dict(connection_dict, **kwargs)[source]

Deserializes a connection from dict.

Parameters
  • connection_dict (dict) – serialized LoggingConnection

  • **kwargs – additional keyword arguments to be forwarded to class constructor

receive_resources_from_source(resources)[source]

See base class.

replace_resources_from_source(old, new)[source]

Replaces existing resources by new ones.

Parameters
  • old (list of ProjectItemResource) – old resources

  • new (list of ProjectItemResource) – new resources

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

property graphics_item[source]
__hash__()[source]

Return hash(self).

static item_type()[source]
has_filters()[source]

Returns True if connection has scenario filters.

Returns

True if connection has filters, False otherwise

Return type

bool

_get_db_map(url, ignore_version_error=False)[source]
_pop_unused_db_maps()[source]

Removes unused database maps and unregisters from listening the DB manager.

_make_fetch_parent(db_map, item_type)[source]
_fetch_more_if_possible()[source]
_receive_data_changed()[source]
receive_session_committed(db_maps, cookie)[source]
receive_session_rolled_back(db_map)[source]
receive_error_msg(_db_map_error_log)[source]
get_scenario_names(url)[source]
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) – Always SCENARIO_FILTER_TYPE, for now.

  • 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.

receive_resources_from_source(resources)[source]

See base class.

replace_resources_from_source(old, new)[source]

See base class.

set_connection_options(options)[source]

Overwrites connections options.

Parameters

options (dict) – new options

_check_available_filters()[source]

Cross-checks filter settings with source databases.

Returns

filter settings containing only filters that exist in source databases

Return type

FilterSettings

_resource_filters_online(resource, filter_type)[source]
to_dict()[source]

See base class.

tear_down()[source]

Releases system resources held by the connection.

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

property graphics_item[source]
static item_type()[source]
spinetoolbox.project_item.project_item

Contains base classes for project items and item factories.

Module Contents
Classes

ProjectItem

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

property logger[source]
abstract property executable_class[source]
create_data_dir()[source]
data_files()[source]

Returns a list of files that are in the data directory.

abstract static item_type()[source]

Item’s type identifier string.

Returns

type string

Return type

str

abstract static item_category()[source]

Item’s category.

Returns

category name

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.

activate()[source]

Restore selections and connect signals.

deactivate()[source]

Save selections and disconnect signals.

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.

_connect_signals()[source]

Connect signals to handlers.

_disconnect_signals()[source]

Disconnect signals from handlers and check for errors.

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

specification()[source]

Returns the specification for this item.

undo_specification()[source]
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

get_icon()[source]

Returns the graphics item representing this item in the scene.

_check_notifications()[source]

Checks if exclamation icon notifications need to be set or cleared.

clear_notifications()[source]

Clear all notifications from the exclamation icon.

add_notification(text)[source]

Add a notification to the exclamation icon.

remove_notification(text)[source]
set_rank(rank)[source]

Set rank of this item for displaying in the design view.

handle_execution_successful(execution_direction, engine_state)[source]

Performs item dependent actions after the execution item has finished successfully.

Parameters
  • execution_direction (str) – “FORWARD” or “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

invalidate_workflow(edges)[source]

Notifies that this item’s workflow is not acyclic.

Parameters

edges (list) – A list of edges that make the graph acyclic after removing them.

revalidate_workflow()[source]
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

ProjectItem

actions()[source]

Item specific actions.

Returns

item’s actions

Return type

list of QAction

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

open_directory(checked=False)[source]

Open this item’s data directory in file explorer.

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.

Module Contents
Classes

ProjectItemFactory

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()[source]

Returns the icon resource path.

Returns

str

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

ProjectItemIcon

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

abstract static make_specification_menu(parent, index)[source]

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

ItemSpecificationMenu

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

Module Contents
Classes

ChangeSpecPropertyCommand

Command to set specification properties.

SpecificationEditorWindowBase

Base class for spec editors.

_SpecNameDescriptionToolbar

QToolBar for line edits and a hamburger menu.

Functions

prompt_to_save_changes(parent, settings, save_callback)

Prompts to save changes.

class spinetoolbox.project_item.specification_editor_window.ChangeSpecPropertyCommand(callback, new_value, old_value, cmd_name)[source]

Bases: PySide6.QtGui.QUndoCommand

Command to set specification properties.

Parameters
  • callback (function) – Function to call to set the spec property.

  • new_value (any) – new value

  • old_value (any) – old value

  • cmd_name (str) – command name

redo()[source]
undo()[source]
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

abstract property settings_group[source]

Returns the settings group for this spec type.

Returns

str

property _duplicate_kwargs[source]
abstract _make_ui()[source]

Returns the ui object from Qt designer.

Returns

object

_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.

show_error(message)[source]
_show_status_bar_msg(msg)[source]
_populate_main_menu()[source]
_update_window_modified(clean)[source]
_set_window_title(title)[source]

Sets window title.

Parameters

title (str) – new window title

_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

prompt_exit_without_saving()[source]

Prompts whether the user wants to exit without saving or cancel the exit.

Returns

False if the user chooses to cancel, in which case we don’t close the form.

Return type

bool

_duplicate()[source]
tear_down()[source]
closeEvent(event)[source]
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

name_changed[source]
_make_main_menu()[source]
_set_name()[source]
_set_description()[source]
do_set_name(name)[source]
do_set_description(description)[source]
name()[source]
description()[source]
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.

Module Contents
Classes

ClientSecurityModel

Generic enumeration.

EngineClient

param host

IP address of the Spine Engine Server

class spinetoolbox.server.engine_client.ClientSecurityModel[source]

Bases: enum.Enum

Generic enumeration.

Derive from this class to define new enumerations.

NONE = 0[source]
STONEHOUSE = 1[source]
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, item_name, accepted)[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

  • item_name (str) –

  • accepted (Bool) –

download_files(q)[source]

Pulls files from server until b’END’ is received.

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.

get_elapsed_time()[source]

Returns the elapsed time between now and when self.start_time was set.

Returns

Time string with unit(s)

Return type

str

close()[source]

Closes client sockets, context and thread.

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.

Submodules
spinetoolbox.spine_db_editor.mvcmodels.alternative_item

Classes to represent items in an alternative tree.

Module Contents
Classes

DBItem

A root item representing a db.

AlternativeItem

An alternative leaf item.

Attributes

_ALTERNATIVE_ICON

spinetoolbox.spine_db_editor.mvcmodels.alternative_item._ALTERNATIVE_ICON = '\uf277'[source]
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.

property item_type[source]
property fetch_item_type[source]
empty_child()[source]
_make_child(id_)[source]
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

property item_type[source]
property icon_code[source]
property tool_tip[source]
add_item_to_db(db_item)[source]
update_item_in_db(db_item)[source]
flags(column)[source]

Makes items editable.

spinetoolbox.spine_db_editor.mvcmodels.alternative_model

Contains alternative tree model.

Module Contents
Classes

AlternativeModel

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
_make_db_item(db_map)[source]
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
spinetoolbox.spine_db_editor.mvcmodels.colors

Color constants for models.

Module Contents
spinetoolbox.spine_db_editor.mvcmodels.colors.PIVOT_TABLE_HEADER_COLOR[source]
spinetoolbox.spine_db_editor.mvcmodels.colors.FIXED_FIELD_COLOR[source]
spinetoolbox.spine_db_editor.mvcmodels.colors.SELECTED_COLOR[source]
spinetoolbox.spine_db_editor.mvcmodels.compound_models

Compound models. These models concatenate several ‘single’ models and one ‘empty’ model.

Module Contents
Classes

CompoundModelBase

A base model for all models that show data in stacked format.

FilterEntityAlternativeMixin

Provides the interface to filter by entity and alternative.

EditParameterValueMixin

Provides the interface for ParameterValueEditor to edit values.

CompoundParameterDefinitionModel

A model that concatenates several single object parameter_definition models

CompoundParameterValueModel

A model that concatenates several single object parameter_value models

CompoundEntityAlternativeModel

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 (DiffDatabaseMapping) – the database maps included in the model

abstract property item_type[source]

Returns the DB item type, e.g., ‘parameter_value’.

Returns

str

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

abstract _make_header()[source]
canFetchMore(_parent)[source]

Returns True if any of the submodels that haven’t been fetched yet can fetch more.

fetchMore(_parent)[source]

Fetches the next sub model and increments the fetched counter.

shows_item(item, db_map)[source]
init_model()[source]

Initializes the model.

get_auto_filter_menu(logical_index)[source]

Returns auto filter menu for given logical index from header view.

Parameters

logical_index (int) –

Returns

AutoFilterMenu

_make_auto_filter_menu(field)[source]
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 (SingleParameterModel, EmptyParameterModel) –

Returns

bool

_class_filter_accepts_model(model)[source]
_auto_filter_accepts_model(model)[source]
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

_invalidate_filter()[source]

Sets the filter invalid.

stop_invalidating_filter()[source]

Stops invalidating the filter.

set_filter_class_ids(class_ids)[source]
clear_auto_filter()[source]
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 (DiffDatabaseMapping) –

Returns

list

_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 DiffDatabaseMapping

_get_insert_position(model)[source]
_create_single_model(db_map, entity_class_id, committed)[source]
_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 (DiffDatabaseMapping) – 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 DiffDatabaseMapping

handle_items_removed(db_map_data)[source]

Runs when either parameter definitions or values are removed from the dbs. Removes the affected rows from the corresponding single models.

Parameters

db_map_data (dict) – list of removed dict-items keyed by DiffDatabaseMapping

db_item(index)[source]
db_map_id(index)[source]
get_entity_class_id(index, db_map)[source]
filter_by(rows_per_column)[source]
filter_excluding(rows_per_column)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_models.FilterEntityAlternativeMixin(*args, **kwargs)[source]

Provides the interface to filter by entity and alternative.

init_model()[source]
set_filter_entity_ids(entity_ids)[source]
set_filter_alternative_ids(alternative_ids)[source]
_create_single_model(db_map, entity_class_id, committed)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_models.EditParameterValueMixin[source]

Provides the interface for ParameterValueEditor to edit values.

index_name(index)[source]

Generates a name for data at given index.

Parameters

index (QModelIndex) – index to model

Returns

label identifying the data

Return type

str

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

class spinetoolbox.spine_db_editor.mvcmodels.compound_models.CompoundParameterDefinitionModel(parent, db_mngr, *db_maps)[source]

Bases: EditParameterValueMixin, CompoundModelBase

A model that concatenates several single object parameter_definition models and one empty object parameter_definition model.

Parameters
  • parent (SpineDBEditor) – the parent object

  • db_mngr (SpineDBManager) – the database manager

  • *db_maps (DiffDatabaseMapping) – the database maps included in the model

property item_type[source]

Returns the DB item type, e.g., ‘parameter_value’.

Returns

str

property _single_model_type[source]

Returns a constructor for the single models.

Returns

SingleParameterModel

property _empty_model_type[source]

Returns a constructor for the empty model.

Returns

EmptyParameterModel

_make_header()[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_models.CompoundParameterValueModel(*args, **kwargs)[source]

Bases: FilterEntityAlternativeMixin, EditParameterValueMixin, CompoundModelBase

A model that concatenates several single object parameter_value models and one empty object parameter_value model.

property item_type[source]

Returns the DB item type, e.g., ‘parameter_value’.

Returns

str

property _single_model_type[source]

Returns a constructor for the single models.

Returns

SingleParameterModel

property _empty_model_type[source]

Returns a constructor for the empty model.

Returns

EmptyParameterModel

_make_header()[source]
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 item_type[source]

Returns the DB item type, e.g., ‘parameter_value’.

Returns

str

property _single_model_type[source]

Returns a constructor for the single models.

Returns

SingleParameterModel

property _empty_model_type[source]

Returns a constructor for the empty model.

Returns

EmptyParameterModel

_make_header()[source]
spinetoolbox.spine_db_editor.mvcmodels.empty_models

Empty models for parameter definitions and values.

Module Contents
Classes

EmptyModelBase

Base class for all empty models that go in a CompoundModelBase subclass.

ParameterMixin

EntityMixin

EmptyParameterDefinitionModel

An empty parameter_definition model.

EmptyParameterValueModel

An empty parameter_value model.

EmptyEntityAlternativeModel

Makes relationships on the fly.

class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyModelBase(parent, header, db_mngr)[source]

Bases: spinetoolbox.mvcmodels.empty_row_model.EmptyRowModel

Base class for all empty models that go in a CompoundModelBase subclass.

Initialize class.

Parameters
  • parent (Object) – the parent object, typically a CompoundParameterModel

  • header (list) – list of field names for the header

  • db_mngr (SpineDBManager) –

abstract property item_type[source]
property can_be_filtered[source]
abstract 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.

accepted_rows()[source]
db_item(_index)[source]
item_id(_row)[source]
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]
_make_item(row)[source]
_make_db_map_data(rows)[source]

Returns model data grouped by database map.

Parameters

rows (set) – group data from these rows

Returns

mapping DiffDatabaseMapping instance to list of items

Return type

dict

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.

class spinetoolbox.spine_db_editor.mvcmodels.empty_models.ParameterMixin[source]
property value_field[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]
class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EntityMixin[source]
abstract _do_add_items_to_db(db_map_items)[source]
add_items_to_db(db_map_data, second_pass=False)[source]

See base class.

_make_item(row)[source]
class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyParameterDefinitionModel(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInValueListIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInParameterNameMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin, ParameterMixin, EmptyModelBase

An empty parameter_definition model.

Initializes lookup dicts.

property item_type[source]
_make_unique_id(item)[source]

Returns a unique id for the given model item (name-based). Used by handle_items_added.

add_items_to_db(db_map_data)[source]

See base class.

_check_item(item)[source]

Checks if a db item is ready to be inserted.

class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyParameterValueModel(*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.InferEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInAlternativeIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInParameterDefinitionIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin, ParameterMixin, EntityMixin, EmptyModelBase

An empty parameter_value model.

Initializes lookup dicts.

property item_type[source]
_check_item(db_map, item)[source]

Checks if a db item is ready to be inserted.

_make_unique_id(item)[source]

Returns a unique id for the given model item (name-based). Used by handle_items_added.

_do_add_items_to_db(db_map_items)[source]
class spinetoolbox.spine_db_editor.mvcmodels.empty_models.EmptyEntityAlternativeModel(*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.InferEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInAlternativeIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityClassIdMixin, EntityMixin, EmptyModelBase

Makes relationships on the fly.

Initializes lookup dicts.

property item_type[source]
_check_item(db_map, item)[source]

Checks if a db item is ready to be inserted.

_make_unique_id(item)[source]

Returns a unique id for the given model item (name-based). Used by handle_items_added.

_do_add_items_to_db(db_map_items)[source]
spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item

Classes to represent entities in a tree.

Module Contents
Classes

EntityClassIndex

dict() -> new empty dictionary

EntityGroupIndex

dict() -> new empty dictionary

EntityIndex

dict() -> new empty dictionary

EntityTreeRootItem

A tree item that may belong in multiple databases.

EntityClassItem

An entity_class item.

EntityItem

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.

process_item(item, db_map)[source]
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.

process_item(item, db_map)[source]
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.

process_item(item, db_map)[source]
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

property visible_children[source]
property display_id[source]

See super class.

property display_icon[source]

Returns an icon to display next to the name. Reimplement in subclasses to return something nice.

property display_data[source]

See super class.

property child_item_class[source]

Returns ObjectClassItem.

item_type = 'root'[source]
set_data(column, value, role)[source]

See base class.

_polish_children(children)[source]

See base class.

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

property display_icon[source]

Returns class icon.

property child_item_class[source]

Returns the type of child items.

property _children_sort_key[source]

Reimplemented so groups are above non-groups.

visual_key = ['name', 'dimension_name_list'][source]
item_type = 'entity_class'[source]
_fetch_index[source]
is_hidden()[source]
default_parameter_data()[source]

Return data to put as default in a parameter table when this item is selected.

data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

_key_for_index(db_map)[source]
accepts_item(item, db_map)[source]
set_data(column, value, role)[source]

See base class.

_polish_children(children)[source]

See base class.

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 is_group[source]
property child_item_class[source]

Child class is always EntityItem.

property display_icon[source]

Returns corresponding class icon.

property element_name_list[source]
property entity_class_key[source]
property display_data[source]

Returns the name for display.

property edit_data[source]
visual_key = ['class_name', 'byname'][source]
item_type = 'entity'[source]
_fetch_index[source]
_entity_group_index[source]
data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

set_data(column, value, role)[source]

See base class.

default_parameter_data()[source]

Return data to put as default in a parameter table when this item is selected.

is_valid()[source]

See base class.

Additionally, checks that the parent entity (if any) is still an element in this entity.

_can_fetch_more_entity_groups()[source]
can_fetch_more()[source]

Returns whether this item can fetch more.

_fetch_more_entity_groups()[source]
fetch_more()[source]

Fetches children from all associated databases.

_key_for_index(db_map)[source]
_key_for_entity_group_index(db_map)[source]
accepts_item(item, db_map)[source]
_accepts_entity_group_item(item, db_map)[source]
_handle_entity_group_items_added(db_map_data)[source]
_handle_entity_group_items_removed(db_map_data)[source]
tear_down()[source]

Do stuff after the item has been removed.

spinetoolbox.spine_db_editor.mvcmodels.entity_tree_models

Models to represent entities in a tree.

Module Contents
Classes

EntityTreeModel

Base class for all tree models in Spine db editor.

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
property root_item_type[source]

Implement in subclasses to create a model specific to any entity type.

property hide_empty_classes[source]
find_next_entity_index(index)[source]

Find and return next occurrence of relationship item.

save_hide_empty_classes()[source]
spinetoolbox.spine_db_editor.mvcmodels.frozen_table_model

Contains FrozenTableModel class.

Module Contents
Classes

FrozenTableModel

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

property headers[source]
selected_row_changed[source]
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

clear_model()[source]
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

clear_selected()[source]

Clears selected row.

set_selected(row)[source]

Changes selected row.

Parameters

row (int) – row index

get_frozen_value()[source]

Return currently selected frozen value.

Returns

frozen value

Return type

tuple

rowCount(parent=QModelIndex())[source]
columnCount(parent=QModelIndex())[source]
row(index)[source]
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

moveColumns(sourceParent, sourceColumn, count, destinationParent, destinationChild)[source]
_keep_sorted()[source]

Sorts the data table.

_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

data(index, role=Qt.ItemDataRole.DisplayRole)[source]
_tooltip_from_data(row, column)[source]

Resolves item tooltip which is usually its description.

Parameters
  • row (int) – row

  • column (int) – column

Returns

value’s tooltip

Return type

str

_name_from_data(value, header)[source]

Resolves item name.

Parameters
  • value (tuple or DatabaseMapping) – cell value

  • header (str) – column header

Returns

value’s name

Return type

str

spinetoolbox.spine_db_editor.mvcmodels.item_metadata_table_model

Contains ItemMetadataTableModel and associated functionality.

Module Contents
Classes

ExtraColumn

Identifiers for hidden table columns.

ItemType

Allowed item types.

ItemMetadataTableModel

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.

ITEM_METADATA_ID[source]
METADATA_ID[source]
class spinetoolbox.spine_db_editor.mvcmodels.item_metadata_table_model.ItemType[source]

Bases: enum.Enum

Allowed item types.

ENTITY[source]
VALUE[source]
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

_ITEM_NAME_KEY = 'metadata_name'[source]
_ITEM_VALUE_KEY = 'metadata_value'[source]
_fetch_parents()[source]

Yields fetch parents for this model.

Yields

FetchParent

clear()[source]

Clears the model.

static _make_hidden_adder_columns()[source]

See base class.

_accepts_entity_metadata_item(item, db_map)[source]
_accepts_parameter_value_metadata_item(item, db_map)[source]
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

_reset_fetch_parents()[source]
_add_data_to_db_mngr(name, value, db_map)[source]

See base class.

_update_data_in_db_mngr(id_, name, value, db_map)[source]

See base class

flags(index)[source]
static _ids_from_added_item(item)[source]

See base class.

static _extra_cells_from_added_item(item)[source]

See base class.

_set_extra_columns(row, ids)[source]

See base class.

_database_table_name()[source]

See base class

_row_id(row)[source]

See base class.

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

update_item_metadata(db_map_data)[source]

Updates item metadata in model after it has been updated in databases.

Parameters

db_map_data (dict) – updated metadata records

remove_item_metadata(db_map_data)[source]

Removes item metadata from model after it has been removed from databases.

Parameters

db_map_data (dict) – removed items keyed by database mapping

spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model

Contains MetadataTableModel and associated functionality.

Module Contents
Classes

ExtraColumn

Identifiers for hidden table columns.

MetadataTableModel

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.

ID[source]
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

_ITEM_NAME_KEY = 'name'[source]
_ITEM_VALUE_KEY = 'value'[source]
static _make_hidden_adder_columns()[source]

See base class.

_add_data_to_db_mngr(name, value, db_map)[source]

See base class.

_update_data_in_db_mngr(id_, name, value, db_map)[source]

See base class

_database_table_name()[source]

See base class

_row_id(row)[source]

See base class.

flags(index)[source]
_fetch_parents()[source]

Yields fetch parents for this model.

Yields

FetchParent

static _ids_from_added_item(item)[source]

See base class.

static _extra_cells_from_added_item(item)[source]

See base class.

_set_extra_columns(row, ids)[source]

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

update_metadata(db_map_data)[source]

Updates model according to data received from database manager.

Parameters

db_map_data (dict) – updated metadata items keyed by database mapping

remove_metadata(db_map_data)[source]

Removes metadata from model after it has been removed from databases.

Parameters

db_map_data (dict) – removed items keyed by database mapping

spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base

Contains base class for metadata table models associated functionality.

Module Contents
Classes

Column

Identifiers for visible table columns.

MetadataTableModelBase

Base for metadata table models

Attributes

FLAGS_FIXED

FLAGS_EDITABLE

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.

NAME = 0[source]
VALUE = 1[source]
DB_MAP = 2[source]
static max()[source]
spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base.FLAGS_FIXED[source]
spinetoolbox.spine_db_editor.mvcmodels.metadata_table_model_base.FLAGS_EDITABLE[source]
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

msg_error[source]

Emitted when an error occurs.

_HEADER = ('name', 'value', 'database')[source]
_ITEM_NAME_KEY[source]
_ITEM_VALUE_KEY[source]
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

abstract static _make_hidden_adder_columns()[source]

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 _fetch_parents()[source]

Yields fetch parents for this model.

Yields

FetchParent

canFetchMore(_)[source]
fetchMore(_)[source]
rowCount(parent=QModelIndex())[source]
columnCount(parent=QModelIndex())[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]
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

setData(index, value, role=Qt.ItemDataRole.EditRole)[source]
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

headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]
insertRows(row, count, parent=QModelIndex())[source]
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

removeRows(first, count, parent=QModelIndex())[source]
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

sort(column, order=Qt.AscendingOrder)[source]
_find_db_map(codename)[source]

Finds database mapping with given codename.

Parameters

codename (str) – database mapping’s code name

Returns

database mapping or None if not found

Return type

DiffDatabaseMapping

_reserved_metadata()[source]

Collects metadata names and values that are already in database.

Returns

mapping from database mapping to metadata name and value

Return type

dict

spinetoolbox.spine_db_editor.mvcmodels.mime_types

Contains mime types used by the models.

Module Contents
spinetoolbox.spine_db_editor.mvcmodels.mime_types.ALTERNATIVE_DATA = 'application/vnd.spinetoolbox.alternative'[source]
spinetoolbox.spine_db_editor.mvcmodels.mime_types.SCENARIO_DATA = 'application/vnd.spinetoolbox.scenario'[source]
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item

Base classes to represent items from multiple databases in a tree.

Module Contents
Classes

MultiDBTreeItem

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 visible_children[source]
property db_mngr[source]
abstract property child_item_class[source]

Returns the type of child items.

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_data[source]

Returns the name for display.

property display_database[source]

Returns the database for display.

property display_icon[source]

Returns an icon to display next to the name. Reimplement in subclasses to return something nice.

property first_db_map[source]

Returns the first associated db_map.

property db_maps[source]

Returns a list of all associated db_maps.

property db_map_ids[source]

Returns dict with db_map as key and id as value

property _children_sort_key[source]
property fetch_item_type[source]
item_type[source]

Item type identifier string. Should be set to a meaningful value by subclasses.

visual_key = ['name'][source]
_fetch_index[source]
row_count()[source]

Returns the number of rows, which may be different from the number of children. This allows subclasses to hide children.

child(row)[source]

Returns the child at given row or None if out of bounds.

child_number()[source]

Returns the rank of this item within its parent or -1 if it’s an orphan.

refresh_child_map()[source]

Recomputes the child map.

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

add_db_map_id(db_map, id_)[source]

Adds id for this item in the given db_map.

take_db_map(db_map)[source]

Removes the mapping for given db_map and returns it.

deep_refresh_children()[source]

Refreshes children after taking db_maps from them. Called after removing and updating children for this item.

deep_remove_db_map(db_map)[source]

Removes given db_map from this item and all its descendants.

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

deep_merge(other)[source]

Merges another item and all its descendants into this one.

db_map_id(db_map)[source]

Returns the id for this item in given db_map or None if not present.

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

restore(db_map_ids, **kwargs)[source]
_make_child(db_map_ids, **kwargs)[source]
_merge_children(new_children)[source]

Merges new children into this item. Ensures that each child has a valid display id afterwards.

_insert_children_sorted(new_children)[source]

Inserts and sorts children.

can_fetch_more()[source]

Returns whether this item can fetch more.

fetch_more()[source]

Fetches children from all associated databases.

fetch_more_if_possible()[source]
_key_for_index(db_map)[source]
accepts_item(item, db_map)[source]
handle_items_added(db_map_data)[source]
handle_items_removed(db_map_data)[source]
handle_items_updated(db_map_data)[source]
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

is_valid()[source]

See base class.

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

remove_children(position, count)[source]

Removes count children starting from the given position.

reposition_child(row)[source]
find_row(db_map, id_)[source]
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_rows_by_id(db_map, *ids, reverse=True)[source]
_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.

data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

default_parameter_data()[source]

Returns data to set as default in a parameter table when this item is selected.

tear_down()[source]

Do stuff after the item has been removed.

register_fetch_parent()[source]

Registers item’s fetch parent for all model’s databases.

spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_model

A base model class to represent items from multiple databases in a tree.

Module Contents
Classes

MultiDBTreeModel

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
abstract property root_item_type[source]

Implement in subclasses to create a model specific to any entity type.

property root_item[source]
property root_index[source]
property _header_labels[source]
build_tree()[source]

Builds tree.

columnCount(parent=QModelIndex())[source]
headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]
find_items(db_map, path_prefix, fetch=False)[source]

Returns items at given path prefix.

spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item

Tree items for parameter_value lists.

Module Contents
Classes

DBItem

An item representing a db.

ListItem

A list item.

ValueItem

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.

property item_type[source]
property fetch_item_type[source]
empty_child()[source]
_make_child(id_)[source]
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.

property item_type[source]
property fetch_item_type[source]
_make_item_data()[source]
_do_set_up()[source]

Do stuff after the item has been inserted.

empty_child()[source]
_make_child(id_)[source]
accepts_item(item, db_map)[source]
_children_sort_key(child)[source]
data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

_make_item_to_add(value)[source]
add_item_to_db(db_item)[source]
update_item_in_db(db_item)[source]
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

property item_type[source]
data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

list_index()[source]
_make_item_to_add(value)[source]
_make_item_to_update(_column, value)[source]
add_item_to_db(db_item)[source]
update_item_in_db(db_item)[source]
spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_model

A tree model for parameter_value lists.

Module Contents
Classes

ParameterValueListModel

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
_make_db_item(db_map)[source]
columnCount(parent=QModelIndex())[source]

Returns the number of columns under the given parent. Always 1.

index_name(index)[source]
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

Callable

spinetoolbox.spine_db_editor.mvcmodels.pivot_model

Provides PivotModel.

Module Contents
Classes

PivotModel

class spinetoolbox.spine_db_editor.mvcmodels.pivot_model.PivotModel[source]
property rows[source]
property columns[source]
reset_model(data, top_left_headers=(), rows=(), columns=(), frozen=(), frozen_value=())[source]

Resets the model.

clear_model()[source]
update_model(data)[source]
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

remove_from_model(data)[source]
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_pivot(rows, columns, frozen, frozen_value)[source]

Sets pivot.

set_frozen_value(value)[source]

Sets values for the frozen indexes.

Parameters

value (list of str) –

set_frozen(frozen)[source]

Sets the frozen names without resetting the pivot.

Parameters

frozen (Iterable of str) –

get_pivoted_data(row_mask, column_mask)[source]

Returns data for indexes in row_mask and column_mask.

Parameters
  • row_mask (list) –

  • column_mask (list) –

Returns

list(list)

row_key(row)[source]
column_key(column)[source]
spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models

Provides pivot table models for the Tabular View.

Module Contents
Classes

TopLeftHeaderItem

Base class for all 'top left pivot headers'.

TopLeftEntityHeaderItem

A top left header for an entity class.

TopLeftParameterHeaderItem

A top left header for parameter_definition.

TopLeftParameterIndexHeaderItem

A top left header for parameter index.

TopLeftAlternativeHeaderItem

A top left header for alternative.

TopLeftScenarioHeaderItem

A top left header for scenario.

TopLeftDatabaseHeaderItem

A top left header for database.

PivotTableModelBase

param db_editor

ParameterValuePivotTableModel

A model for the pivot table in parameter_value input type.

IndexExpansionPivotTableModel

A model for the pivot table in parameter index expansion input type.

ElementPivotTableModel

A model for the pivot table in element input type.

ScenarioAlternativePivotTableModel

A model for the pivot table in scenario alternative input type.

PivotTableSortFilterProxy

Initialize class.

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) –

property model[source]
property db_mngr[source]
_get_header_data_from_db(item_type, header_id, field_name, role)[source]
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

abstract update_data(db_map_data)[source]

Updates database data.

Parameters

db_map_data (dict) – update data

Returns

True if data was successfully updated, False otherwise

Return type

bool

abstract add_data(names, db_map)[source]

Adds more data to database.

Parameters
  • names (set of str) – header names

  • db_map (DatabaseMapping) – database to add the data to

Returns

True if data was added successfully, False otherwise

Return type

bool

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) –

property header_type[source]
property name[source]
header_data(header_id, role=Qt.ItemDataRole.DisplayRole)[source]

See base class.

update_data(db_map_data)[source]

See base class.

add_data(names, db_map)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftParameterHeaderItem(model)[source]

Bases: TopLeftHeaderItem

A top left header for parameter_definition.

Parameters

model (PivotTableModelBase) –

property header_type[source]
property name[source]
header_data(header_id, role=Qt.ItemDataRole.DisplayRole)[source]

See base class.

update_data(db_map_data)[source]

See base class.

add_data(names, db_map)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftParameterIndexHeaderItem(model)[source]

Bases: TopLeftHeaderItem

A top left header for parameter index.

Parameters

model (PivotTableModelBase) –

property header_type[source]
property name[source]
header_data(header_id, role=Qt.ItemDataRole.DisplayRole)[source]

See base class.

update_data(db_map_data)[source]

See base class.

add_data(names, db_map)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftAlternativeHeaderItem(model)[source]

Bases: TopLeftHeaderItem

A top left header for alternative.

Parameters

model (PivotTableModelBase) –

property header_type[source]
property name[source]
header_data(header_id, role=Qt.ItemDataRole.DisplayRole)[source]

See base class.

update_data(db_map_data)[source]

See base class.

add_data(names, db_map)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftScenarioHeaderItem(model)[source]

Bases: TopLeftHeaderItem

A top left header for scenario.

Parameters

model (PivotTableModelBase) –

property header_type[source]
property name[source]
header_data(header_id, role=Qt.ItemDataRole.DisplayRole)[source]

See base class.

update_data(db_map_data)[source]

See base class.

add_data(names, db_map)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftDatabaseHeaderItem(model)[source]

Bases: TopLeftHeaderItem

A top left header for database.

Parameters

model (PivotTableModelBase) –

property header_type[source]
property name[source]
header_data(header_id, role=Qt.ItemDataRole.DisplayRole)[source]

See base class.

update_data(db_map_data)[source]

See base class.

add_data(names, db_map)[source]

See base class.

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

take_suggested_db_map()[source]

Suggests database mapping resetting the suggestion afterwards.

Returns

database mapping

Return type

DatabaseMapping

suggest_db_map_codename()[source]

Suggests a database mapping codename.

Returns

codename

Return type

str

class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.PivotTableModelBase(db_editor)[source]

Bases: PySide6.QtCore.QAbstractTableModel

Parameters

db_editor (SpineDBEditor) –

property db_maps[source]
abstract property item_type[source]

Returns the item type.

property plot_x_column[source]

Returns the index of the column designated as Y values for plotting or None.

_CHUNK_SIZE = 1000[source]
model_data_changed[source]
frozen_values_added[source]
frozen_values_removed[source]
reset_fetch_parents()[source]
abstract _fetch_parents()[source]

Yields fetch parents for this model.

Yields

FetchParent

canFetchMore(_)[source]
fetchMore(_)[source]
_reset_data_count()[source]
_collect_more_data()[source]
_collect_more_rows()[source]
_collect_more_columns()[source]
abstract call_reset_model(pivot=None)[source]
Parameters

pivot (tuple, optional) – list of rows, list of columns, list of frozen indexes, frozen value

abstract static make_delegate(parent)[source]
reset_model(data, index_ids, rows=(), columns=(), frozen=(), frozen_value=())[source]
clear_model()[source]
update_model(data)[source]

Update model with new data, but doesn’t grow the model.

Parameters

data (dict) –

add_to_model(db_map_data)[source]
remove_from_model(data)[source]
_emit_all_data_changed()[source]
set_pivot(rows, columns, frozen, frozen_value)[source]
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

set_plot_x_column(column, is_x)[source]

Sets or clears the X flag on a column

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

headerRowCount()[source]

Returns number of rows occupied by header.

headerColumnCount()[source]

Returns number of columns occupied by header.

dataRowCount()[source]

Returns number of rows that contain actual data.

dataColumnCount()[source]

Returns number of columns that contain actual data.

emptyRowCount()[source]
emptyColumnCount()[source]
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

flags(index)[source]

Roles for data

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_within_top_left(index)[source]
index_in_top(index)[source]
index_in_left(index)[source]
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_headers(index)[source]
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.

index_in_data(index)[source]

Returns whether the given index is in data area.

column_is_index_column(column)[source]

Returns True if column is the column containing expanded parameter_value indexes.

headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]
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

_color_data(index)[source]
_text_alignment_data(index)[source]
_header_data(index, role=Qt.ItemDataRole.DisplayRole)[source]
_header_name(top_left_id, header_id)[source]
abstract _data(index, role)[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]
setData(index, value, role=Qt.ItemDataRole.EditRole)[source]
batch_set_data(indexes, values)[source]
_batch_set_inner_data(inner_data)[source]
abstract _do_batch_set_inner_data(row_map, column_map, data, values)[source]
_batch_set_header_data(header_data)[source]

Sets header data for multiple indexes at once.

Parameters

header_data (list of tuple) – mapping from index to data

Returns

True if data was set successfully, False otherwise

Return type

bool

_batch_set_empty_header_data(header_data, get_top_left_id)[source]
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) –

property item_type[source]

Returns the item type.

_handle_entities_added(db_map_data)[source]
_handle_entities_removed(db_map_data)[source]
_handle_parameter_definitions_added(db_map_data)[source]
_handle_parameter_definitions_removed(db_map_data)[source]
_handle_parameter_values_added(db_map_data)[source]
_handle_parameter_values_removed(db_map_data)[source]
_handle_alternatives_added(db_map_data)[source]
_handle_alternatives_removed(db_map_data)[source]
_load_empty_parameter_value_data(*args, **kwargs)[source]
_load_full_parameter_value_data(*args, **kwargs)[source]
_fetch_parents()[source]

Yields fetch parents for this model.

Yields

FetchParent

_db_map_element_ids(header_ids)[source]
db_map_entity_ids(indexes)[source]

Returns db_map and entity ids for given indexes. Used by PivotTableView.

Parameters

list (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

call_reset_model(pivot=None)[source]

See base class.

static make_delegate(parent)[source]
_default_pivot(data)[source]
_data(index, role)[source]
_do_batch_set_inner_data(row_map, column_map, data, values)[source]
_entity_parameter_value_to_add(db_map, header_ids, value_and_type, ent_id_lookup)[source]
_make_parameter_value_to_add()[source]
static _parameter_value_to_update(id_, header_ids, value_and_type)[source]
_batch_set_parameter_value_data(row_map, column_map, data, values)[source]

Sets parameter values in batch.

_add_parameter_values(db_map_data)[source]
_update_parameter_values(db_map_data)[source]
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

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) –

call_reset_model(pivot=None)[source]

See base class.

flags(index)[source]

Roles for data

column_is_index_column(column)[source]

Returns True if column is the column containing expanded parameter_value indexes.

_load_empty_parameter_value_data(*args, **kwargs)[source]
_load_full_parameter_value_data(*args, **kwargs)[source]
_data(index, role)[source]
static _parameter_value_to_update(id_, header_ids, value_and_type)[source]
_update_parameter_values(db_map_data)[source]
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) –

property item_type[source]

Returns the item type.

_handle_entities_added(db_map_data)[source]
_handle_entities_removed(db_map_data)[source]
_load_empty_element_data(db_map_data)[source]
_handle_elements_added(db_map_data)[source]
_handle_elements_removed(db_map_data)[source]
_fetch_parents()[source]

Yields fetch parents for this model.

Yields

FetchParent

call_reset_model(pivot=None)[source]

See base class.

static make_delegate(parent)[source]
_default_pivot(data)[source]
_data(index, role)[source]
_do_batch_set_inner_data(row_map, column_map, data, values)[source]
_batch_set_entity_data(row_map, column_map, data, values)[source]
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) –

property item_type[source]

Returns the item type.

_handle_scenarios_added(db_map_data)[source]
_handle_scenarios_removed(db_map_data)[source]
_handle_alternatives_added(db_map_data)[source]
_handle_alternatives_removed(db_map_data)[source]
_handle_scenario_alternatives_changed(db_map_data)[source]
_fetch_parents()[source]

Yields fetch parents for this model.

Yields

FetchParent

call_reset_model(pivot=None)[source]

See base class.

static make_delegate(parent)[source]
_default_pivot(data)[source]
_data(index, role)[source]
_do_batch_set_inner_data(row_map, column_map, data, values)[source]
_batch_set_scenario_alternative_data(row_map, column_map, data, values)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.PivotTableSortFilterProxy(parent=None)[source]

Bases: PySide6.QtCore.QSortFilterProxyModel

Initialize class.

model_data_changed[source]
setSourceModel(model)[source]
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)

clear_filter()[source]
accept_index(index, index_ids)[source]
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.

filterAcceptsColumn(source_column, source_parent)[source]

Returns true if the item in the column indicated by the given source_column and source_parent should be included in the model; otherwise returns false.

batch_set_data(indexes, values)[source]
spinetoolbox.spine_db_editor.mvcmodels.scenario_item

Classes to represent items in scenario tree.

Module Contents
Classes

ScenarioDBItem

A root item representing a db.

ScenarioItem

A scenario leaf item.

ScenarioAlternativeItem

A scenario alternative leaf item.

Attributes

_SCENARIO_ICON

spinetoolbox.spine_db_editor.mvcmodels.scenario_item._SCENARIO_ICON = '\uf008'[source]
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.

property item_type[source]
property fetch_item_type[source]
empty_child()[source]
_make_child(id_)[source]
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.

property item_type[source]
property fetch_item_type[source]
property icon_code[source]
property tool_tip[source]
property alternative_id_list[source]
_do_set_up()[source]

Doesn’t add children to the last row.

add_item_to_db(db_item)[source]
update_item_in_db(db_item)[source]
handle_updated_in_db()[source]
flags(column)[source]

Makes items editable.

update_alternative_id_list()[source]
accepts_item(item, db_map)[source]
handle_items_added(_db_map_data)[source]

Inserts items at right positions. Items with commit_id are kept sorted. Items without a commit_id are put at the end.

Parameters

db_map_data (dict) – mapping db_map to list of dict corresponding to db items

handle_items_removed(_db_map_data)[source]
handle_items_updated(_db_map_data)[source]
empty_child()[source]

See base class.

_make_child(id_)[source]

Not needed - we don’t quite add children here, but rather update them in update_alternative_id_list.

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

property item_type[source]
property tool_tip[source]
property item_data[source]
property alternative_id[source]
_make_item_data()[source]
abstract add_item_to_db(db_item)[source]
abstract update_item_in_db(db_item)[source]
flags(column)[source]

Makes items editable.

set_data(column, value, role=Qt.ItemDataRole.EditRole)[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

spinetoolbox.spine_db_editor.mvcmodels.scenario_model

Contains scenario tree model.

Module Contents
Classes

ScenarioModel

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
_make_db_item(db_map)[source]
supportedDropActions()[source]
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

canDropMimeData(mime_data, drop_action, row, column, parent)[source]
dropMimeData(mime_data, drop_action, row, column, parent)[source]
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

Miscelaneous mixins for parameter models

Module Contents
Classes

ConvertToDBMixin

Base class for all mixins that convert model items (name-based) into database items (id-based).

SplitValueAndTypeMixin

Base class for all mixins that convert model items (name-based) into database items (id-based).

FillInAlternativeIdMixin

Fills in alternative names.

FillInParameterNameMixin

Fills in parameter names.

FillInValueListIdMixin

Fills in value list ids.

FillInEntityClassIdMixin

Fills in entity_class ids.

FillInEntityIdsMixin

Fills in entity ids.

FillInParameterDefinitionIdsMixin

Fills in parameter_definition ids.

InferEntityClassIdMixin

Infers entity class ids.

ImposeEntityClassIdMixin

Imposes entity class ids.

MakeEntityOnTheFlyMixin

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).

build_lookup_dictionary(db_map_data)[source]

Begins an operation to convert items.

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

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).

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInAlternativeIdMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in alternative names.

Initializes lookup dicts.

build_lookup_dictionary(db_map_data)[source]

Builds a name lookup dictionary for the given data.

Parameters

db_map_data (dict) – lists of model items keyed by DiffDatabaseMapping

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInParameterNameMixin[source]

Bases: ConvertToDBMixin

Fills in parameter names.

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInValueListIdMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in value list ids.

Initializes lookup dicts.

build_lookup_dictionary(db_map_data)[source]

Builds a name lookup dictionary for the given data.

Parameters

db_map_data (dict) – lists of model items keyed by DiffDatabaseMapping

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

_fill_in_value_list_id(item, db_map)[source]

Fills in the value list id in the given db item.

Parameters
  • item (dict) – the db item

  • db_map (DiffDatabaseMapping) – the database where the given item belongs

Returns

error log

Return type

list

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityClassIdMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in entity_class ids.

Initializes lookup dicts.

build_lookup_dictionary(db_map_data)[source]

Builds a name lookup dictionary for the given data.

Parameters

db_map_data (dict) – lists of model items keyed by DiffDatabaseMapping

_fill_in_entity_class_id(item, db_map)[source]

Fills in the entity_class id in the given db item.

Parameters
  • item (dict) – the db item

  • db_map (DiffDatabaseMapping) – the database where the given item belongs

Returns

error log

Return type

list

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityIdsMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in entity ids.

Initializes lookup dicts.

build_lookup_dictionary(db_map_data)[source]

Builds a name lookup dictionary for the given data.

Parameters

db_map_data (dict) – lists of model items keyed by DiffDatabaseMapping

_fill_in_entity_ids(item, db_map)[source]

Fills in all possible entity ids keyed by entity_class id in the given db item (as there can be more than one entity for the same name).

Parameters
  • item (dict) – the db item

  • db_map (DiffDatabaseMapping) – the database where the given item belongs

Returns

error log

Return type

list

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInParameterDefinitionIdsMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in parameter_definition ids.

Initializes lookup dicts.

build_lookup_dictionary(db_map_data)[source]

Builds a name lookup dictionary for the given data.

Parameters

db_map_data (dict) – lists of model items keyed by DiffDatabaseMapping

_fill_in_parameter_ids(item, db_map)[source]

Fills in all possible parameter_definition ids keyed by entity_class id in the given db item (as there can be more than one parameter_definition for the same name).

Parameters
  • item (dict) – the db item

  • db_map (DiffDatabaseMapping) – the database where the given item belongs

Returns

error log

Return type

list

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.InferEntityClassIdMixin[source]

Bases: ConvertToDBMixin

Infers entity class ids.

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

_infer_and_fill_in_entity_class_id(item, db_map)[source]

Fills the entity_class id in the given db item, by intersecting entity ids and parameter ids. Then picks the correct entity id and parameter_definition id. Also sets the inferred entity_class name in the model.

Parameters
  • item (dict) – the db item

  • db_map (DiffDatabaseMapping) – the database where the given item belongs

Returns

error log

Return type

list

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.ImposeEntityClassIdMixin[source]

Bases: ConvertToDBMixin

Imposes entity class ids.

_convert_to_db(item, db_map)[source]

Returns a db item (id-based) from the given model item (name-based).

Parameters
  • item (dict) – the model item

  • db_map (DiffDatabaseMapping) – the database where the resulting item belongs

Returns

the db item list: error log

Return type

dict

_impose_entity_class_id(item, db_map)[source]

Imposes the entity_class id from the model, to pick the correct entity id and parameter_definition id.

Parameters
  • item (dict) – the db item

  • db_map (DiffDatabaseMapping) – the database where the given item belongs

Returns

error log

Return type

list

class spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.MakeEntityOnTheFlyMixin(*args, **kwargs)[source]

Makes relationships on the fly.

Initializes lookup dicts.

static _make_unique_entity_id(item)[source]

Returns a unique name-based identifier for db entities.

build_lookup_dictionary(db_map_data)[source]

Builds a name lookup dictionary for the given data.

Parameters

db_map_data (dict) – lists of model items keyed by DiffDatabaseMapping.

_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’).

Module Contents
Classes

HalfSortedTableModel

Table model for outlining simple tabular data.

SingleModelBase

Base class for all single models that go in a CompoundModelBase subclass.

FilterEntityAlternativeMixin

Provides the interface to filter by entity and alternative.

ParameterMixin

Provides the data method for parameter values and definitions.

EntityMixin

SingleParameterDefinitionModel

A parameter_definition model for a single entity_class.

SingleParameterValueModel

A parameter_value model for a single entity_class.

SingleEntityAlternativeModel

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

reset_model(main_data=None)[source]

Reset model.

add_rows(data)[source]
_sort_key(element)[source]
class spinetoolbox.spine_db_editor.mvcmodels.single_models.SingleModelBase(header, db_mngr, db_map, entity_class_id, committed, lazy=False)[source]

Bases: HalfSortedTableModel

Base class for all single models that go in a CompoundModelBase subclass.

Init class.

Parameters

header (list) – list of field names for the header

abstract property item_type[source]

The DB item type, required by the data method.

abstract property _references[source]
property entity_class_name[source]
property dimension_id_list[source]
property fixed_fields[source]
property group_fields[source]
property _field_map[source]
property can_be_filtered[source]
__lt__(other)[source]
abstract update_items_in_db(items)[source]

Update items in db. Required by batch_set_data

_mapped_field(field)[source]
item_id(row)[source]

Returns parameter id for row.

Parameters

row (int) – row index

Returns

parameter id

Return type

int

item_ids()[source]

Returns model’s parameter ids.

Returns

ids

Return type

set of int

db_item(index)[source]
_db_item(row)[source]
db_item_from_id(id_)[source]
db_items()[source]
flags(index)[source]

Make fixed indexes non-editable.

_filter_accepts_row(row)[source]
filter_accepts_item(item)[source]
set_auto_filter(field, values)[source]
_auto_filter_accepts_item(item)[source]

Returns the result of the auto filter.

accepted_rows()[source]

Yields accepted rows, for convenience.

_get_ref(db_item, field)[source]

Returns the item referred by the given field.

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. Sets data directly in database using db mngr. If successful, updated data will be automatically seen by the data method.

class spinetoolbox.spine_db_editor.mvcmodels.single_models.FilterEntityAlternativeMixin(*args, **kwargs)[source]

Provides the interface to filter by entity and alternative.

set_filter_entity_ids(db_map_entity_ids)[source]
set_filter_alternative_ids(db_map_alternative_ids)[source]
filter_accepts_item(item)[source]

Reimplemented to also account for the entity and alternative filter.

_entity_filter_accepts_item(item)[source]

Returns the result of the entity filter.

_alternative_filter_accepts_item(item)[source]

Returns the result of the alternative filter.

class spinetoolbox.spine_db_editor.mvcmodels.single_models.ParameterMixin[source]

Provides the data method for parameter values and definitions.

property value_field[source]
property parameter_definition_id_key[source]
property _references[source]
data(index, role=Qt.ItemDataRole.DisplayRole)[source]

Gets the id and database for the row, and reads data from the db manager using the item_type property. Paint the object_class icon next to the name. Also paint background of fixed indexes gray and apply custom format to JSON fields.

class spinetoolbox.spine_db_editor.mvcmodels.single_models.EntityMixin[source]
update_items_in_db(items)[source]

Update items in db.

Parameters

items (list) – dictionary-items

abstract _do_update_items_in_db(db_map_data)[source]
class spinetoolbox.spine_db_editor.mvcmodels.single_models.SingleParameterDefinitionModel(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInParameterNameMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInValueListIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin, ParameterMixin, SingleModelBase

A parameter_definition model for a single entity_class.

Initializes lookup dicts.

property item_type[source]

The DB item type, required by the data method.

property _field_map[source]
_sort_key(element)[source]
update_items_in_db(items)[source]

Update items in db.

Parameters

items (list) – dictionary-items

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.FillInAlternativeIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.ImposeEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInParameterDefinitionIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.SplitValueAndTypeMixin, ParameterMixin, EntityMixin, FilterEntityAlternativeMixin, SingleModelBase

A parameter_value model for a single entity_class.

Initializes lookup dicts.

property item_type[source]

The DB item type, required by the data method.

_sort_key(element)[source]
_do_update_items_in_db(db_map_data)[source]
class spinetoolbox.spine_db_editor.mvcmodels.single_models.SingleEntityAlternativeModel(*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.FillInAlternativeIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.ImposeEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.single_and_empty_model_mixins.FillInEntityIdsMixin, EntityMixin, FilterEntityAlternativeMixin, SingleModelBase

An entity_alternative model for a single entity_class.

Initializes lookup dicts.

property item_type[source]

The DB item type, required by the data method.

property _references[source]
_sort_key(element)[source]
_do_update_items_in_db(db_map_data)[source]
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility

A tree model for parameter_value lists.

Module Contents
Classes

StandardTreeItem

A tree item that fetches their children as they are inserted.

EditableMixin

GrayIfLastMixin

Paints the item gray if it's the last.

BoldTextMixin

Bolds text.

EmptyChildMixin

Guarantees there's always an empty child.

SortChildrenMixin

FetchMoreMixin

StandardDBItem

An item representing a db.

LeafItem

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.

property item_type[source]
property db_mngr[source]
property display_data[source]
property icon_code[source]
property tool_tip[source]
property display_icon[source]
property non_empty_children[source]
property children_ids[source]
data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

set_data(column, value, role=Qt.ItemDataRole.DisplayRole)[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

class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EditableMixin[source]
flags(column)[source]

Makes items editable.

class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin[source]

Paints the item gray if it’s the last.

data(column, role=Qt.ItemDataRole.DisplayRole)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.BoldTextMixin[source]

Bolds text.

data(column, role=Qt.ItemDataRole.DisplayRole)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildMixin[source]

Guarantees there’s always an empty child.

property non_empty_children[source]
abstract empty_child()[source]
_do_set_up()[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.SortChildrenMixin[source]
_children_sort_key(child)[source]
insert_children_sorted(children)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin(*args, **kwargs)[source]
property fetch_item_type[source]
tear_down()[source]
_fetch_parents()[source]
can_fetch_more()[source]
fetch_more()[source]
abstract _make_child(id_)[source]
_do_make_child(id_)[source]
accepts_item(item, db_map)[source]
handle_items_added(db_map_data)[source]

Inserts items at right positions. Items with commit_id are kept sorted. Items without a commit_id are put at the end.

Parameters

db_map_data (dict) – mapping db_map to list of dict corresponding to db items

handle_items_removed(db_map_data)[source]
handle_items_updated(db_map_data)[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
property item_type[source]
data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Shows Spine icon for fun.

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

abstract property item_type[source]
property db_map[source]
property id[source]
property item_data[source]
property name[source]
_make_item_data()[source]
abstract add_item_to_db(db_item)[source]
abstract update_item_in_db(db_item)[source]
header_data(column)[source]
data(column, role=Qt.ItemDataRole.DisplayRole)[source]

Returns data for given column and role.

set_data(column, value, role=Qt.ItemDataRole.EditRole)[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

_make_item_to_add(value)[source]
_make_item_to_update(column, value)[source]
handle_updated_in_db()[source]
can_fetch_more()[source]

Returns whether this item can fetch more.

spinetoolbox.spine_db_editor.mvcmodels.tree_model_base

Models to represent things in a tree.

Module Contents
Classes

TreeModelBase

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
columnCount(parent=QModelIndex())[source]

Returns the number of columns under the given parent. Always 2.

Returns

column count

Return type

int

headerData(section, orientation, role=Qt.ItemDataRole.DisplayRole)[source]
build_tree()[source]

Builds tree.

abstract _make_db_item(db_map)[source]
static db_item(item)[source]
db_row(item)[source]
spinetoolbox.spine_db_editor.mvcmodels.utils

General helper functions and classes for DB editor’s models.

Module Contents
Functions

two_column_as_csv(indexes)

Writes data in given indexes into a CSV table.

spinetoolbox.spine_db_editor.mvcmodels.utils.two_column_as_csv(indexes)[source]

Writes data in given indexes into a CSV table.

Expects the source table to have two columns.

Parameters

indexes (Sequence of QModelIndex) – model indexes

Returns

data as CSV table

Return type

str

spinetoolbox.spine_db_editor.ui

Automatically generated UI modules for Spine db editor.

Submodules
spinetoolbox.spine_db_editor.ui.scenario_generator
Module Contents
Classes

Ui_Form

class spinetoolbox.spine_db_editor.ui.scenario_generator.Ui_Form[source]

Bases: object

setupUi(Form)[source]
retranslateUi(Form)[source]
spinetoolbox.spine_db_editor.ui.select_databases
Module Contents
Classes

Ui_Form

class spinetoolbox.spine_db_editor.ui.select_databases.Ui_Form[source]

Bases: object

setupUi(Form)[source]
retranslateUi(Form)[source]
spinetoolbox.spine_db_editor.ui.spine_db_editor_window
Module Contents
Classes

Ui_MainWindow

class spinetoolbox.spine_db_editor.ui.spine_db_editor_window.Ui_MainWindow[source]

Bases: object

setupUi(MainWindow)[source]
retranslateUi(MainWindow)[source]
spinetoolbox.spine_db_editor.widgets

Interface logic for Spine db editor.

Submodules
spinetoolbox.spine_db_editor.widgets.add_items_dialogs

Classes for custom QDialogs to add items to databases.

Module Contents
Classes

AddReadyEntitiesDialog

A dialog to let the user add new 'ready' multidimensional entities.

AddItemsDialog

A dialog to query user's preferences for new db items.

AddEntityClassesDialog

A dialog to query user's preferences for new entity classes.

AddEntitiesOrManageElementsDialog

A dialog to query user's preferences for new entities.

AddEntitiesDialog

A dialog to query user's preferences for new entities.

ManageElementsDialog

A dialog to query user's preferences for managing entity dimensions.

EntityGroupDialogBase

param parent

data store widget

AddEntityGroupDialog

param parent

data store widget

ManageMembersDialog

param parent

data store widget

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.ManageItemsDialogBase

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

make_table_view()[source]
populate_table_view()[source]
connect_signals()[source]

Connect signals to slots.

_handle_table_view_cell_clicked(row, column)[source]
_handle_table_view_current_changed(current, _previous)[source]
accept()[source]

Collect info from dialog and try to add items.

get_db_map_data()[source]
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
connect_signals()[source]

Connect signals to slots.

remove_selected_rows(checked=True)[source]
all_databases(row)[source]

Returns a list of db names available for a given row. Used by delegates.

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
connect_signals()[source]

Connect signals to slots.

_handle_spin_box_value_changed(i)[source]
insert_column()[source]
remove_column()[source]
_handle_model_data_changed(top_left, bottom_right, roles)[source]

Reimplement in subclasses to handle changes in model data.

accept()[source]

Collect info from dialog and try to add items.

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
abstract make_model()[source]
connect_signals()[source]

Connect signals to slots.

abstract reset_model(index)[source]

Called when relationship_class’s combobox’s index changes. Update relationship_class attribute accordingly and reset model.

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
make_model()[source]
reset_model(index)[source]

Setup model according to current entity_class selected in combobox.

_handle_model_data_changed(top_left, bottom_right, roles)[source]

Reimplement in subclasses to handle changes in model data.

get_db_map_data()[source]
accept()[source]

Collect info from dialog and try to add items.

keys_of_entity_classes_relevant_to_item(item)[source]

Returns a list of entity class keys that contain all the entity classes the selected item is composed of.

Parameters

item (MultiDBTreeItem) – Selected item

Returns

List of relevant entity class keys

Return type

entity_class_keys (list)

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
make_model()[source]
splitter_widgets()[source]
connect_signals()[source]

Connect signals to slots.

reset_entity_class_combo_box(database, relationship_class_key=None)[source]
add_entities(checked=True)[source]
reset_model(index)[source]

Setup model according to current entity class selected in combobox.

resize_window_to_columns(height=None)[source]
accept()[source]

Collect info from dialog and try to add items.

class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.EntityGroupDialogBase(parent, entity_class_item, db_mngr, *db_maps)[source]

Bases: PySide6.QtWidgets.QDialog

Parameters
connect_signals()[source]

Connect signals to slots.

reset_list_widgets(database)[source]
abstract initial_member_ids()[source]
abstract initial_entity_id()[source]
add_members(checked=False)[source]
remove_members(checked=False)[source]
_check_validity()[source]
class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddEntityGroupDialog(parent, entity_class_item, db_mngr, *db_maps)[source]

Bases: EntityGroupDialogBase

Parameters
initial_member_ids()[source]
initial_entity_id()[source]
_check_validity()[source]
accept()[source]
class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.ManageMembersDialog(parent, entity_item, db_mngr, *db_maps)[source]

Bases: EntityGroupDialogBase

Parameters
_entity_groups()[source]
initial_member_ids()[source]
initial_entity_id()[source]
accept()[source]
spinetoolbox.spine_db_editor.widgets.commit_viewer

Contains the CommitViewer class.

Module Contents
Classes

_DBCommitViewer

_CommitItem

A widget to show commit message, author and data on a QTreeWidget.

_AffectedItemsFromOneTable

A widget to show all the items from one table that are affected by a commit.

CommitViewer

param qsettings

class spinetoolbox.spine_db_editor.widgets.commit_viewer._DBCommitViewer(db_mngr, db_map, parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

_select_commit(current, previous)[source]
_do_select_commit(current)[source]
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.

class spinetoolbox.spine_db_editor.widgets.commit_viewer._AffectedItemsFromOneTable(items, parent=None)[source]

Bases: PySide6.QtWidgets.QTreeWidget

A widget to show all the items from one table that are affected by a commit.

moveEvent(ev)[source]
sizeHint()[source]
class spinetoolbox.spine_db_editor.widgets.commit_viewer.CommitViewer(qsettings, db_mngr, *db_maps, parent=None)[source]

Bases: PySide6.QtWidgets.QMainWindow

Parameters
  • qsettings (QSettings) –

  • db_mngr (SpineDBManager) –

  • db_maps (DiffDatabaseMapping) –

_carry_splitter_state(index)[source]
closeEvent(ev)[source]
spinetoolbox.spine_db_editor.widgets.custom_delegates

Custom item delegates.

Module Contents
Classes

PivotTableDelegateMixin

A mixin that fixes Pivot table's header table editor position.

RelationshipPivotTableDelegate

A mixin that fixes Pivot table's header table editor position.

ScenarioAlternativeTableDelegate

A mixin that fixes Pivot table's header table editor position.

ParameterPivotTableDelegate

A mixin that fixes Pivot table's header table editor position.

ParameterValueElementDelegate

Delegate for Array and Map editors' table cells.

TableDelegate

Base class for all custom stacked table delegates.

DatabaseNameDelegate

A delegate for the database name.

ParameterValueOrDefaultValueDelegate

A delegate for either the value or the default value.

ParameterDefaultValueDelegate

A delegate for the default value.

ParameterValueDelegate

A delegate for the parameter_value.

ValueListDelegate

A delegate for the parameter value list.

EntityClassNameDelegate

A delegate for the object_class name.

ParameterNameDelegate

A delegate for the object parameter name.

EntityBynameDelegate

A delegate for the entity byname.

AlternativeNameDelegate

A delegate for the alternative name.

BooleanValueDelegate

Base class for all custom stacked table delegates.

AlternativeDelegate

A delegate for the alternative tree.

ScenarioDelegate

A delegate for the scenario tree.

ParameterValueListDelegate

A delegate for the parameter value list tree.

ManageItemsDelegate

A custom delegate for the model in {Add/Edit}ItemDialogs.

ManageEntityClassesDelegate

A delegate for the model and view in {Add/Edit}EntityClassesDialog.

ManageEntitiesDelegate

A delegate for the model and view in {Add/Edit}EntitiesDialog.

RemoveEntitiesDelegate

A delegate for the model and view in RemoveEntitiesDialog.

ItemMetadataDelegate

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.

updateEditorGeometry(editor, option, index)[source]

Fixes position of header table editors.

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

data_committed[source]
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

setModelData(editor, model, index)[source]

Send signal.

setEditorData(editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

paint(painter, option, index)[source]

Paint a checkbox without the label.

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.

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.

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

data_committed[source]
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

setModelData(editor, model, index)[source]

Send signal.

setEditorData(editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

paint(painter, option, index)[source]

Paint a checkbox without the label.

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.

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.

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

parameter_value_editor_requested[source]
data_committed[source]
setModelData(editor, model, index)[source]

Send signal.

setEditorData(editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

createEditor(parent, option, index)[source]
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

createEditor(parent, option, index)[source]

Creates an editor widget or emits value_editor_requested for complex values.

Parameters
  • parent (QWidget) – parent widget

  • option (QStyleOptionViewItem) – unused

  • index (QModelIndex) – element’s model index

Returns

editor widget

Return type

ParameterValueLineEditor

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

SpineDBManager

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

data_committed[source]
setModelData(editor, model, index)[source]

Send signal.

setEditorData(editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

updateEditorGeometry(editor, option, index)[source]
_close_editor(editor, index)[source]

Closes editor. Needed by SearchBarEditor.

_get_db_map(index)[source]

Returns the db_map for the database at given index or None if not set yet.

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

createEditor(parent, option, index)[source]

Returns editor.

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

parameter_value_editor_requested[source]
setModelData(editor, model, index)[source]

Send signal.

_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

ParameterValueLineEditor

abstract _get_value_list_id(index, db_map)[source]

Returns a value list id for the given index and db_map.

Parameters
  • index (QModelIndex) – value list’s index

  • db_map (DiffDatabaseMapping) – database mapping

Returns

value list id

Return type

int

createEditor(parent, option, index)[source]

If the parameter has associated a value list, returns a SearchBarEditor. Otherwise returns or requests a dedicated parameter_value editor.

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

_get_value_list_id(index, db_map)[source]

See base class

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

_get_value_list_id(index, db_map)[source]

See base class.

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

createEditor(parent, option, index)[source]

Returns editor.

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

createEditor(parent, option, index)[source]

Returns editor.

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

createEditor(parent, option, index)[source]

Returns editor.

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

element_name_list_editor_requested[source]
createEditor(parent, option, index)[source]

Returns editor.

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

createEditor(parent, option, index)[source]

Returns editor.

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

SpineDBManager

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

setModelData(editor, model, index)[source]

Send signal.

createEditor(parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.AlternativeDelegate[source]

Bases: PySide6.QtWidgets.QStyledItemDelegate

A delegate for the alternative tree.

data_committed[source]
setModelData(editor, model, index)[source]

Send signal.

setEditorData(editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

createEditor(parent, option, index)[source]

Returns editor.

_close_editor(editor, index)[source]

Closes editor.

Needed by SearchBarEditor.

Parameters
  • editor (QWidget) – editor widget

  • index (QModelIndex) – index that is being edited

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

data_committed[source]
setModelData(editor, model, index)[source]

Send signal.

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

createEditor(parent, option, index)[source]

Returns editor.

updateEditorGeometry(editor, option, index)[source]
_close_editor(editor, index)[source]

Closes editor.

Needed by SearchBarEditor.

Parameters
  • editor (QWidget) – editor widget

  • index (QModelIndex) – index that is being edited

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueListDelegate[source]

Bases: PySide6.QtWidgets.QStyledItemDelegate

A delegate for the parameter value list tree.

data_committed[source]
parameter_value_editor_requested[source]
setModelData(editor, model, index)[source]

Send signal.

setEditorData(editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

createEditor(parent, option, index)[source]

Returns editor.

_close_editor(editor, index)[source]

Closes editor.

Needed by SearchBarEditor.

Parameters
  • editor (QWidget) – editor widget

  • index (QModelIndex) – index that is being edited

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageItemsDelegate[source]

Bases: PySide6.QtWidgets.QStyledItemDelegate

A custom delegate for the model in {Add/Edit}ItemDialogs.

data_committed[source]
setModelData(editor, model, index)[source]

Send signal.

close_editor(editor, index)[source]

Closes editor.

Needed by SearchBarEditor.

Parameters
  • editor (QWidget) – editor widget

  • index (QModelIndex) – index that is being edited

updateEditorGeometry(editor, option, index)[source]
connect_editor_signals(editor, index)[source]

Connect editor signals if necessary.

Parameters
  • editor (QWidget) – editor widget

  • index (QModelIndex) – index being edited

_create_database_editor(parent, index)[source]

Creates an editor.

Parameters
  • parent (QWidget) – parent widget

  • index (QModelIndex) – index being edited

Returns

editor

Return type

QWidget

createEditor(parent, option, index)[source]

Returns an editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageEntityClassesDelegate[source]

Bases: ManageItemsDelegate

A delegate for the model and view in {Add/Edit}EntityClassesDialog.

icon_color_editor_requested[source]
paint(painter, option, index)[source]

Get a pixmap from the index data and paint it in the middle of the cell.

createEditor(parent, option, index)[source]

Return editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageEntitiesDelegate[source]

Bases: ManageItemsDelegate

A delegate for the model and view in {Add/Edit}EntitiesDialog.

createEditor(parent, option, index)[source]

Return editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.RemoveEntitiesDelegate[source]

Bases: ManageItemsDelegate

A delegate for the model and view in RemoveEntitiesDialog.

createEditor(parent, option, index)[source]

Return editor.

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 column

  • parent (QObject, optional) – parent object

createEditor(parent, option, index)[source]
spinetoolbox.spine_db_editor.widgets.custom_menus

Classes for custom context menus and pop-up menus.

Module Contents
Classes

MainMenu

AutoFilterMenu

Filter menu.

TabularViewFilterMenu

Filter menu to use together with FilterWidget in TabularViewMixin.

class spinetoolbox.spine_db_editor.widgets.custom_menus.MainMenu[source]

Bases: PySide6.QtWidgets.QMenu

event(ev)[source]

Intercepts shortcuts and instead sends an equivalent event with the ‘Alt’ modifier, so that mnemonics works with just the key. Also sends a key press event with the ‘Alt’ key when this menu shows, so that mnemonics are underlined on Windows.

class spinetoolbox.spine_db_editor.widgets.custom_menus.AutoFilterMenu(parent, db_mngr, db_maps, item_type, field, show_empty=True)[source]

Bases: spinetoolbox.widgets.custom_menus.FilterMenuBase

Filter menu.

Parameters
  • parent (SpineDBEditor) –

  • db_mngr (SpineDBManager) –

  • db_maps (Sequence of DatabaseMapping) –

  • item_type (str) –

  • field (str) – the field name

filterChanged[source]
set_filter_accepted_values(accepted_values)[source]
set_filter_rejected_values(rejected_values)[source]
_get_value(item, db_map)[source]
_get_display_value(item, db_map)[source]
_handle_items_added(db_map_data)[source]
_handle_items_removed(db_map_data)[source]
_build_auto_filter(valid_values)[source]

Builds the auto filter given valid values.

Parameters

valid_values (Sequence) – Values accepted by the filter.

Returns

mapping (db_map, entity_class_id) to set of valid values

Return type

dict

emit_filter_changed(valid_values)[source]

Builds auto filter and emits signal.

Parameters

valid_values (Sequence) – Values accepted by the filter.

class spinetoolbox.spine_db_editor.widgets.custom_menus.TabularViewFilterMenu(parent, db_mngr, db_maps, item_type, accepts_item, identifier, show_empty=True)[source]

Bases: spinetoolbox.widgets.custom_menus.FilterMenuBase

Filter menu to use together with FilterWidget in TabularViewMixin.

Parameters
  • parent (SpineDBEditor) –

  • db_mngr (SpineDBManager) –

  • db_maps (Sequence of DatabaseMapping) –

  • item_type (str) –

  • accepts_item (function) –

  • identifier (int) – index identifier

filterChanged[source]
_handle_items_added(db_map_data)[source]
_get_values(db_map, item)[source]
_handle_items_removed(db_map_data)[source]
emit_filter_changed(valid_values)[source]
event(event)[source]
spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews

Classes for custom QGraphicsViews for the Entity graph view.

Module Contents
Classes

_GraphProperty

_GraphBoolProperty

_GraphIntProperty

EntityQGraphicsView

QGraphicsView for the Entity Graph View.

class spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews._GraphProperty(name, settings_name)[source]
property value[source]
connect_spine_db_editor(spine_db_editor)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews._GraphBoolProperty(*args, **kwargs)[source]

Bases: _GraphProperty

_set_value(_checked=False, save_setting=True)[source]
set_value(checked)[source]
update(menu)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews._GraphIntProperty(min_value, max_value, default_value, *args, **kwargs)[source]

Bases: _GraphProperty

_set_value(_value=None, save_setting=True)[source]
set_value(value)[source]
update(menu)[source]
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)

property _qsettings[source]
property db_mngr[source]
property entity_items[source]
graph_selection_changed[source]
get_property(name)[source]
set_property(name, value)[source]
get_all_properties()[source]
set_many_properties(props)[source]
handle_scene_selection_changed()[source]

Filters parameters by selected objects in the graph.

connect_spine_db_editor(spine_db_editor)[source]
populate_context_menu()[source]
_update_actions_visibility()[source]

Enables or disables actions according to current selection in the graph.

make_items_menu()[source]
_save_state()[source]
_load_state(action)[source]
_remove_state(action)[source]
_find()[source]
increase_arc_length()[source]
decrease_arc_length()[source]
add_entities_at_position(checked=False)[source]
edit_selected(_=False)[source]

Edits selected items.

remove_selected(_=False)[source]

Removes selected items.

_get_selected_entity_names()[source]
hide_selected_items(checked=False)[source]

Hides selected items.

_hide_class(action)[source]

Hides some class.

show_all_hidden_items(checked=False)[source]

Shows all hidden items.

show_hidden_items(action)[source]

Shows some hidden items.

prune_selected_items(checked=False)[source]

Prunes selected items.

_prune_class(action)[source]

Prunnes some class.

restore_all_pruned_items(checked=False)[source]

Reinstates all pruned items.

restore_pruned_items(action)[source]

Reinstates some pruned items.

select_graph_parameters(checked=False)[source]
_set_graph_parameters(name_parameter, pos_x_parameter, pos_y_parameter, color_parameter, arc_width_parameter)[source]
_save_selected_positions(checked=False)[source]
_save_all_positions(checked=False)[source]
_save_positions(items)[source]
_clear_selected_positions(checked=False)[source]
_clear_all_positions(checked=False)[source]
_clear_positions(items)[source]
_select_bg_image(_checked=False)[source]
set_bg_svg(svg)[source]
get_bg_svg()[source]
set_bg_rect(rect)[source]
get_bg_rect()[source]
clear_scene()[source]
_no_zoom()[source]
export_as_image(_=False)[source]
_do_export_as_image(file_path)[source]
_get_print_source(scene=None)[source]
_print_scene(printer, source, size, index=None, scene=None)[source]
_clone_scene()[source]
_frames(start, stop, frame_count, buffer_path, cv2)[source]
export_as_video()[source]
_do_export_as_video(file_path, start, stop, frame_count, fps, cv2)[source]
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)) –

clear_cross_hairs_items()[source]
_cross_hairs_has_valid_target()[source]
mousePressEvent(event)[source]

Handles relationship creation if one it’s in process.

mouseMoveEvent(event)[source]

Updates the hovered object item if we’re in entity creation mode.

_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

mouseReleaseEvent(event)[source]

Reestablish scroll hand drag mode.

_scroll_scene_by(dx, dy)[source]
keyPressEvent(event)[source]

Aborts relationship creation if user presses ESC.

contextMenuEvent(e)[source]

Shows context menu.

Parameters

e (QContextMenuEvent) – Context menu event

_compute_max_zoom()[source]
_use_smooth_zoom()[source]
_zoom(factor)[source]
apply_zoom()[source]
wheelEvent(event)[source]

Zooms in/out. If user has pressed the shift key, rotates instead.

Parameters

event (QWheelEvent) – Mouse wheel event

_handle_rotation_time_line_advanced(pos)[source]

Performs rotation whenever the smooth rotation time line advances.

_rotate(angle)[source]
rotate_clockwise()[source]

Performs a rotate clockwise with fixed angle.

rotate_anticlockwise()[source]

Performs a rotate anticlockwise with fixed angle.

spinetoolbox.spine_db_editor.widgets.custom_qtableview

Custom QTableView classes that support copy-paste and the like.

Module Contents
Classes

StackedTableView

Base stacked view.

ParameterTableView

Base stacked view.

ParameterDefinitionTableView

Base stacked view.

ParameterValueTableView

Base stacked view.

EntityAlternativeTableView

Visualize entities and their alternatives.

PivotTableView

Custom QTableView class with pivot capabilities.

FrozenTableView

MetadataTableViewBase

Base for metadata and item metadata table views.

MetadataTableView

Table view for metadata.

ItemMetadataTableView

Table view for entity and parameter value metadata.

Functions

_set_data(index, new_value)

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_qwidgets.ResizingViewMixin, spinetoolbox.widgets.custom_qtableview.AutoFilterCopyPasteTableView

Base stacked view.

Parameters

parent (QObject) – parent object

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
Returns

TableDelegate

create_delegates()[source]

Creates delegates for this view

populate_context_menu()[source]

Creates a context menu for this view.

contextMenuEvent(event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

_selected_rows_per_column()[source]

Computes selected rows per column.

Returns

Mapping columns to selected rows in that column.

Return type

dict

filter_by_selection(checked=False)[source]
filter_excluding_selection(checked=False)[source]
remove_selected()[source]

Removes selected indexes.

_do_resize()[source]
_refresh_copy_paste_actions(_, __)[source]

Enables or disables copy and paste actions.

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterTableView(parent)[source]

Bases: StackedTableView

Base stacked view.

Parameters

parent (QObject) – parent object

value_column_header: str[source]

Either “default value” or “value”. Used to identify the value column for advanced editing and plotting.

populate_context_menu()[source]

Creates a context menu for this view.

contextMenuEvent(event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

open_in_editor()[source]

Opens the current index in a parameter_value editor using the connected Spine db editor.

plot(checked=False)[source]

Plots current index.

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

PlotWidget

plot_in_window(action)[source]

Plots current index in the window given by action’s name.

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterDefinitionTableView(parent)[source]

Bases: ParameterTableView

Base stacked view.

Parameters

parent (QObject) – parent object

value_column_header = 'default_value'[source]
create_delegates()[source]

Creates delegates for this view

_plot_selection(selection, plot_widget=None)[source]

See base class

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterValueTableView(parent)[source]

Bases: ParameterTableView

Base stacked view.

Parameters

parent (QObject) – parent object

property _pk_fields[source]
value_column_header = 'value'[source]
connect_spine_db_editor(spine_db_editor)[source]

Connects a Spine db editor to work with this view.

Parameters

spine_db_editor (SpineDBEditor) –

create_delegates()[source]

Creates delegates for this view

_update_pinned_values(_selected, _deselected)[source]
_make_pinned_value(index)[source]
_plot_selection(selection, plot_widget=None)[source]

See base class.

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.EntityAlternativeTableView(parent)[source]

Bases: StackedTableView

Visualize entities and their alternatives.

Parameters

parent (QObject) – parent object

create_delegates()[source]

Creates delegates for this view

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.PivotTableView(parent=None)[source]

Bases: spinetoolbox.widgets.custom_qwidgets.ResizingViewMixin, 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

_REMOVE_ENTITY = 'Remove entities'[source]
_REMOVE_PARAMETER = 'Remove parameter definitions'[source]
_REMOVE_ALTERNATIVE = 'Remove alternatives'[source]
_REMOVE_SCENARIO = 'Remove scenarios'[source]
_DUPLICATE_SCENARIO = 'Duplicate scenario'[source]
_clear_selection_lists()[source]

Clears cached selected index lists.

abstract populate_context_menu()[source]

Generates context menu.

_refresh_selected_indexes()[source]

Caches selected index lists.

remove_alternatives()[source]

Removes selected alternatives from the database.

show_context_menu(position)[source]

Shows the context menu.

_to_selection_lists(index)[source]

Caches given index to corresponding selected index list.

Parameters

index (QModelIndex) – index to cache

abstract _update_actions_availability()[source]

Enables/disables context menu entries before the menu is shown.

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

_clear_selection_lists()[source]

See base class.

abstract populate_context_menu()[source]

See base class.

remove_entities()[source]

Removes selected entities from the database.

abstract _update_actions_availability()[source]

See base class.

class _ParameterValueContext(view, db_editor)[source]

Bases: PivotTableView._EntityContextBase

Context for showing parameter values in the pivot table.

Parameters
_clear_selection_lists()[source]

See base class.

populate_context_menu()[source]

See base class.

open_in_editor()[source]

Opens the parameter value editor for the first selected cell.

plot()[source]

Plots the selected cells.

_plot_in_window(action)[source]

Plots the selected cells in an existing window.

remove_parameters()[source]

Removes selected parameter definitions from the database.

remove_values()[source]

Removes selected parameter values from the database.

show_context_menu(position)[source]

Shows the context menu.

_to_selection_lists(index)[source]

See base class.

_update_actions_availability()[source]

See base class.

class _IndexExpansionContext(view, db_editor)[source]

Bases: PivotTableView._ParameterValueContext

Context for expanded parameter values

Parameters
class _ElementContext(view, db_editor)[source]

Bases: PivotTableView._EntityContextBase

Context for presenting relationships in the pivot table.

Parameters
populate_context_menu()[source]

See base class.

_update_actions_availability()[source]

See base class.

class _ScenarioAlternativeContext(view, db_editor)[source]

Bases: PivotTableView._ContextBase

Context for presenting scenarios and alternatives

Parameters
_clear_selection_lists()[source]

See base class.

populate_context_menu()[source]

See base class.

remove_scenarios()[source]

Removes selected scenarios from the database.

duplicate_scenario()[source]

Duplicates current scenario in the database.

_to_selection_lists(index)[source]

See base class.

_update_actions_availability()[source]

See base class.

_open_scenario_generator()[source]

Opens the scenario generator dialog.

_toggle_checked_state()[source]

Toggles the checked state of selected alternatives.

property source_model[source]
property db_mngr[source]
header_changed[source]
_do_resize()[source]
connect_spine_db_editor(spine_db_editor)[source]
_change_context()[source]

Changes the UI engine according to pivot model type.

contextMenuEvent(event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

setModel(model)[source]
_synch_selection_with_header_tables(selected, deselected)[source]
setIndexWidget(proxy_index, widget)[source]
setHorizontalHeader(horizontal_header)[source]
setVerticalHeader(vertical_header)[source]
resizeEvent(ev)[source]
_fetch_more_visible()[source]
_update_header_tables()[source]
_update_section_width(logical_index, _old_size, new_size)[source]
_update_section_height(logical_index, _old_size, new_size)[source]
_update_header_tables_geometry()[source]
_refresh_copy_paste_actions(_, __)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtableview.FrozenTableView[source]

Bases: PySide6.QtWidgets.QTableView

property area[source]
header_dropped[source]
dragEnterEvent(event)[source]
dragMoveEvent(event)[source]
dropEvent(event)[source]
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

contextMenuEvent(event)[source]
_remove_selected()[source]

Removes selected rows from view’s model.

_enable_delegates(db_editor)[source]

Creates delegates for this view

Parameters

db_editor (SpineDBEditor) – database editor

_populate_context_menu()[source]

Fills context menu with actions.

_set_model_data(index, value)[source]

Sets model data.

Parameters
  • index (QModelIndex) – model index to set

  • value (str) – value

_refresh_copy_paste_actions()[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtableview.MetadataTableView(parent)[source]

Bases: MetadataTableViewBase

Table view for metadata.

Parameters

parent (QWidget, optional) – parent widget

_enable_delegates(db_editor)[source]

See base class.

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

_enable_delegates(db_editor)[source]

See base class

spinetoolbox.spine_db_editor.widgets.custom_qtreeview

Classes for custom QTreeView.

Module Contents
Classes

ResizableTreeView

Custom QTreeView class with copy and paste support.

EntityTreeView

Tree view base class for object and relationship tree views.

ItemTreeView

Base class for all non-entity tree views.

AlternativeTreeView

Custom QTreeView for the alternative tree in SpineDBEditor.

ScenarioTreeView

Custom QTreeView for the scenario tree in SpineDBEditor.

ParameterValueListTreeView

Custom QTreeView class for parameter_value_list in SpineDBEditor.

class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ResizableTreeView(*args, **kwargs)[source]

Bases: spinetoolbox.widgets.custom_qwidgets.ResizingViewMixin, spinetoolbox.widgets.custom_qtreeview.CopyPasteTreeView

Custom QTreeView class with copy and paste support.

_do_resize()[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.EntityTreeView(parent)[source]

Bases: ResizableTreeView

Tree view base class for object and relationship tree views.

Parameters

parent (QWidget) – parent widget

tree_selection_changed[source]
reset()[source]
connect_spine_db_editor(spine_db_editor)[source]

Connects a Spine db editor to work with this view.

Parameters

spine_db_editor (SpineDBEditor) –

_add_middle_actions()[source]
_create_context_menu()[source]

Creates a context menu for this view.

toggle_hide_empty_classes()[source]
edit(index, trigger, event)[source]

Edit all selected items.

connect_signals()[source]

Connects signals.

rowsInserted(parent, start, end)[source]
rowsRemoved(parent, start, end)[source]
setModel(model)[source]
_fetch_more_visible()[source]
verticalScrollbarValueChanged(value)[source]
_handle_selection_changed(selected, deselected)[source]

Classifies selection by item type and emits signal.

_refresh_selected_indexes()[source]
clear_any_selections()[source]

Clears the selection if any.

fully_expand()[source]

Expands selected indexes and all their children.

fully_collapse()[source]

Collapses selected indexes and all their children.

export_selected()[source]

Exports data from selected indexes using the connected Spine db editor.

remove_selected()[source]

Removes selected indexes using the connected Spine db editor.

contextMenuEvent(event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

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.

edit_selected()[source]

Edits all selected indexes using the connected Spine db editor.

add_entity_classes()[source]
add_entities()[source]
find_next_entity()[source]

Finds the next occurrence of the relationship at the current index and expands it.

_do_find_next_entity()[source]
duplicate_entity()[source]

Duplicates the object at the current index using the connected Spine db editor.

add_entity_group()[source]
manage_elements()[source]
manage_members()[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ItemTreeView(parent)[source]

Bases: ResizableTreeView

Base class for all non-entity tree views.

Parameters

parent (QWidget) – parent widget

rowsInserted(parent, start, end)[source]
connect_signals()[source]

Connects signals.

abstract remove_selected()[source]

Removes items selected in the view.

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

populate_context_menu()[source]

Creates a context menu for this view.

contextMenuEvent(event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

_refresh_copy_paste_actions(_, __)[source]

Refreshes copy and paste actions enabled state.

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

property selected_alternative_ids[source]
alternative_selection_changed[source]
reset()[source]
connect_signals()[source]

Connects signals.

connect_spine_db_editor(spine_db_editor)[source]

see base class

populate_context_menu()[source]

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

_handle_selection_changed(selected, deselected)[source]

Emits alternative_selection_changed with the current selection.

remove_selected()[source]

See base class.

update_actions_availability(item)[source]

See base class.

_open_scenario_generator()[source]

Opens the scenario generator dialog.

can_copy()[source]

See base class.

can_paste()[source]

See base class.

copy()[source]

See base class.

paste()[source]

Pastes alternatives from clipboard to the tree.

This makes sense only when pasting alternatives from one database to another.

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

property selected_alternative_ids[source]
scenario_selection_changed[source]
reset()[source]
connect_signals()[source]

Connects signals.

connect_spine_db_editor(spine_db_editor)[source]

see base class

populate_context_menu()[source]

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

_handle_selection_changed(selected, deselected)[source]

Emits scenario_selection_changed with the current selection.

remove_selected()[source]

See base class.

dragMoveEvent(event)[source]
dragEnterEvent(event)[source]
update_actions_availability(item)[source]

See base class

copy()[source]

See base class.

can_paste()[source]

See base class.

paste()[source]

Pastes alternatives and scenarios from clipboard to the tree.

_duplicate_scenario()[source]

Duplicates selected scenarios.

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

connect_spine_db_editor(spine_db_editor)[source]

see base class

populate_context_menu()[source]

Creates a context menu for this view.

update_actions_availability(item)[source]

See base class.

open_in_editor()[source]

Opens the parameter_value editor for the first selected cell.

remove_selected()[source]

See base class.

spinetoolbox.spine_db_editor.widgets.custom_qwidgets

Custom QWidgets.

Module Contents
Classes

OpenFileButton

A button to open files or show them in the folder.

OpenSQLiteFileButton

A button to open sqlite files, show them in the folder, or add them to the project.

ShootingLabel

ProgressBarWidget

TimeLineWidget

LegendWidget

ExportAsVideoDialog

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.

set_progress(progress)[source]
open_file(checked=False)[source]
open_containing_folder(checked=False)[source]
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.

open_file(checked=False)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.ShootingLabel(origin, destination, parent=None, duration=1200)[source]

Bases: PySide6.QtWidgets.QLabel

_handle_value_changed(value)[source]
show()[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.ProgressBarWidget(parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

set_layout_generator(layout_generator)[source]
paintEvent(event)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.TimeLineWidget(parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

index_changed[source]
_STEP_COUNT = 10000[source]
_refresh_button_icon()[source]
_play_pause()[source]
_handle_value_changed(value)[source]
set_index_range(min_index, max_index)[source]
get_index_range()[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.LegendWidget(parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

_BASE_HEIGHT = 30[source]
_SPACING = 6[source]
set_legend(legend)[source]
static _paint_color_bar(painter, cell)[source]
static _paint_volume_bar(painter, cell)[source]
paintEvent(ev)[source]
paint(painter, rect)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.ExportAsVideoDialog(start, stop, parent=None)[source]

Bases: PySide6.QtWidgets.QDialog

_handle_start_dt_changed(start_dt)[source]
_handle_stop_dt_changed(stop_dt)[source]
selections()[source]
spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs

Classes for custom QDialogs to edit items in databases.

Module Contents
Classes

EditOrRemoveItemsDialog

A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all

EditEntityClassesDialog

A dialog to query user's preferences for updating entity classes.

EditEntitiesDialog

A dialog to query user's preferences for updating entities.

RemoveEntitiesDialog

A dialog to query user's preferences for removing tree items.

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.

Init class.

Parameters
all_databases(row)[source]

Returns a list of db names available for a given row. Used by delegates.

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.

Init class.

Parameters
  • parent (SpineDBEditor) – data store widget

  • db_mngr (SpineDBManager) – the manager to do the update

  • selected (set) – set of EntityClassItem instances to edit

connect_signals()[source]

Connect signals to slots.

accept()[source]

Collect info from dialog and try to update items.

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.

Init class.

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) – (class_name, dimension_name_list) for identifying the entity class

accept()[source]

Collect info from dialog and try to update items.

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.

Init class.

Parameters
  • parent (SpineDBEditor) – data store widget

  • db_mngr (SpineDBManager) – the manager to do the removal

  • selected (dict) – maps item type (class) to instances

accept()[source]

Collect info from dialog and try to remove items.

spinetoolbox.spine_db_editor.widgets.element_name_list_editor

Contains the ObjectNameListEditor class.

Module Contents
Classes

SearchBarDelegate

A custom delegate to use with ElementNameListEditor.

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.

data_committed[source]
setModelData(editor, model, index)[source]
createEditor(parent, option, index)[source]
updateEditorGeometry(editor, option, index)[source]
close_editor(editor, index, model)[source]
eventFilter(editor, event)[source]
class spinetoolbox.spine_db_editor.widgets.element_name_list_editor.ElementNameListEditor(parent, index, entity_class_names, element_name_lists, current_element_names)[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.

Initializes widget.

Parameters
  • parent (SpineDBEditor) –

  • index (QModelIndex) –

  • entity_class_names (list) – string entity_class names

  • element_name_lists (list) – lists of string element names

  • current_element_names (list) –

init_model(entity_class_names, element_name_lists, current_element_names)[source]
accept()[source]
spinetoolbox.spine_db_editor.widgets.graph_layout_generator

Contains the GraphLayoutGeneratorRunnable class.

Module Contents
Classes

GraphLayoutGeneratorRunnable

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.

class Signals[source]

Bases: PySide6.QtCore.QObject

finished[source]
layout_available[source]
progressed[source]
stop(_checked=False)[source]
set_show_previews(checked)[source]
_is_stopped()[source]
_layout_progressed(iteration)[source]
_layout_available(x, y)[source]
_preview_available(x, y)[source]
run()[source]
spinetoolbox.spine_db_editor.widgets.graph_view_mixin

Contains the GraphViewMixin class.

Module Contents
Classes

GraphViewMixin

Provides the graph view for the DB editor.

_Offset

Functions

_min_value(pv)

_max_value(pv)

_get_value(pv, index)

_min_max(pvs)

_min_max_indexes(pvs)

spinetoolbox.spine_db_editor.widgets.graph_view_mixin._min_value(pv)[source]
spinetoolbox.spine_db_editor.widgets.graph_view_mixin._max_value(pv)[source]
spinetoolbox.spine_db_editor.widgets.graph_view_mixin._get_value(pv, index)[source]
spinetoolbox.spine_db_editor.widgets.graph_view_mixin._min_max(pvs)[source]
spinetoolbox.spine_db_editor.widgets.graph_view_mixin._min_max_indexes(pvs)[source]
class spinetoolbox.spine_db_editor.widgets.graph_view_mixin.GraphViewMixin(*args, **kwargs)[source]

Provides the graph view for the DB editor.

NOT_SPECIFIED[source]
_VERTEX_EXTENT = 64[source]
_ARC_WIDTH[source]
_ARC_LENGTH_HINT[source]
_update_time_line_index(index)[source]
_graph_fetch_more_later(entity=True, parameter_value=True)[source]
_graph_fetch_more(entity=True, parameter_value=True)[source]
_graph_fetch_more_parameter_value()[source]
_graph_fetch_more_entity()[source]
init_models()[source]
connect_signals()[source]

Connects signals.

_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.

_all_pruned_db_map_entity_ids()[source]
_accepts_entity_item(item, db_map)[source]
_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.

_db_map_ids_by_key(db_map_data)[source]
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

_graph_handle_parameter_values_added(db_map_data)[source]
polish_items()[source]
_update_property_pvs()[source]
_handle_entity_graph_visibility_changed(visible)[source]
_handle_entity_tree_selection_changed_in_graph(selected)[source]

Stores the given selection of entity tree indexes and builds graph.

expand_graph(db_map_entity_ids)[source]
collapse_graph(db_map_entity_ids)[source]
prune_graph(key, db_map_entity_ids)[source]
restore_graph(key=None)[source]
_get_db_map_graph_data()[source]
save_graph_data(name)[source]
overwrite_graph_data(db_map_graph_data)[source]
get_db_map_graph_data_by_name()[source]
load_graph_data(db_map_graph_data)[source]
remove_graph_data(name)[source]
rebuild_graph(_checked=False)[source]
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.

_do_build_graph()[source]
_stop_layout_generators()[source]
_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_db_map_entities_for_graph()[source]
_update_graph_data()[source]

Updates data for graph according to selection in trees.

get_entity_key(db_map_entity_id)[source]
_update_entity_element_inds(db_map_element_id_lists)[source]
_get_pv(db_map, entity_id, pname)[source]
get_item_name(db_map, entity_id)[source]
get_item_color(db_map, entity_id, time_line_index)[source]
get_arc_width(db_map, entity_id, time_line_index)[source]
_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

_get_fixed_pos(db_map, entity_id)[source]
_make_layout_generator()[source]

Returns a layout generator for the current graph.

Returns

GraphLayoutGeneratorRunnable

static convert_position(x, y)[source]
_get_entity_offset(db_map_entity_ids)[source]
_make_new_items(x, y)[source]

Returns new items for the graph.

Parameters
  • x (list) –

  • y (list) –

_add_new_items()[source]
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) –

finalize_connecting_entities(entity_class, *entity_items)[source]

Tries to add multi dimensional entity with the given entity items as elements.

Parameters
  • entity_class (dict) –

  • entity_items (..graphics_items.EntityItem) –

_do_finalize_connecting_entities(dialog, element_items)[source]
add_entities_at_position(pos)[source]
_do_add_entites_at_pos(dialog, x, y)[source]
_add_entities_from_dialog(dialog)[source]
get_save_file_path(group, caption, filters)[source]
get_open_file_path(group, caption, filters)[source]
closeEvent(event)[source]

Handle close window.

Parameters

event (QCloseEvent) – Closing event

class spinetoolbox.spine_db_editor.widgets.graph_view_mixin._Offset(all_offsets)[source]
value()[source]
spinetoolbox.spine_db_editor.widgets.item_metadata_editor

Contains machinery to deal with item metadata editor.

Module Contents
Classes

ItemMetadataEditor

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
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

_reload_entity_metadata(current_index, previous_index)[source]

Loads entity metadata for selected object or relationship.

Parameters
  • current_index (QModelIndex) – currently selected index in object/relationship tree

  • previous_index (QModelIndex) – unused

_reload_value_metadata(current_index, previous_index)[source]

Loads parameter value metadata for selected value.

Parameters
  • current_index (QModelIndex) – currently selected index in object/relationship parameter value table

  • previous_index (QModelIndex) – unused

spinetoolbox.spine_db_editor.widgets.manage_items_dialogs

Classes for custom QDialogs to add edit and remove database items.

Module Contents
Classes

ManageItemsDialogBase

Init class.

ManageItemsDialog

A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all

GetEntityClassesMixin

Provides a method to retrieve entity classes for AddEntitiesDialog and AddEntityClassesDialog.

GetEntitiesMixin

Provides a method to retrieve entities for AddEntitiesDialog and EditEntitiesDialog.

ShowIconColorEditorMixin

Provides methods to show an IconColorEditor upon request.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialogBase(parent, db_mngr)[source]

Bases: PySide6.QtWidgets.QDialog

Init class.

Parameters
make_table_view()[source]
connect_signals()[source]

Connect signals to slots.

resize_window_to_columns(height=None)[source]
class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialog(parent, db_mngr)[source]

Bases: ManageItemsDialogBase

A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all dialogs to query user’s preferences for adding/editing/managing data items.

Init class.

Parameters
connect_signals()[source]

Connect signals to slots.

_handle_model_data_changed(top_left, bottom_right, roles)[source]

Reimplement in subclasses to handle changes in model data.

set_model_data(index, data)[source]

Update model data.

_handle_model_reset()[source]

Resize columns and form.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntityClassesMixin[source]

Provides a method to retrieve entity classes for AddEntitiesDialog and AddEntityClassesDialog.

make_db_map_ent_cls_lookup()[source]
make_db_map_ent_cls_lookup_by_name()[source]
entity_class_name_list(row)[source]

Return a list of entity class names present in all databases selected for given row. Used by ManageEntityClassesDelegate.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetEntitiesMixin[source]

Provides a method to retrieve entities for AddEntitiesDialog and EditEntitiesDialog.

make_db_map_ent_lookup()[source]
make_db_map_alt_id_lookup()[source]
alternative_name_list(row)[source]

Return a list of alternative names present in all databases selected for given row. Used by ManageEntitiesDelegate.

entity_name_list(row, column)[source]

Return a list of entity names present in all databases selected for given row. Used by ManageEntitiesDelegate.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ShowIconColorEditorMixin[source]

Provides methods to show an IconColorEditor upon request.

show_icon_color_editor(index)[source]
spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs

Classes for custom QDialogs to add edit and remove database items.

Module Contents
Classes

_SelectDatabases

A widget that shows checkboxes for each database.

MassSelectItemsDialog

A dialog to query a selection of dbs and items from the user.

MassRemoveItemsDialog

A dialog to query user's preferences for mass removing db items.

MassExportItemsDialog

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

checked_state_changed[source]
checked_states()[source]

Collects the checked states of databases.

Returns

mapping from database mapping to checked state boolean

Return type

dict

any_checked()[source]

Checks if any of the checkboxes is checked.

Returns

True if any check box is checked, False otherwise

Return type

bool

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

state_storing_requested[source]
_handle_check_box_state_changed(_checked)[source]

Enables or disables the OK button.

accept()[source]
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

accept()[source]
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

_warn_checked_non_data_items = False[source]
data_submitted[source]
accept()[source]
spinetoolbox.spine_db_editor.widgets.metadata_editor

Contains machinery to deal with metadata editor.

Module Contents
Classes

MetadataEditor

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
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

metadata_model()[source]

Returns metadata model.

Returns

model

Return type

MetadataModel

spinetoolbox.spine_db_editor.widgets.multi_spine_db_editor

Contains the MultiSpineDBEditor class.

Module Contents
Classes

MultiSpineDBEditor

Database editor's tabbed main window.

_CustomStatusBar

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

MultiTabWindow

_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)[source]

Creates a new tab.

Parameters
  • *args – positional arguments neede to make a new tab

  • **kwargs – keyword arguments needed to make a new tab

show_plus_button_context_menu(global_pos)[source]

Opens a context menu for the tool bar.

Parameters

global_pos (QPoint) – menu position on screen

make_context_menu(index)[source]

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) –

insert_open_file_button(file_path, progress, is_sqlite)[source]
_open_sqlite_url(url, codename)[source]

Opens sqlite url.

show_user_guide(checked=False)[source]

Opens Spine db editor documentation page in browser.

class spinetoolbox.spine_db_editor.widgets.multi_spine_db_editor._CustomStatusBar(parent=None)[source]

Bases: PySide6.QtWidgets.QStatusBar

spinetoolbox.spine_db_editor.widgets.pivot_table_header_view

Contains custom QHeaderView for the pivot table.

Module Contents
Classes

PivotTableHeaderView

Header view for the pivot table.

ParameterValuePivotHeaderView

Header view for the pivot table in parameter value and index expansion mode.

ScenarioAlternativePivotHeaderView

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

property area[source]
header_dropped[source]
dragEnterEvent(event)[source]
dragMoveEvent(event)[source]
dropEvent(event)[source]
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

_add_column_to_plot(action)[source]

Adds a single column to existing plot window.

_plot_column()[source]

Plots a single column not the selection.

_column_indexes(column)[source]

Makes indexes for given column.

Parameters

column (int) – column

Returns

column indexes

Return type

list of QModelIndex

_set_x_flag()[source]

Sets the X flag for a column.

contextMenuEvent(event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

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

context_menu_requested[source]

Requests a header context menu be shown at given global position.

contextMenuEvent(event)[source]
spinetoolbox.spine_db_editor.widgets.scenario_generator

Contains a dialog for generating scenarios from selected alternatives.

Module Contents
Classes

_ScenarioNameResolution

Generic enumeration.

ScenarioGenerator

A dialog where users can generate scenarios from given alternatives.

Functions

_ensure_unique(scenario_alternatives)

Removes duplicate scenario alternatives.

_find_base_alternative(names)

Returns the name of a 'base' alternative or empty string if not found.

_suffix(item_count)

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.

NO_CONFLICT[source]
OVERWRITE[source]
LEAVE_AS_IS[source]
CANCEL_OPERATION[source]
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

_TYPE_LABELS = ('All combinations', 'Scenario for each alternative')[source]
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

_ScenarioNameResolution

_enable_base_alternative(check_box_state)[source]

Enables and disables base alternative combo box.

Parameters

check_box_state (int) – state of ‘Use base alternative’ check box

_insert_base_alternative(scenario_alternatives)[source]

Prepends base alternative to scenario alternatives if it has been enabled.

If base alternative is already in scenario alternatives, make sure it comes first.

Parameters

scenario_alternatives (list of list) – scenario alternatives

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.

Module Contents
Classes

SelectGraphParametersDialog

ParameterNameDelegate

A delegate for the database name.

class spinetoolbox.spine_db_editor.widgets.select_graph_parameters_dialog.SelectGraphParametersDialog(parent, name_parameter, pos_x_parameter, pos_y_parameter, color_parameter, arc_width_parameter)[source]

Bases: PySide6.QtWidgets.QDialog

selection_made[source]
resize_columns()[source]
accept()[source]
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.

setModelData(editor, model, index)[source]

Send signal.

setEditorData(editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

updateEditorGeometry(editor, option, index)[source]
_close_editor(editor, index)[source]

Closes editor. Needed by SearchBarEditor.

createEditor(parent, option, index)[source]

Returns editor.

spinetoolbox.spine_db_editor.widgets.spine_db_editor

Contains the SpineDBEditor class.

Module Contents
Classes

SpineDBEditorBase

Base class for SpineDBEditor (i.e. Spine database editor).

SpineDBEditor

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

property toolbox[source]
property settings_subgroup[source]
property db_names[source]
property first_db_map[source]
property db_url_codenames[source]
msg[source]
msg_error[source]
file_exported[source]

filepath, progress between 0 and 1, True if sqlite file

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

load_db_urls(db_url_codenames, create=False, update_history=True)[source]
init_add_undo_redo_actions()[source]
load_previous_urls(_=False)[source]
load_next_urls(_=False)[source]
open_db_file(_=False)[source]
add_db_file(_=False)[source]
create_db_file(_=False)[source]
_make_docks_menu()[source]

Returns a menu with all dock toggle/view actions. Called by self.add_main_menu().

Returns

QMenu

add_main_menu()[source]

Adds a menu with main actions to toolbar.

_browse_commits()[source]
connect_signals()[source]

Connects signals to slots.

vacuum(_checked=False)[source]
update_undo_redo_actions(_)[source]
_replace_undo_redo_actions(new_undo_action, new_redo_action)[source]
_refresh_undo_redo_actions()[source]
update_commit_enabled(_clean=False)[source]
init_models()[source]

Initializes models.

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.

copy(checked=False)[source]

Copies data to clipboard.

paste(checked=False)[source]

Pastes data from clipboard.

import_data(data)[source]
import_file(checked=False)[source]

Import file. It supports SQLite, JSON, and Excel.

import_from_json(file_path)[source]
import_from_sqlite(file_path)[source]
import_from_excel(file_path)[source]
show_mass_export_items_dialog(checked=False)[source]

Shows dialog for user to select dbs and items for export.

_store_export_settings(state)[source]

Stores export items dialog settings.

_clean_up_export_items_dialog()[source]

Cleans up export items dialog.

export_session(checked=False)[source]

Exports changes made in the current session.

mass_export_items(db_map_item_types)[source]
duplicate_entity(entity_item)[source]

Duplicates an entity.

Parameters

entity_item (EntityTreeItem of 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

refresh_session(checked=False)[source]
commit_session(checked=False)[source]

Commits dirty database maps.

rollback_session(checked=False)[source]

Rolls back dirty database maps.

receive_session_committed(db_maps, cookie)[source]
receive_session_rolled_back(db_maps)[source]
receive_session_refreshed(db_maps)[source]
show_mass_remove_items_form(checked=False)[source]

Opens the purge items dialog.

_store_purge_settings(state)[source]

Stores Purge items dialog state.

Parameters

state (dict) – dialog state

_clean_up_purge_items_dialog()[source]

Removes references to purge items dialog.

show_parameter_value_editor(index, plain=False)[source]

Shows the parameter_value editor for the given index of given table view.

receive_error_msg(db_map_error_log)[source]
_update_export_enabled()[source]

Update export enabled.

_log_items_change(msg)[source]

Enables or disables actions and informs the user about what just happened.

_handle_items_added(item_type, db_map_data)[source]
_handle_items_updated(item_type, db_map_data)[source]
_handle_items_removed(item_type, db_map_data)[source]
restore_ui()[source]

Restore UI state from previous session.

save_window_state()[source]

Save window state parameters (size, position, state) via QSettings.

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

_get_rollback_confirmation(db_names)[source]

Prompts user for confirmation before rolling back the session.

Parameters

db_names (Iterable of str) – database names

Returns

True if user confirmed, False otherwise

Return type

bool

_purge_change_notifiers()[source]

Tears down change notifiers.

closeEvent(event)[source]

Handle close window.

Parameters

event (QCloseEvent) – Closing event

static _get_base_dir()[source]
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

pinned_values_updated[source]
emit_pinned_values_updated()[source]
connect_signals()[source]

Connects signals to slots.

init_models()[source]

Initializes models.

_restart_timer_refresh_tab_order(_visible=False)[source]
_refresh_tab_order()[source]
tabify_and_raise(docks)[source]

Tabifies docks in given list, then raises the first.

Parameters

docks (list) –

restore_dock_widgets()[source]

Docks all floating and or hidden QDockWidgets back to the window.

begin_style_change()[source]

Begins a style change operation.

end_style_change()[source]

Ends a style change operation.

apply_stacked_style(_checked=False)[source]

Applies the stacked style, inspired in the former tree view.

_finish_stacked_style()[source]
apply_pivot_style(_checked=False)[source]

Applies the pivot style, inspired in the former tabular view.

apply_graph_style(_checked=False)[source]

Applies the graph style, inspired in the former graph view.

static _get_base_dir()[source]
spinetoolbox.spine_db_editor.widgets.stacked_view_mixin

Contains the StackedViewMixin class.

Module Contents
Classes

StackedViewMixin

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.

connect_signals()[source]

Connects signals to slots.

init_models()[source]

Initializes models.

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 (DiffDatabaseMapping) –

_set_default_parameter_data(index=None)[source]

Sets default rows for parameter models according to given index.

Parameters

index (QModelIndex) – and index of the object or relationship tree

set_default_parameter_data(default_data, default_db_map)[source]
clear_all_filters()[source]
_reset_filters()[source]

Resets filters.

_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
_clear_all_other_selections(current, other=None)[source]

Clears all the other selections besides the one that was just made.

Parameters
  • current – the tree where the selection that was just made

  • other (optional) – other optional tree

tear_down()[source]
spinetoolbox.spine_db_editor.widgets.tabular_view_header_widget

Contains TabularViewHeaderWidget class.

Module Contents
Classes

TabularViewHeaderWidget

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

property identifier[source]
property area[source]
header_dropped[source]
_H_MARGIN = 3[source]
_SPACING = 16[source]
mousePressEvent(event)[source]

Register drag start position

mouseMoveEvent(event)[source]

Start dragging action if needed

mouseReleaseEvent(event)[source]

Forget drag start position

dragEnterEvent(event)[source]
dropEvent(event)[source]
spinetoolbox.spine_db_editor.widgets.tabular_view_mixin

Contains TabularViewMixin class.

Module Contents
Classes

TabularViewMixin

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.

property current_dimension_id_list[source]
property first_current_entity_class[source]
property current_dimension_name_list[source]
property current_dimension_ids[source]
_PARAMETER_VALUE = '&Value'[source]
_INDEX_EXPANSION = '&Index'[source]
_ELEMENT = 'E&lement'[source]
_SCENARIO_ALTERNATIVE = '&Scenario'[source]
_PARAMETER = 'parameter'[source]
_ALTERNATIVE = 'alternative'[source]
_INDEX = 'index'[source]
populate_pivot_action_group()[source]
connect_signals()[source]

Connects signals to slots.

refresh_views()[source]
update_filter_menus(action)[source]
_needs_to_update_headers(item_type, db_map_data)[source]
_reload_pivot_table_if_needed(item_type, db_map_data)[source]
_connect_pivot_table_header_signals()[source]

Connects signals of pivot table’s header views.

init_models()[source]

Initializes models.

_set_model_data(index, value)[source]
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

_handle_pivot_action_triggered(action)[source]
_handle_pivot_table_visibility_changed(visible)[source]
_handle_entity_tree_selection_changed_in_pivot_table(selected_indexes)[source]
_update_class_attributes(current_index)[source]

Updates current class (type and id) and reloads pivot table for it.

static _get_current_class_item(current_index)[source]
static _make_get_id(action)[source]

Returns a function to compute the db_map-id tuple of an item.

get_db_map_entities()[source]

Returns a dict mapping db maps to a list of dict entity items in the current class.

Returns

dict

load_empty_element_data(db_map_class_entities=None)[source]

Returns a dict containing all possible entity elements in the current class.

Parameters

db_map_class_entities (dict) –

Returns

Key is db_map-object_id tuple, value is None.

Return type

dict

load_full_element_data(db_map_entities=None, action='add')[source]

Returns a dict of entity elements in the current class.

Parameters

db_map_relationships (dict) –

Returns

Key is db_map-object id tuple, value is relationship id.

Return type

dict

load_relationship_data()[source]

Returns a dict that merges empty and full relationship data.

Returns

Key is object id tuple, value is True if a relationship exists, False otherwise.

Return type

dict

load_scenario_alternative_data(db_map_scenarios=None, db_map_alternatives=None)[source]

Returns a dict containing all scenario alternatives.

Returns

Key is db_map-id tuple, value is None or rank.

Return type

dict

_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_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

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

_indexes(value)[source]
load_empty_expanded_parameter_value_data(db_map_entities=None, db_map_parameter_ids=None, db_map_alternative_ids=None)[source]

Makes a dict of expanded parameter values for the current class.

Parameters
  • db_map_parameter_values (list, optional) –

  • action (str) –

Returns

mapping from unique value id tuple to value tuple

Return type

dict

load_full_expanded_parameter_value_data(db_map_parameter_values=None, action='add')[source]

Makes a dict of expanded parameter values for the current class.

Parameters
  • db_map_parameter_values (list, optional) –

  • action (str) –

Returns

mapping from unique value id tuple to value tuple

Return type

dict

load_parameter_value_data()[source]

Returns a dict that merges empty and full parameter_value data.

Returns

Key is a tuple object_id, …, parameter_id, value is the parameter_value or None if not specified.

Return type

dict

load_expanded_parameter_value_data()[source]

Returns all permutations of entities as well as parameter indexes and values for the current class.

Returns

Key is a tuple object_id, …, index, while value is None.

Return type

dict

get_pivot_preferences()[source]

Returns saved pivot preferences.

Returns

pivot tuple, or None if no preference stored

Return type

tuple, NoneType

do_reload_pivot_table()[source]

Reloads pivot table.

_can_build_pivot_table()[source]
clear_pivot_table()[source]
wipe_out_filter_menus()[source]
make_pivot_headers()[source]

Turns top left indexes in the pivot table into TabularViewHeaderWidget.

_resize_pivot_header_columns()[source]
_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.

_make_frozen_headers(first_column, last_column)[source]
_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.

create_filter_menu(identifier)[source]

Returns a filter menu for given given object_class identifier.

Parameters

identifier (int) –

Returns

TabularViewFilterMenu

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
_change_selected_frozen_row(current, previous)[source]

Sets the frozen value from selection in frozen table.

change_filter(identifier, valid_values, has_filter)[source]
_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

reload_frozen_table()[source]

Resets the frozen model according to new selection in entity trees.

find_frozen_values(frozen)[source]

Returns a list of tuples containing unique values for the frozen indexes.

Parameters

frozen (tuple) – A tuple of currently frozen indexes

Returns

frozen value

Return type

list

_change_frozen_value()[source]

Updated frozen value according to selected row in Frozen table.

receive_session_rolled_back(db_maps)[source]

Reacts to session rolled back event.

accepts_entity_item(item, db_map)[source]
accepts_parameter_item(item, db_map)[source]
accepts_element_item(item, db_map)[source]
accepts_ith_element_item(i, item, db_map)[source]
_frozen_table_reload_disabled()[source]
spinetoolbox.spine_db_editor.widgets.tree_view_mixin

Contains the TreeViewMixin class.

Module Contents
Classes

TreeViewMixin

Provides object and relationship trees for the Spine db editor.

class spinetoolbox.spine_db_editor.widgets.tree_view_mixin.TreeViewMixin(*args, **kwargs)[source]

Provides object and relationship trees for the Spine db editor.

init_models()[source]

Initializes models.

static _db_map_items(indexes)[source]

Groups items from given tree indexes by db map.

Returns

lists of dictionary items keyed by DiffDatabaseMapping

Return type

dict

_db_map_ids(indexes)[source]
_db_map_class_ids(indexes)[source]
export_selected(selected_indexes)[source]

Exports data from given indexes in the entity tree.

show_add_entity_classes_form(parent_item)[source]

Shows dialog to add new entity classes.

show_add_entities_form(parent_item)[source]

Shows dialog to add new entities.

show_add_entity_group_form(entity_class_item)[source]

Shows dialog to add new entity group.

show_manage_members_form(entity_item)[source]

Shows dialog to manage an entity group.

show_manage_elements_form(parent_item)[source]
edit_entity_tree_items(selected_indexes)[source]

Starts editing given indexes.

show_edit_entity_classes_form(items)[source]
show_edit_entities_form(items)[source]
remove_entity_tree_items(selected_indexes)[source]

Shows form to remove items from object treeview.

show_remove_entity_tree_items_form(selected)[source]
spinetoolbox.spine_db_editor.widgets.url_toolbar

Contains the UrlToolBar class and helpers.

Module Contents
Classes

UrlToolBar

_FilterWidget

_FilterArrayWidget

_DBListWidget

_UrlFilterDialog

class spinetoolbox.spine_db_editor.widgets.url_toolbar.UrlToolBar(db_editor)[source]

Bases: PySide6.QtWidgets.QToolBar

property line_edit[source]
_add_open_project_url_menu()[source]
_update_ds_url_menu_enabled()[source]
_connect_project_item_model_signals(slot)[source]
_disconnect_project_item_model_signals(slot)[source]
_update_open_project_url_menu()[source]
_open_ds_url(action)[source]
add_main_menu(menu)[source]
_update_history_actions_availability()[source]
add_urls_to_history(db_urls)[source]

Adds url to history.

Parameters

db_urls (list of str) –

get_previous_urls()[source]

Returns previous urls in history.

Returns

list of str

get_next_urls()[source]

Returns next urls in history.

Returns

list of str

_handle_line_edit_return_pressed()[source]
set_current_urls(urls)[source]
_show_filter_menu(_checked=False)[source]
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

sizeHint()[source]
filter_config()[source]
class spinetoolbox.spine_db_editor.widgets.url_toolbar._FilterArrayWidget(db_mngr, db_map, parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

filter_selection_changed[source]
filtered_url_codename()[source]
sizeHint()[source]
moveEvent(ev)[source]
class spinetoolbox.spine_db_editor.widgets.url_toolbar._DBListWidget(db_mngr, db_maps, parent=None)[source]

Bases: PySide6.QtWidgets.QTreeWidget

db_filter_selection_changed[source]
sizeHint()[source]
filtered_url_codenames()[source]
class spinetoolbox.spine_db_editor.widgets.url_toolbar._UrlFilterDialog(db_mngr, db_maps, parent=None)[source]

Bases: PySide6.QtWidgets.QDialog

filter_accepted[source]
sizeHint()[source]
_update_filter_enabled()[source]
accept()[source]
Submodules
spinetoolbox.spine_db_editor.graphics_items

Classes for drawing graphics items on graph view’s QGraphicsScene.

Module Contents
Classes

EntityItem

param spine_db_editor

'owner'

ArcItem

Connects a two EntityItems.

CrossHairsItem

Creates new relationships directly in the graph.

CrossHairsEntityItem

Represents the relationship that's being created using the CrossHairsItem.

CrossHairsArcItem

Connects a CrossHairsEntityItem with the CrossHairsItem,

EntityLabelItem

Provides a label for EntityItem.

BgItem

_ResizableQGraphicsSvgItem

_Resizer

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

property has_dimensions[source]
property db_map_ids[source]
property original_db_map_ids[source]
property entity_name[source]
property first_entity_class_id[source]
property entity_class_name[source]
property dimension_id_list[source]
property entity_byname[source]
property element_name_list[source]
property first_db_map_id[source]
property first_id[source]
property first_db_map[source]
property display_data[source]
property display_database[source]
property db_maps[source]
clone()[source]
element_id_list(db_map)[source]
entity_class_id(db_map)[source]
entity_id(db_map)[source]
db_map_data(db_map)[source]
db_map_id(db_map)[source]
db_items(db_map)[source]
boundingRect()[source]
set_pos(x, y)[source]
move_by(dx, dy)[source]
_snap(x, y)[source]
has_unique_key()[source]

Returns whether or not the item still has a single key in all the databases it represents.

Returns

bool

_get_name()[source]
_get_prop(getter, index)[source]
_get_color(index=None)[source]
_get_arc_width(index=None)[source]
_has_name()[source]
set_up()[source]
update_props(index)[source]
_update_bg()[source]
refresh_icon()[source]

Refreshes the icon.

_update_renderer(color, resize=True)[source]
_install_renderer(resize=True)[source]
_make_tool_tip()[source]
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.

set_highlight_color(color)[source]
paint(painter, option, widget=None)[source]

Shows or hides the selection halo.

_paint_as_selected()[source]
_paint_as_deselected()[source]
add_arc_item(arc_item)[source]

Adds an item to the list of arcs.

Parameters

arc_item (ArcItem) –

update_entity_pos()[source]
apply_zoom(factor)[source]

Applies zoom.

Parameters

factor (float) – The zoom factor.

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) –

update_arcs_line()[source]

Moves arc items.

_update_arcs(color, arc_width)[source]
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) –

_make_menu()[source]
contextMenuEvent(e)[source]

Shows context menu.

Parameters

e (QGraphicsSceneMouseEvent) – Mouse event

remove_db_map_ids(db_map_ids)[source]

Removes db_map_ids.

add_db_map_ids(db_map_ids)[source]
_rotate_svg_item()[source]
mouseDoubleClickEvent(e)[source]
_duplicate()[source]
_refresh_db_map_entity_class_lists()[source]
_populate_expand_collapse_menu(menu)[source]

Populates the ‘Expand’ or ‘Collapse’ menu.

Parameters

menu (QMenu) –

_populate_connect_entities_menu(menu)[source]

Populates the ‘Add relationships’ menu.

Parameters

menu (QMenu) –

_get_db_map_entity_ids_to_expand_or_collapse(action)[source]
_expand(action)[source]
_collapse(action)[source]
_start_connecting_entities(action)[source]
class spinetoolbox.spine_db_editor.graphics_items.ArcItem(ent_item, el_item, width)[source]

Bases: PySide6.QtWidgets.QGraphicsPathItem

Connects a two EntityItems.

Initializes item.

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

clone(entity_items)[source]
_make_pen()[source]
moveBy(dx, dy)[source]

Does nothing. This item is not moved the regular way, but follows the EntityItems it connects.

update_line()[source]
update_color(color)[source]
apply_value(factor)[source]
mousePressEvent(event)[source]

Accepts the event so it’s not propagated.

other_item(item)[source]
apply_zoom(factor)[source]

Applies zoom.

Parameters

factor (float) – The zoom factor.

_update_width()[source]
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

property entity_class_name[source]
property entity_name[source]
_make_tool_tip()[source]
_has_name()[source]
refresh_icon()[source]

Refreshes the icon.

set_plus_icon()[source]
set_check_icon()[source]
set_normal_icon()[source]
set_ban_icon()[source]
set_icon(unicode, color=0)[source]

Refreshes the icon.

_snap(x, y)[source]
mouseMoveEvent(event)[source]

Moves the item and all connected arcs.

Parameters

event (QGraphicsSceneMouseEvent) –

contextMenuEvent(e)[source]

Shows context menu.

Parameters

e (QGraphicsSceneMouseEvent) – Mouse event

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

_make_tool_tip()[source]
_has_name()[source]
refresh_icon()[source]

Refreshes the icon.

contextMenuEvent(e)[source]

Shows context menu.

Parameters

e (QGraphicsSceneMouseEvent) – Mouse event

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.

Initializes item.

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

_make_pen()[source]
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.

entity_name_edited[source]
boundingRect()[source]
setPlainText(text)[source]

Set texts and resets position.

Parameters

text (str) –

reset_position()[source]

Adapts item geometry so text is always centered.

class spinetoolbox.spine_db_editor.graphics_items.BgItem(svg, parent=None)[source]

Bases: PySide6.QtWidgets.QGraphicsRectItem

class Anchor[source]

Bases: enum.Enum

Generic enumeration.

Derive from this class to define new enumerations.

TL[source]
TR[source]
BL[source]
BR[source]
_getter_setter[source]
_cursors[source]
clone()[source]
hoverEnterEvent(ev)[source]
hoverLeaveEvent(ev)[source]
apply_zoom(factor)[source]
_place_resizers()[source]
_resize(anchor, delta, strong)[source]
_do_resize(rect, strong)[source]
fit_rect(rect)[source]
scene_rect()[source]
class spinetoolbox.spine_db_editor.graphics_items._ResizableQGraphicsSvgItem(*args, **kwargs)[source]

Bases: PySide6.QtSvgWidgets.QGraphicsSvgItem

resize(width, height)[source]
setSharedRenderer(renderer)[source]
boundingRect()[source]
paint(painter, options, widget)[source]
class spinetoolbox.spine_db_editor.graphics_items._Resizer(rect=QRectF(0, 0, 20, 20), parent=None)[source]

Bases: PySide6.QtWidgets.QGraphicsRectItem

class SignalsProvider[source]

Bases: PySide6.QtCore.QObject

resized[source]
mousePressEvent(ev)[source]
mouseMoveEvent(ev)[source]
mouseReleaseEvent(ev)[source]
spinetoolbox.spine_db_editor.main
Module Contents
Functions

main()

Launches Spine Db Editor as its own application.

_make_argument_parser()

Builds a command line argument parser.

spinetoolbox.spine_db_editor.main.main()[source]

Launches Spine Db Editor as its own application.

spinetoolbox.spine_db_editor.main._make_argument_parser()[source]

Builds a command line argument parser.

Returns

parser

Return type

ArgumentParser

spinetoolbox.spine_db_editor.scenario_generation

Contains functions for automatically generating scenarios from a set of alternatives.

Module Contents
Functions

all_combinations(alternatives)

Creates all possible combinations of alternatives.

unique_alternatives(alternatives)

Creates all possible single-alternative scenarios.

spinetoolbox.spine_db_editor.scenario_generation.all_combinations(alternatives)[source]

Creates all possible combinations of alternatives.

Parameters

alternatives (Iterable of Any) – alternatives

Returns

lists containing alternatives for each scenario

Return type

list of list

spinetoolbox.spine_db_editor.scenario_generation.unique_alternatives(alternatives)[source]

Creates all possible single-alternative scenarios.

Parameters

alternatives (Iterable of Any) – alternatives

Returns

tuples containing alternatives for each scenario

Return type

list of list

spinetoolbox.widgets

Init file for widgets package. Intentionally empty.

Submodules
spinetoolbox.widgets.about_widget

A widget for presenting basic information about the application.

Module Contents
Classes

AboutWidget

About widget class.

class spinetoolbox.widgets.about_widget.AboutWidget(toolbox)[source]

Bases: PySide6.QtWidgets.QWidget

About widget class.

Parameters

toolbox (ToolboxUI) – QMainWindow instance

copy_to_clipboard(_)[source]

Copies package and Python info to clipboard.

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.

setup_license_text()[source]

Add license to QTextBrowser.

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

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

spinetoolbox.widgets.add_project_item_widget

Widget shown to user when a new Project Item is created.

Module Contents
Classes

AddProjectItemWidget

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.

toolbox

Parent widget

Type

ToolboxUI

x

X coordinate of new item

Type

int

y

Y coordinate of new item

Type

int

Initialize class.

connect_signals()[source]

Connect signals to slots.

handle_name_changed()[source]

Update label to show upcoming folder name.

handle_ok_clicked()[source]

Check that given item name is valid and add it to project.

abstract call_add_item()[source]

Creates new Item according to user’s selections.

Must be reimplemented by subclasses.

keyPressEvent(e)[source]

Close Setup form when escape key is pressed.

Parameters

e (QKeyEvent) – Received key press event.

closeEvent(event=None)[source]

Handle close window.

Parameters

event (QEvent) – Closing event if ‘X’ is clicked.

spinetoolbox.widgets.add_up_spine_opt_wizard

Classes for custom QDialogs for julia setup.

Module Contents
Classes

_PageId

Enum where members are also (and must be) ints

AddUpSpineOptWizard

A wizard to install & upgrade SpineOpt.

IntroPage

SelectJuliaPage

CheckPreviousInstallPage

AddUpSpineOptPage

A QWizards page with a log. Useful for pages that need to capture the output of a process.

SuccessPage

FailurePage

TroubleshootProblemsPage

TroubleshootSolutionPage

ResetRegistryPage

A QWizards page with a log. Useful for pages that need to capture the output of a process.

AddUpSpineOptAgainPage

A QWizards page with a log. Useful for pages that need to capture the output of a process.

TotalFailurePage

Functions

_clear_layout(layout)

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.

INTRO[source]
SELECT_JULIA[source]
CHECK_PREVIOUS_INSTALL[source]
ADD_UP_SPINE_OPT[source]
SUCCESS[source]
FAILURE[source]
TROUBLESHOOT_PROBLEMS[source]
TROUBLESHOOT_SOLUTION[source]
RESET_REGISTRY[source]
ADD_UP_SPINE_OPT_AGAIN[source]
TOTAL_FAILURE[source]
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

nextId()[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.SelectJuliaPage(parent, julia_exe, julia_project)[source]

Bases: PySide6.QtWidgets.QWizardPage

initializePage()[source]
_select_julia_exe(_)[source]
_select_julia_project(_)[source]
nextId()[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.CheckPreviousInstallPage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

isComplete()[source]
cleanupPage()[source]
initializePage()[source]
_handle_check_install_finished(ret)[source]
nextId()[source]
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.

initializePage()[source]
_handle_spine_opt_add_up_finished(ret)[source]
nextId()[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.SuccessPage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

initializePage()[source]
nextId()[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.FailurePage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

_handle_check_box_clicked(checked=False)[source]
initializePage()[source]
nextId()[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.TroubleshootProblemsPage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

isComplete()[source]
_show_log(_=False)[source]
nextId()[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.TroubleshootSolutionPage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

cleanupPage()[source]
initializePage()[source]
_initialize_page_solution1()[source]
_initialize_page_solution2()[source]
nextId()[source]
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.

initializePage()[source]
_handle_registry_reset_finished(ret)[source]
nextId()[source]
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.

nextId()[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.TotalFailurePage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

nextId()[source]
spinetoolbox.widgets.add_up_spine_opt_wizard._clear_layout(layout)[source]
spinetoolbox.widgets.array_editor

Contains an editor widget for array type parameter values.

Module Contents
Classes

ArrayEditor

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

value()[source]

Returns the array currently being edited.

Returns

array

Return type

Array

_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

_change_value_type(type_name)[source]
open_value_editor(index)[source]

Opens an editor widget for array element.

Parameters

index (QModelIndex) – element’s index

_show_table_context_menu(position)[source]

Shows the table’s context menu.

Parameters

position (QPoint) – menu’s position on the table

_update_plot(topLeft=None, bottomRight=None, roles=None)[source]

Updates the plot widget.

_open_header_editor(column)[source]
spinetoolbox.widgets.array_value_editor

An editor dialog for Array elements.

Module Contents
Classes

ArrayValueEditor

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

_set_data(value)[source]

See base class.

spinetoolbox.widgets.code_text_edit

Provides simple text editor for programming purposes.

Module Contents
Classes

CodeTextEdit

A plain text edit with syntax highlighting and line numbers.

LineNumberArea

class spinetoolbox.widgets.code_text_edit.CodeTextEdit(*arg, **kwargs)[source]

Bases: PySide6.QtWidgets.QPlainTextEdit

A plain text edit with syntax highlighting and line numbers.

insertFromMimeData(source)[source]
file_selected(status)[source]
set_lexer_name(lexer_name)[source]
setPlainText(text)[source]
setDocument(doc)[source]
line_number_area_width()[source]
_update_line_number_area_width(_new_block_count=0)[source]
_update_line_number_area(rect, dy)[source]
_update_line_number_area_cursor_position()[source]
set_enabled_with_greyed(enabled)[source]
resizeEvent(event)[source]
line_number_area_paint_event(ev)[source]
class spinetoolbox.widgets.code_text_edit.LineNumberArea(editor)[source]

Bases: PySide6.QtWidgets.QWidget

sizeHint()[source]
paintEvent(ev)[source]
spinetoolbox.widgets.commit_dialog

Classes for custom QDialogs to add edit and remove database items.

Module Contents
Classes

CommitDialog

A dialog to query user's preferences for new commit.

class spinetoolbox.widgets.commit_dialog.CommitDialog(parent, *db_names)[source]

Bases: PySide6.QtWidgets.QDialog

A dialog to query user’s preferences for new commit.

Parameters
  • parent (QWidget) – the parent widget

  • db_names (Iterable of str) – database names

receive_text_changed()[source]

Called when text changes in the commit msg text edit. Enable/disable commit button accordingly.

spinetoolbox.widgets.custom_combobox

Contains a custom combo box for the custom open project dialog.

Module Contents
Classes

ElidedCombobox

Combobox with elided text.

OpenProjectDialogComboBox

class spinetoolbox.widgets.custom_combobox.ElidedCombobox[source]

Bases: PySide6.QtWidgets.QComboBox

Combobox with elided text.

paintEvent(event)[source]
class spinetoolbox.widgets.custom_combobox.OpenProjectDialogComboBox[source]

Bases: PySide6.QtWidgets.QComboBox

keyPressEvent(e)[source]

Interrupts Enter and Return key presses when QComboBox is in focus. This is needed to prevent showing the ‘Not a valid Spine Toolbox project’ Notifier every time Enter is pressed.

Parameters

e (QKeyEvent) – Received key press event.

spinetoolbox.widgets.custom_delegates

Custom item delegates.

Module Contents
Classes

ComboBoxDelegate

CheckBoxDelegate

A delegate that places a fully functioning QCheckBox.

RankDelegate

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

createEditor(parent, option, index)[source]
paint(painter, option, index)[source]
setEditorData(editor, index)[source]
setModelData(editor, model, index)[source]
updateEditorGeometry(editor, option, index)[source]
_finalize_editing(editor)[source]
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

data_committed[source]
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.

paint(painter, option, index)[source]

Paint a checkbox without the label.

static _do_paint(painter, checkbox_style_option, index)[source]
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.

setModelData(editor, model, index)[source]

Do nothing. Model data is updated by handling the data_committed signal.

get_checkbox_rect(option)[source]
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

static _do_paint(painter, checkbox_style_option, index)[source]
spinetoolbox.widgets.custom_editors

Custom editors for model/view programming.

Module Contents
Classes

CustomLineEditor

A custom QLineEdit to handle data from models.

ParameterValueLineEditor

A custom QLineEdit to handle data from models.

PivotHeaderTableLineEditor

Line editor that is visible on Pivot view's header tables due to a clever hack.

_CustomLineEditDelegate

A delegate for placing a CustomLineEditor on the first row of SearchBarEditor.

SearchBarEditor

A Google-like search bar, implemented as a QTableView with a _CustomLineEditDelegate in the first row.

CheckListEditor

A check list editor.

_IconPainterDelegate

A delegate to highlight decorations in a QListWidget.

IconColorEditor

An editor to let the user select an icon and a color for an object_class.

class spinetoolbox.widgets.custom_editors.CustomLineEditor[source]

Bases: PySide6.QtWidgets.QLineEdit

A custom QLineEdit to handle data from models.

set_data(data)[source]

Sets editor’s text.

Parameters

data (Any) – anything convertible to string

data()[source]

Returns editor’s text.

Returns

editor’s text

Return type

str

keyPressEvent(event)[source]

Prevents shift key press to clear the contents.

class spinetoolbox.widgets.custom_editors.ParameterValueLineEditor[source]

Bases: CustomLineEditor

A custom QLineEdit to handle data from models.

set_data(data)[source]

See base class.

data()[source]

See base class.

class spinetoolbox.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

fix_geometry()[source]

Fixes editor’s position after reparenting.

class spinetoolbox.widgets.custom_editors._CustomLineEditDelegate[source]

Bases: PySide6.QtWidgets.QStyledItemDelegate

A delegate for placing a CustomLineEditor on the first row of SearchBarEditor.

text_edited[source]
setModelData(editor, model, index)[source]
createEditor(parent, option, index)[source]

Create editor and ‘forward’ textEdited signal.

eventFilter(editor, event)[source]

Handle all sort of special cases.

class spinetoolbox.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.

data_committed[source]
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

refit()[source]

Changes the position and size of the editor to fit the window.

data()[source]

Returns editor’s final data.

Returns

editor data

Return type

str

_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

keyPressEvent(event)[source]

Sets data from current index into first index as the user navigates through the table using the up and down keys.

currentChanged(current, previous)[source]
edit_first_index()[source]

Edits first index if valid and not already being edited.

mousePressEvent(event)[source]

Commits data.

class spinetoolbox.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

keyPressEvent(event)[source]

Toggles checked state if the user presses space.

toggle_selected(index)[source]

Adds or removes given index from selected items.

Parameters

index (QModelIndex) – index to toggle

mouseMoveEvent(event)[source]

Sets the current index to the one under mouse.

mousePressEvent(event)[source]

Toggles checked state of pressed index.

set_data(items, checked_items)[source]

Sets data and updates geometry.

Parameters
  • items (Sequence(str)) – All items.

  • checked_items (Sequence(str)) – Initially checked items.

data()[source]

Returns a comma separated list of checked items.

Returns

str

update_geometry(option)[source]

Updates geometry.

Parameters

option (QStyleOptionViewItem) – style information

class spinetoolbox.widgets.custom_editors._IconPainterDelegate[source]

Bases: PySide6.QtWidgets.QStyledItemDelegate

A delegate to highlight decorations in a QListWidget.

paint(painter, option, index)[source]

Paints selected items using the highlight brush.

class spinetoolbox.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

_proxy_model_filter_accepts_row(source_row, source_parent)[source]

Filters icons according to search terms.

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

connect_signals()[source]

Connects signals to slots.

set_data(data)[source]

Sets current icon data.

Parameters

data (int) – database icon data

data()[source]

Gets current icon data.

Returns

database icon data

Return type

int

spinetoolbox.widgets.custom_menus

Classes for custom context menus and pop-up menus.

Module Contents
Classes

CustomContextMenu

Context menu master class for several context menus.

OpenProjectDialogComboBoxContextMenu

Context menu master class for several context menus.

CustomPopupMenu

Popup menu master class for several popup menus.

ItemSpecificationMenu

Context menu class for item specifications.

RecentProjectsPopupMenu

Recent projects menu embedded to 'File-Open recent' QAction.

KernelsPopupMenu

Menu embedded into 'Consoles->Start Jupyter Console' QMenu.

FilterMenuBase

Filter menu.

class spinetoolbox.widgets.custom_menus.CustomContextMenu(parent, position)[source]

Bases: PySide6.QtWidgets.QMenu

Context menu master class for several context menus.

Parameters
  • parent (QWidget) – Parent for menu widget (ToolboxUI)

  • position (QPoint) – Position on screen

add_action(text, icon=QIcon(), enabled=True)[source]

Adds an action to the context menu.

Parameters
  • text (str) – Text description of the action

  • icon (QIcon) – Icon for menu item

  • enabled (bool) – Is action enabled?

set_action(option)[source]

Sets the action which was clicked.

Parameters

option (str) – string with the text description of the action

get_action()[source]

Returns the clicked action, a string with a description.

class spinetoolbox.widgets.custom_menus.OpenProjectDialogComboBoxContextMenu(parent, position)[source]

Bases: CustomContextMenu

Context menu master class for several context menus.

Parameters
  • parent (QWidget) – Parent for menu widget

  • position (QPoint) – Position on screen

class spinetoolbox.widgets.custom_menus.CustomPopupMenu(parent)[source]

Bases: PySide6.QtWidgets.QMenu

Popup menu master class for several popup menus.

Parameters

parent (QWidget) – Parent widget of this pop-up menu

add_action(text, slot, enabled=True, tooltip=None, icon=None)[source]

Adds an action to the popup menu.

Parameters
  • text (str) – Text description of the action

  • slot (method) – Method to connect to action’s triggered signal

  • enabled (bool) – Is action enabled?

  • tooltip (str) – Tool tip for the action

  • icon (QIcon) – Action icon

class spinetoolbox.widgets.custom_menus.ItemSpecificationMenu(toolbox, index, item=None)[source]

Bases: CustomPopupMenu

Context menu class for item specifications.

Parameters
  • toolbox (ToolboxUI) – Toolbox that requests this menu, used as parent.

  • index (QModelIndex) – the index

  • item (ProjectItem, optional) – passed to show_specification_form

class spinetoolbox.widgets.custom_menus.RecentProjectsPopupMenu(parent)[source]

Bases: CustomPopupMenu

Recent projects menu embedded to ‘File-Open recent’ QAction.

Parameters

parent (QWidget) – Parent widget of this menu (ToolboxUI)

has_recents()[source]

Returns True if recent projects available, False otherwise.

add_recent_projects()[source]

Reads the previous project names and paths from QSettings. Adds them to the QMenu as QActions.

call_clear_recents(checked)[source]

Slot for Clear recents menu item.

Parameters

checked (bool) – Argument sent by triggered signal

call_open_project(checked, p)[source]

Slot for catching the user selected action from the recent projects menu.

Parameters
  • checked (bool) – Argument sent by triggered signal

  • p (str) – Full path to a project file

class spinetoolbox.widgets.custom_menus.KernelsPopupMenu(parent)[source]

Bases: CustomPopupMenu

Menu embedded into ‘Consoles->Start Jupyter Console’ QMenu.

Parameters

parent (QWidget) – Parent widget of this menu (ToolboxUI)

add_kernel(kernel_name, resource_dir, cond, ico, deats)[source]

Adds a kernel entry as an action to this menu.

call_open_console(checked, kernel_name, icon, conda)[source]

Slot for catching the user selected action from the kernel’s menu.

Parameters
  • checked (bool) – Argument sent by triggered signal

  • kernel_name (str) – Kernel name to launch

  • icon (QIcon) – Icon representing the kernel language

  • conda (bool) – Is this a Conda kernel spec?

class spinetoolbox.widgets.custom_menus.FilterMenuBase(parent)[source]

Bases: PySide6.QtWidgets.QMenu

Filter menu.

Parameters

parent (QWidget) – a parent widget

_set_up(make_filter_model, *args, **kwargs)[source]
connect_signals()[source]
add_items_to_filter_list(items)[source]
remove_items_from_filter_list(items)[source]
_clear_filter()[source]
_check_filter()[source]
_change_filter()[source]
abstract emit_filter_changed(valid_values)[source]
wipe_out()[source]
spinetoolbox.widgets.custom_qcombobox

Class for a custom QComboBox.

Module Contents
Classes

CustomQComboBox

A custom QComboBox for showing kernels in Settings->Tools.

class spinetoolbox.widgets.custom_qcombobox.CustomQComboBox[source]

Bases: PySide6.QtWidgets.QComboBox

A custom QComboBox for showing kernels in Settings->Tools.

mouseMoveEvent(e)[source]

Catch mouseMoveEvent and accept it because the comboBox popup (QListView) has mouse tracking on as default. This makes sure the comboBox popup appears in correct position and clicking on the combobox repeatedly does not move the Settings window.

spinetoolbox.widgets.custom_qgraphicsscene

Custom QGraphicsScene used in the Design View.

Module Contents
Classes

CustomGraphicsScene

A custom QGraphicsScene. It provides signals to notify about items,

DesignGraphicsScene

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

item_move_finished[source]

Emitted when an item has finished moving.

center_items()[source]

Centers toplevel items in the scene.

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

_handle_timeout()[source]
mouseMoveEvent(event)[source]

Moves link drawer.

mousePressEvent(event)[source]

Puts link drawer to sleep and log 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.

emit_connection_failed()[source]
keyPressEvent(event)[source]

Puts link drawer to sleep if user presses ESC.

connect_signals()[source]

Connect scene signals.

project_item_icons()[source]
handle_selection_changed()[source]

Synchronizes selection with the project tree.

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”

dragLeaveEvent(event)[source]

Accept event.

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.

drawBackground(painter, rect)[source]

Reimplemented method to make a custom background.

Parameters
  • painter (QPainter) – Painter that is used to paint background

  • rect (QRectF) – The exposed (viewport) rectangle in scene coordinates

_draw_solid_bg(painter, rect)[source]

Draws solid bg.

_draw_grid_bg(painter, rect)[source]

Draws grid bg.

_draw_tree_bg(painter, rect)[source]

Draws ‘tree of life’ bg.

Selects current link drawer.

Parameters

drawer_type (LinkType) – selected link drawer’s type

spinetoolbox.widgets.custom_qgraphicsviews

Classes for custom QGraphicsViews for the Design and Graph views.

Module Contents
Classes

CustomQGraphicsView

Super class for Design and Entity QGraphicsViews.

DesignQGraphicsView

QGraphicsView for the Design View.

class spinetoolbox.widgets.custom_qgraphicsviews.CustomQGraphicsView(parent)[source]

Bases: PySide6.QtWidgets.QGraphicsView

Super class for Design and Entity QGraphicsViews.

parent

Parent widget

Type

QWidget

Init CustomQGraphicsView.

abstract property _qsettings[source]
property zoom_factor[source]
reset_zoom()[source]

Resets zoom to the default factor.

keyPressEvent(event)[source]

Overridden method. Enable zooming with plus and minus keys (comma resets zoom). Send event downstream to QGraphicsItems if pressed key is not handled here.

Parameters

event (QKeyEvent) – Pressed key

mousePressEvent(event)[source]

Set rubber band selection mode if Control pressed. Enable resetting the zoom factor from the middle mouse button.

mouseReleaseEvent(event)[source]

Reestablish scroll hand drag mode.

_use_smooth_zoom()[source]
wheelEvent(event)[source]

Zooms in/out.

Parameters

event (QWheelEvent) – Mouse wheel 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 (ShrinkingScene) – a new scene

_handle_item_move_finished(item)[source]
_update_zoom_limits()[source]

Updates the minimum zoom limit and the zoom level with which the view fits all the items in the scene.

abstract _compute_max_zoom()[source]
_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.

_handle_resize_time_line_finished()[source]

Cleans up after resizing time line finishes.

zoom_in()[source]

Perform a zoom in with a fixed scaling.

zoom_out()[source]

Perform a zoom out with a fixed scaling.

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

_zoom(factor)[source]
_get_viewport_scene_rect()[source]

Returns the viewport rect mapped to the scene.

Returns

QRectF

_ensure_item_visible(item)[source]

Resets zoom if item is not visible.

_set_preferred_scene_rect()[source]

Sets the scene rect to the result of uniting the scene viewport rect and the items bounding rect.

class spinetoolbox.widgets.custom_qgraphicsviews.DesignQGraphicsView(parent)[source]

Bases: CustomQGraphicsView

QGraphicsView for the Design View.

Parameters

parent (QWidget) – parent widget

property _qsettings[source]
set_ui(toolbox)[source]

Set a new scene into the Design View when app is started.

reset_zoom()[source]

Resets zoom to the default factor.

_compute_max_zoom()[source]
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

Pushes an AddLinkCommand to the toolbox undo stack.

Parameters

Adds given connection to the Design view.

Parameters

connection (Connection) – the connection to add

Replaces a link on the Design view.

Parameters

updated_connection (Connection) – connection that was updated

Pushes a RemoveConnectionsCommand to the Toolbox undo stack.

Parameters

links (list of Link) – links to remove

Removes a link from the scene.

Parameters

connection (ConnectionBase) – link’s connection

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
do_add_jump(jump)[source]

Adds given jump to the Design view.

Parameters

jump (Jump) – jump to add

do_update_jump(updated_jump)[source]

Replaces a jump link on the Design view.

Parameters

updated_jump (Jump) – jump that was updated

do_remove_jump(jump)[source]

Removes a jump from the scene.

Parameters

jump (Jump) – link’s jump

contextMenuEvent(event)[source]

Shows context menu for the blank view

Parameters

event (QContextMenuEvent) – Event

spinetoolbox.widgets.custom_qlineedits

Classes for custom line edits.

Module Contents
Classes

PropertyQLineEdit

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.

setText(text)[source]

Overridden to prevent the cursor going to the end whenever the user is still editing. This happens because we set the text programmatically in undo/redo implementations.

spinetoolbox.widgets.custom_qtableview

Custom QTableView classes that support copy-paste and the like.

Module Contents
Classes

CopyPasteTableView

Custom QTableView class with copy and paste methods.

AutoFilterCopyPasteTableView

Custom QTableView class with autofilter functionality.

IndexedParameterValueTableViewBase

Custom QTableView base class with copy and paste methods for indexed parameter values.

TimeSeriesFixedResolutionTableView

A QTableView for fixed resolution time series table.

IndexedValueTableView

A QTableView class with for variable resolution time series and time patterns.

ArrayTableView

Custom QTableView with copy and paste methods for single column tables.

MapTableView

Custom QTableView with copy and paste methods for map tables.

Functions

_range(selection)

Returns the top left and bottom right corners of selection.

_could_be_time_stamp(s)

Evaluates if given string could be a time stamp.

system_lc_numeric()

Attributes

_

_NOT_TIME_STAMP

spinetoolbox.widgets.custom_qtableview._[source]
class spinetoolbox.widgets.custom_qtableview.CopyPasteTableView(parent=None)[source]

Bases: PySide6.QtWidgets.QTableView

Custom QTableView class with copy and paste methods.

property copy_action[source]
property paste_action[source]
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

delete_content(_=False)[source]

Deletes content from editable indexes in current selection.

can_copy()[source]
copy(_=False)[source]

Copies current selection to clipboard in excel format.

can_paste()[source]
paste(_=False)[source]

Paste data from clipboard.

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

paste_on_selection()[source]

Pastes clipboard data on selection, but not beyond. If data is smaller than selection, repeat data to fit selection.

paste_normal()[source]

Pastes clipboard data, overwriting cells if needed.

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) –

_trigger_filter_menu(_)[source]

Shows current column’s auto filter menu.

show_auto_filter_menu(logical_index)[source]

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.

copy(_=False)[source]

Copies current selection to clipboard in CSV format.

Returns

True if data was copied on the clipboard, False otherwise

Return type

bool

abstract static _read_pasted_text(text)[source]

Reads CSV formatted table.

abstract paste(_=False)[source]

Pastes data from clipboard to selection.

class spinetoolbox.widgets.custom_qtableview.TimeSeriesFixedResolutionTableView(parent=None)[source]

Bases: IndexedParameterValueTableViewBase

A QTableView for fixed resolution time series table.

paste(_=True)[source]

Pastes data from clipboard.

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(_=False)[source]

Pastes data from clipboard.

_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

static _read_pasted_text(text)[source]

Parses a given CSV table.

Parameters

text (str) – a CSV table

Returns

a tuple (data indexes, data 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.

copy(_=False)[source]

Copies current selection to clipboard in CSV format.

Returns

True if data was copied on the clipboard, False otherwise

Return type

bool

paste(_=False)[source]

Pastes data from clipboard.

static _read_pasted_text(text)[source]

Reads the first column of given CSV table.

Parameters

text (str) – a CSV table

Returns

data column

Return type

list of str

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

delete_content(_=False)[source]

Deletes content in current selection.

paste(_=False)[source]

Pastes data from clipboard.

Returns

True if data was pasted successfully, False otherwise

Return type

bool

static _read_pasted_text(text)[source]

Parses a given CSV table.

Parameters

text (str) – a CSV table

Returns

a list of table rows

Return type

list of list

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._NOT_TIME_STAMP[source]
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_qtableview.system_lc_numeric()[source]
spinetoolbox.widgets.custom_qtextbrowser

Class for a custom QTextBrowser for showing the logs and tool output.

Module Contents
Classes

CustomQTextBrowser

Custom QTextBrowser class.

MonoSpaceFontTextBrowser

Custom QTextBrowser class.

class spinetoolbox.widgets.custom_qtextbrowser.CustomQTextBrowser(parent)[source]

Bases: PySide6.QtWidgets.QTextBrowser

Custom QTextBrowser class.

Parameters

parent (QWidget) – Parent widget

_ALL_RUNS = 'All executions'[source]
set_toolbox(toolbox)[source]
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

clear()[source]
_populate_executions_menu()[source]
reset_executions_button_text()[source]
_select_execution(action)[source]
static _make_log_entry_title(title)[source]
start_execution(timestamp)[source]

Creates cursors (log entry points) for given items in event log.

Parameters

timestamp (str) – time stamp

add_log_message(item_name, filter_id, message)[source]

Adds a message to an item’s execution log.

Parameters
  • item_name (str) – item name

  • filter_id (str) – filter identifier

  • message (str) – formatted message

execution_timestamps()[source]
select_all_executions()[source]
select_execution(timestamp)[source]
_set_execution_visible(timestamp, visible)[source]
set_item_log_selected(selected)[source]
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.

Module Contents
Classes

CopyPasteTreeView

Custom QTreeView class with copy and paste support.

SourcesTreeView

Custom QTreeView class for 'Sources' in Tool specification editor widget.

CustomTreeView

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

copy()[source]

Copy current selection to clipboard.

The default implementation copies the data as linefeed separated list.

Returns

True if data was successfully copied, False otherwise

Return type

bool

paste()[source]

Pastes data to the view.

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

files_dropped[source]
del_key_pressed[source]
dragEnterEvent(event)[source]

Accept file and folder drops from the filesystem.

dragMoveEvent(event)[source]

Accept event.

dropEvent(event)[source]

Emit files_dropped signal with a list of files for each dropped url.

keyPressEvent(event)[source]

Overridden method to make the view support deleting items with a delete key.

class spinetoolbox.widgets.custom_qtreeview.CustomTreeView(parent)[source]

Bases: PySide6.QtWidgets.QTreeView

Custom QTreeView class for Tool specification editor form to enable keyPressEvent.

Parameters

parent (QWidget) – The parent of this view

del_key_pressed[source]
keyPressEvent(event)[source]

Overridden method to make the view support deleting items with a delete key.

spinetoolbox.widgets.custom_qwidgets

Custom QWidgets for Filtering and Zooming.

Module Contents
Classes

ElidedTextMixin

UndoRedoMixin

FilterWidget

Filter widget class.

CustomWidgetAction

A QWidgetAction with custom hovering.

ToolBarWidgetAction

An action with a tool bar.

ToolBarWidgetBase

A toolbar on the right, with enough space to print a text beneath.

ToolBarWidget

A toolbar on the right, with enough space to print a text beneath.

MenuItemToolBarWidget

A menu item with a toolbar on the right.

_MenuToolBar

A custom tool bar for MenuItemToolBarWidget.

TitleWidgetAction

A titled separator.

WrapLabel

A QLabel that always wraps text.

HyperTextLabel

A QLabel that supports hyperlinks.

QWizardProcessPage

A QWizards page with a log. Useful for pages that need to capture the output of a process.

LabelWithCopyButton

A read only QLabel with a QToolButton that copies the text to clipboard.

ElidedLabel

A QLabel with elided text.

HorizontalSpinBox

PropertyQSpinBox

A spinbox where undo and redo key strokes apply to the project.

SelectDatabaseItemsDialog

Dialog that lets selecting database items.

PurgeSettingsDialog

Dialog that lets selecting database items.

ResizingViewMixin

class spinetoolbox.widgets.custom_qwidgets.ElidedTextMixin(*args, **kwargs)[source]
setText(text)[source]
_update_text(text)[source]
_set_text_elided(width=None)[source]
_elided_offset()[source]
text()[source]
resizeEvent(event)[source]
class spinetoolbox.widgets.custom_qwidgets.UndoRedoMixin[source]
keyPressEvent(e)[source]

Overridden to catch and pass on the Undo and Redo commands when this line edit has the focus.

Parameters

e (QKeyEvent) – Event

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

okPressed[source]
cancelPressed[source]
set_filter_list(items)[source]
connect_signals()[source]
save_state()[source]

Saves the state of the FilterCheckboxListModel.

reset_state()[source]

Sets the state of the FilterCheckboxListModel to saved state.

clear_filter()[source]

Selects all items in FilterCheckBoxListModel.

has_filter()[source]

Returns true if any item is filtered in FilterCheckboxListModel false otherwise.

_apply_filter()[source]

Apply current filter and save state.

_cancel_filter()[source]

Cancel current edit of filter and set the state to the stored state.

_filter_list()[source]

Filter list with current text.

_text_edited(new_text)[source]

Callback for edit text, starts/restarts timer. Start timer after text is edited, restart timer if text is edited before last time out.

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

_handle_hovered()[source]

Hides other menus that might be shown in the parent widget and repaints it. This is to emulate the behavior of QAction.

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

eventFilter(obj, ev)[source]
_handle_hovered()[source]

Hides other menus that might be shown in the parent widget and repaints it. This is to emulate the behavior of QAction.

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

paintEvent(event)[source]

Draws the menu item, then calls the super() method to draw the tool bar.

class spinetoolbox.widgets.custom_qwidgets._MenuToolBar(parent=None)[source]

Bases: PySide6.QtWidgets.QToolBar

A custom tool bar for MenuItemToolBarWidget.

enabled_changed[source]
_align_buttons()[source]

Align all buttons to bottom so frames look good.

add_frame(left, right, title)[source]

Add frame around given actions, with given title.

Parameters
  • left (QAction) –

  • right (QAction) –

  • title (str) –

is_enabled()[source]
addActions(actions)[source]

Overriden method to customize tool buttons.

addAction(*args, **kwargs)[source]

Overriden method to customize the tool button.

sizeHint()[source]

Make room for frames if needed.

paintEvent(ev)[source]

Paint the frames.

_setup_action_button(action)[source]
Customizes the QToolButton associated with given action:
  1. Makes sure that the text honors the action’s mnemonics.

  2. 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. Emits self.enabled_changed accordingly.

eventFilter(obj, ev)[source]

Installed on each action’s QToolButton. Ignores Up and Down key press events, so they are handled by the toolbar for custom navigation.

keyPressEvent(ev)[source]

Navigates over the tool bar buttons.

hideEvent(ev)[source]
class spinetoolbox.widgets.custom_qwidgets.TitleWidgetAction(title, parent=None)[source]

Bases: CustomWidgetAction

A titled separator.

Class constructor.

Parameters

parent (QMenu) – the widget’s parent

H_MARGIN = 5[source]
V_MARGIN = 2[source]
static _add_line(widget, layout)[source]
isSeparator()[source]
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 _ExecutionManager[source]

A descriptor that stores a QProcessExecutionManager. When execution_finished is emitted, it shows the button to copy the process log.

public_name[source]
private_name[source]
__set_name__(owner, name)[source]
__get__(obj, objtype=None)[source]
__set__(obj, value)[source]
msg[source]
msg_warning[source]
msg_error[source]
msg_success[source]
msg_proc[source]
msg_proc_error[source]
_exec_mngr[source]
_connect_signals()[source]
_handle_copy_clicked(_=False)[source]
_add_msg(msg)[source]
_add_msg_warning(msg)[source]
_add_msg_error(msg)[source]
_add_msg_success(msg)[source]
isComplete()[source]
cleanupPage()[source]
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

valueChanged[source]
value()[source]
setMinimum(minimum)[source]
setMaximum(maximum)[source]
setValue(value, strict=False)[source]
_dec_value()[source]
_inc_value()[source]
_focus_line_edit()[source]
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

_warn_checked_non_data_items = True[source]
_ok_button_can_be_disabled = True[source]
show()[source]

Sets the OK button enabled before showing the dialog

get_checked_states()[source]

Returns current item checked states.

Returns

mapping from database item name to checked flag

Return type

dict

_handle_check_box_state_changed(_checked)[source]
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

_ok_button_can_be_disabled = False[source]
class spinetoolbox.widgets.custom_qwidgets.ResizingViewMixin(*args, **kwargs)[source]
rowsInserted(parent, start, end)[source]
abstract _do_resize()[source]
spinetoolbox.widgets.datetime_editor

An editor widget for editing datetime database (relationship) parameter values.

Module Contents
Classes

DatetimeEditor

An editor widget for DateTime type parameter values.

Functions

_QDateTime_to_datetime(dt)

Converts a QDateTime object to Python's datetime.datetime type.

_datetime_to_QDateTime(dt)

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.

class spinetoolbox.widgets.datetime_editor.DatetimeEditor(parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

An editor widget for DateTime type parameter values.

parent

a parent widget

Type

QWidget

_change_datetime(new_datetime)[source]

Updates the internal DateTime value

set_value(value)[source]

Sets the value to be edited.

value()[source]

Returns the editor’s current value.

spinetoolbox.widgets.duration_editor

An editor widget for editing duration database (relationship) parameter values.

Module Contents
Classes

DurationEditor

An editor widget for Duration type parameter values.

class spinetoolbox.widgets.duration_editor.DurationEditor(parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

An editor widget for Duration type parameter values.

parent

a parent widget

Type

QWidget

_change_duration()[source]

Updates the value being edited.

set_value(value)[source]

Sets the value for editing.

value()[source]

Returns the current Duration.

spinetoolbox.widgets.indexed_value_table_context_menu

Context menus for parameter value editor widgets.

Module Contents
Classes

ContextMenuBase

Context menu base for parameter value editor tables.

ArrayTableContextMenu

Context menu for array editor tables.

IndexedValueTableContextMenu

Context menu for time series and time pattern editor tables.

MapTableContextMenu

Context menu for map editor tables.

Functions

_unique_row_ranges(selections)

Merged ranges in given selections to unique ranges.

_unique_column_ranges(selections)

Merged ranges in given selections to unique ranges.

_merge_intervals(intervals)

Merges given intervals if they overlap.

Attributes

_INSERT_SINGLE_COLUMN_AFTER

_INSERT_SINGLE_ROW_AFTER

_INSERT_MULTIPLE_COLUMNS_AFTER

_INSERT_MULTIPLE_ROWS_AFTER

_INSERT_SINGLE_COLUMN_BEFORE

_INSERT_SINGLE_ROW_BEFORE

_INSERT_MULTIPLE_COLUMNS_BEFORE

_INSERT_MULTIPLE_ROWS_BEFORE

_OPEN_EDITOR

_PLOT

_PLOT_IN_WINDOW

_REMOVE_COLUMNS

_REMOVE_ROWS

_TRIM_COLUMNS

spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_SINGLE_COLUMN_AFTER = 'Insert column after'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_SINGLE_ROW_AFTER = 'Insert row after'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_MULTIPLE_COLUMNS_AFTER = 'Insert columns after...'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_MULTIPLE_ROWS_AFTER = 'Insert rows after...'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_SINGLE_COLUMN_BEFORE = 'Insert column before'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_SINGLE_ROW_BEFORE = 'Insert row before'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_MULTIPLE_COLUMNS_BEFORE = 'Insert columns before...'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._INSERT_MULTIPLE_ROWS_BEFORE = 'Insert rows before...'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._OPEN_EDITOR = 'Edit...'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._PLOT = 'Plot...'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._PLOT_IN_WINDOW = 'Plot in window'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._REMOVE_COLUMNS = 'Remove columns'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._REMOVE_ROWS = 'Remove rows'[source]
spinetoolbox.widgets.indexed_value_table_context_menu._TRIM_COLUMNS = 'Trim columns'[source]
class spinetoolbox.widgets.indexed_value_table_context_menu.ContextMenuBase(table_view, position)[source]

Bases: PySide6.QtWidgets.QMenu

Context menu base for parameter value editor tables.

Parameters
  • table_view (QTableView) – the view where the menu is invoked

  • position (QPoint) – menu’s position on the table view

_add_default_actions()[source]

Adds default actions to the menu.

_first_row()[source]

Returns the first selected row.

Returns

index to the first row

Return type

int

_insert_multiple_rows_after()[source]

Prompts for row count, then inserts new rows below the current selection.

_insert_multiple_rows_before()[source]

Prompts for row count, then inserts new rows above the current selection.

_insert_single_row_after()[source]

Inserts a single row below the current selection.

_insert_single_row_before()[source]

Inserts a single row above the current selection.

_last_row()[source]

Returns the last selected row.

Returns

index to the last row

Return type

int

_prompt_row_count()[source]

Prompts for number of rows to insert.

Returns

number of rows

Return type

int

_remove_rows()[source]

Removes selected rows.

class spinetoolbox.widgets.indexed_value_table_context_menu.ArrayTableContextMenu(editor, table_view, position)[source]

Bases: ContextMenuBase

Context menu for array editor tables.

Parameters
  • editor (ArrayEditor) – array editor widget

  • table_view (QTableView) – the view where the menu is invoked

  • position (QPoint) – menu’s position

_show_value_editor()[source]

Opens the value element editor.

class spinetoolbox.widgets.indexed_value_table_context_menu.IndexedValueTableContextMenu(table_view, position)[source]

Bases: ContextMenuBase

Context menu for time series and time pattern editor tables.

Parameters
  • table_view (QTableView) – the view where the menu is invoked

  • position (QPoint) – menu’s position

class spinetoolbox.widgets.indexed_value_table_context_menu.MapTableContextMenu(editor, table_view, position)[source]

Bases: ContextMenuBase

Context menu for map editor tables.

Parameters
  • editor (MapEditor) – map editor widget

  • table_view (QTableView) – the view where the menu is invoked

  • position (QPoint) – table cell index

_first_column()[source]

Returns the first selected column.

Returns

index to the first column

Return type

int

_insert_multiple_columns_after()[source]

Prompts for column count, then inserts new columns right from the current selection.

_insert_multiple_columns_before()[source]

Prompts for column count, then inserts new columns left from the current selection.

_insert_single_column_before()[source]

Inserts a single column left from the current selection.

_insert_single_column_after()[source]

Inserts a single column right from the current selection.

_last_column()[source]

Returns the last selected column.

Returns

index to the last column

Return type

int

_prompt_column_count()[source]

Prompts for number of column to insert.

Returns

number of columns

Return type

int

_remove_columns()[source]

Removes selected columns

_show_value_editor()[source]

Opens the value element editor.

_plot(checked=False)[source]

Plots current indexes.

_plot_in_window(action)[source]

Plots the selected cells in an existing window.

_trim_columns()[source]

Removes excessive columns from the table.

spinetoolbox.widgets.indexed_value_table_context_menu._unique_row_ranges(selections)[source]

Merged ranges in given selections to unique ranges.

Parameters

selections (list of QItemSelectionRange) – selected ranges

Returns

a list of [first_row, last_row] ranges

Return type

list of list

spinetoolbox.widgets.indexed_value_table_context_menu._unique_column_ranges(selections)[source]

Merged ranges in given selections to unique ranges.

Parameters

selections (list of QItemSelectionRange) – selected ranges

Returns

a list of [first_row, last_row] ranges

Return type

list of list

spinetoolbox.widgets.indexed_value_table_context_menu._merge_intervals(intervals)[source]

Merges given intervals if they overlap.

Parameters

intervals (list of list) – a list of intervals in the form [first, last]

Returns

merged intervals in the form [first, last]

Return type

list of list

spinetoolbox.widgets.install_julia_wizard

Classes for custom QDialogs for julia setup.

Module Contents
Classes

_PageId

Enum where members are also (and must be) ints

InstallJuliaWizard

A wizard to install julia

JillNotFoundPage

IntroPage

SelectDirsPage

InstallJuliaPage

A QWizards page with a log. Useful for pages that need to capture the output of a process.

SuccessPage

FailurePage

Attributes

jill_install

spinetoolbox.widgets.install_julia_wizard.jill_install[source]
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.

INTRO[source]
SELECT_DIRS[source]
INSTALL[source]
SUCCESS[source]
FAILURE[source]
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)

julia_exe_selected[source]
set_julia_exe()[source]
accept()[source]
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

nextId()[source]
class spinetoolbox.widgets.install_julia_wizard.SelectDirsPage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

initializePage()[source]
_select_install_dir()[source]
nextId()[source]
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.

cleanupPage()[source]
initializePage()[source]
_handle_julia_install_finished(ret)[source]
nextId()[source]
class spinetoolbox.widgets.install_julia_wizard.SuccessPage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

initializePage()[source]
nextId()[source]
class spinetoolbox.widgets.install_julia_wizard.FailurePage(parent)[source]

Bases: PySide6.QtWidgets.QWizardPage

initializePage()[source]
nextId()[source]
spinetoolbox.widgets.jump_properties_widget

Contains jump properties widget’s business logic.

Module Contents
Classes

JumpPropertiesWidget

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

_load_condition_into_ui(condition)[source]
_make_condition_from_ui()[source]
_change_condition()[source]

Stores jump condition to link.

_show_tool_spec_form(_checked=False)[source]
_set_save_script_button_enabled()[source]
_update_add_args_button_enabled(_selected, _deselected)[source]
_do_update_add_args_button_enabled()[source]
_update_remove_args_button_enabled(_selected, _deselected)[source]
_do_update_remove_args_button_enabled()[source]
_populate_cmd_line_args_model()[source]
_push_update_cmd_line_args_command(cmd_line_args)[source]
_remove_arg(_=False)[source]
_add_args(_=False)[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

Releases the widget from any links.

set_condition(jump, condition)[source]
update_cmd_line_args(jump, cmd_line_args)[source]
spinetoolbox.widgets.jupyter_console_widget

Class for a custom RichJupyterWidget that can run Tool instances.

Module Contents
Classes

JupyterConsoleWidget

Base class for all embedded console widgets that can run tool instances.

Attributes

traitlets_logger

asyncio_logger

spinetoolbox.widgets.jupyter_console_widget.traitlets_logger[source]
spinetoolbox.widgets.jupyter_console_widget.asyncio_logger[source]
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.

property owner_names[source]
console_closed[source]
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

release_exec_mngr_resources()[source]

Closes _io.TextIOWrapper files.

_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.

request_shutdown_kernel_manager()[source]

Sends a shutdown kernel manager request to engine.

name()[source]

Returns console name for display purposes.

shutdown_kernel_client()[source]

Shuts down local kernel client.

dragEnterEvent(e)[source]

Rejects dropped project items.

_context_menu_make(pos)[source]

Reimplemented to add actions to console context-menus.

copy_input()[source]

Copies only input.

closeEvent(e)[source]

Catches close event to shut down the kernel client and sends a signal to Toolbox to request Spine Engine to shut down the kernel manager.

spinetoolbox.widgets.kernel_editor

Widget for showing the progress of making a Julia or Python kernel.

Module Contents
Classes

KernelEditorBase

Base class for kernel editors.

MiniPythonKernelEditor

A Simple Python kernel maker. The Python executable path is passed in

MiniJuliaKernelEditor

A Simple Julia Kernel maker. The julia exe and project are passed in

Functions

format_event_message(msg_type, message[, show_datetime])

Formats message for the kernel editor text browser.

format_process_message(msg_type, message)

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”

connect_signals()[source]

Connects signals to slots.

_show_close_button(failed=False)[source]
make_kernel()[source]
abstract _do_make_kernel()[source]
new_kernel_name()[source]

Returns the new kernel name after it’s been created.

_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

abstract _python_kernel_name()[source]
abstract _python_kernel_display_name()[source]
_python_interpreter_name()[source]
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

abstract _julia_kernel_name()[source]
_julia_executable()[source]
_julia_project()[source]
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_rebuild_ijulia_needed()[source]
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

start_ijulia_rebuild_process(program, project)[source]

Starts rebuilding IJulia.

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

add_process_error_message(msg)[source]

Writes message from stderr to kernel editor text browser.

Parameters

msg (str) – String written to QTextBrowser

_save_ui()[source]
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”

abstract _julia_kernel_name()[source]
_python_kernel_name()[source]
_python_kernel_display_name()[source]
_do_make_kernel()[source]
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

set_kernel_name()[source]

Retrieves Python version in a subprocess and makes a kernel name based on it.

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”

_julia_kernel_name()[source]
abstract _python_kernel_name()[source]
abstract _python_kernel_display_name()[source]
_do_make_kernel()[source]
handle_installkernel_process_finished(retval)[source]

Checks whether the IJulia.installkernel process finished successfully.

Parameters

retval (int) – Process return value. 0: success, !0: failure

spinetoolbox.widgets.kernel_editor.format_event_message(msg_type, message, show_datetime=True)[source]

Formats message for the kernel editor text browser. This is a copy of helpers.format_event_message() but the colors have been edited for a text browser with a white background.

spinetoolbox.widgets.kernel_editor.format_process_message(msg_type, message)[source]

Formats process message for the kernel editor text browser.

spinetoolbox.widgets.map_editor

An editor widget for editing a map type parameter values.

Module Contents
Classes

MapEditor

A widget for editing maps.

class spinetoolbox.widgets.map_editor.MapEditor(parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

A widget for editing maps.

parent
Type

QWidget

_convert_leaves(_)[source]
_show_table_context_menu(position)[source]

Opens table context menu.

Parameters

position (QPoint) – menu’s position

set_value(value)[source]

Sets the parameter_value to be edited.

value()[source]

Returns the parameter_value currently being edited.

open_value_editor(index)[source]

Opens value editor dialog for given map model index.

Parameters

index (QModelIndex) – index

_open_header_editor(column)[source]
spinetoolbox.widgets.map_value_editor

An editor dialog for map indexes and values.

Module Contents
Classes

MapValueEditor

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

_set_data(value)[source]

See base class.

spinetoolbox.widgets.multi_tab_spec_editor

Contains the MultiTabSpecEditor class.

Module Contents
Classes

MultiTabSpecEditor

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

property new_tab_title[source]

Title for new tabs.

_make_other()[source]

Creates a new MultiTabWindow of this type.

Returns

new MultiTabWindow

Return type

MultiTabWindow

_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

show_plus_button_context_menu(global_pos)[source]

Opens a context menu for the tool bar.

Parameters

global_pos (QPoint) – menu position on screen

spinetoolbox.widgets.multi_tab_window

Contains the MultiTabWindow and TabBarPlus classes.

Module Contents
Classes

MultiTabWindow

A main window that has a tab widget as its central widget.

TabBarPlus

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

property accepting_new_tabs[source]
property new_tab_title[source]

Title for new tabs.

_tab_slots[source]
_other_editor_windows[source]
abstract _make_other()[source]

Creates a new MultiTabWindow of this type.

Returns

new MultiTabWindow

Return type

MultiTabWindow

others()[source]

List of other MultiTabWindows of the same type.

Returns

other MutliTabWindows 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

abstract show_plus_button_context_menu(global_pos)[source]

Opens a context menu for the tool bar.

Parameters

global_pos (QPoint) – menu position on screen

connect_signals()[source]

Connects window’s signals.

name()[source]

Generates name based on the current tab and total tab count.

Returns

a name

Return type

str

all_tabs()[source]

Iterates over tab contents widgets.

Yields

QWidget – tab contents widget

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()

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.

_close_tab(index)[source]

Closes the tab at index.

Parameters

index (int) – tab index

set_current_tab(tab)[source]

Sets the tab that is shown on the window.

Parameters

tab (QWidget) – tab’s contents widget

make_context_menu(index)[source]

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

restore_ui()[source]

Restore UI state from previous session.

save_window_state()[source]

Save window state parameters (size, position, state) via QSettings.

closeEvent(event)[source]
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) –

plus_clicked[source]
resizeEvent(event)[source]

Sets the dimension of the plus button. Also, makes the tab bar as wide as the parent.

tabLayoutChange()[source]
_move_plus_button()[source]

Places the plus button at the right of the last tab.

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) –

mouseReleaseEvent(event)[source]
start_dragging(index)[source]

Stars dragging the given index. This happens when a detached tab is reattached to this bar.

Parameters

index (int) –

index_under_mouse()[source]

Returns the index under the mouse cursor, or None if the cursor isn’t over the tab bar. Used to check for drop targets.

Returns

int or NoneType

contextMenuEvent(event)[source]
spinetoolbox.widgets.notification

Contains a notification widget.

Module Contents
Classes

Notification

Custom pop-up notification widget with fade-in and fade-out effect.

ButtonNotification

A notification with a button.

LinkNotification

A notification that may have a link.

ChangeNotifier

param parent

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) –

_FADE_IN_OUT_DURATION = 500[source]
opacity[source]
show()[source]

Shows widget and moves it to the selected corner of the parent widget.

get_opacity()[source]

opacity getter.

set_opacity(op)[source]

opacity setter.

update_opacity(value)[source]

Updates graphics effect opacity.

start_self_destruction()[source]

Starts fade-out animation and closing of the notification.

enterEvent(e)[source]

Pauses timer as the mouse hovers the notification.

leaveEvent(e)[source]

Starts self destruction after the mouse leaves the notification.

remaining_time()[source]
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) –

class spinetoolbox.widgets.notification.ChangeNotifier(parent, undo_stack, settings, settings_key, corner=Qt.BottomRightCorner)[source]

Bases: PySide6.QtCore.QObject

Parameters
  • parent (QWidget) –

  • undo_stack (QUndoStack) –

  • settings (QSettings) –

  • settings_key (str) –

  • corner (int) –

_ANIMATION_LIFE_SPAN = 5000[source]
_push_notification(index)[source]
tear_down()[source]

Tears down the notifier.

spinetoolbox.widgets.open_project_widget

Contains a class for a widget that represents a ‘Open Project Directory’ dialog.

Module Contents
Classes

OpenProjectDialog

A dialog that lets user select a project to open either by choosing

CustomQFileSystemModel

Custom file system model.

DirValidator

class spinetoolbox.widgets.open_project_widget.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

set_keyboard_shortcuts()[source]

Creates keyboard shortcuts for the ‘Root’, ‘Home’, etc. buttons.

connect_signals()[source]

Connects signals to slots.

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.

selection()[source]

Returns the selected path from dialog.

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

show_context_menu(pos)[source]

Shows the context menu for the QCombobox with a ‘Clear history’ entry.

Parameters

pos (QPoint) – Mouse position

closeEvent(event=None)[source]

Handles dialog closing.

Parameters

event (QCloseEvent) – Close event

class spinetoolbox.widgets.open_project_widget.CustomQFileSystemModel[source]

Bases: PySide6.QtWidgets.QFileSystemModel

Custom file system model.

columnCount(parent=QModelIndex())[source]

Returns one.

class spinetoolbox.widgets.open_project_widget.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.parameter_value_editor

An editor dialog for editing database (relationship) parameter values.

Module Contents
Classes

ParameterValueEditor

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

_set_data(value)[source]

See base class.

spinetoolbox.widgets.parameter_value_editor_base

A base for editor windows for editing parameter values.

Module Contents
Classes

ValueType

Enum to identify value types that use different editors.

ParameterValueEditorBase

Dialog for editing parameter values.

Attributes

_SELECTORS

class spinetoolbox.widgets.parameter_value_editor_base.ValueType[source]

Bases: enum.Enum

Enum to identify value types that use different editors.

PLAIN_VALUE[source]
MAP[source]
TIME_SERIES_FIXED_RESOLUTION[source]
TIME_SERIES_VARIABLE_RESOLUTION[source]
TIME_PATTERN[source]
ARRAY[source]
DATETIME[source]
DURATION[source]
spinetoolbox.widgets.parameter_value_editor_base._SELECTORS[source]
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 to QWidget

  • 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) –

_use_editor(value, value_type)[source]

Sets a value to edit on an editor widget.

Parameters
  • value (object) – value to edit

  • value_type (ValueType) – type of value

abstract _set_data(value)[source]

Writes parameter value back to the model.

Parameters

value (object) – value to write

Returns

True if the operation was successful, False otherwise

Return type

bool

spinetoolbox.widgets.persistent_console_widget
Module Contents
Classes

_CustomLineEdit

PersistentConsoleWidget

A widget to interact with a persistent process.

AnsiEscapeCodeHandler

Functions

_ansi_color(code[, bright])

class spinetoolbox.widgets.persistent_console_widget._CustomLineEdit(console)[source]

Bases: PySide6.QtWidgets.QPlainTextEdit

property min_pos[source]
property new_line_indent[source]
reset(current_prompt)[source]
new_line()[source]
formatted_text()[source]
raw_text()[source]
set_raw_text(text)[source]
_handle_text_changed()[source]

Add indent to new lines.

_handle_cursor_position_changed()[source]

Move cursor away from indent areas.

keyPressEvent(ev)[source]
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

property prompt[source]
property owner_names[source]
property _input_start_pos[source]
_command_checked[source]
_msg_available[source]
_command_finished[source]
_history_item_available[source]
_completions_available[source]
_restarted[source]
_killed[source]
_flush_needed[source]
_FLUSH_INTERVAL = 200[source]
_MAX_LINES_PER_SECOND = 2000[source]
_MAX_LINES_PER_CYCLE[source]
_MAX_LINES_COUNT = 2000[source]
closeEvent(ev)[source]
name()[source]

Returns console name for display purposes.

focusInEvent(ev)[source]
mouseMoveEvent(ev)[source]
mousePressEvent(ev)[source]
mouseReleaseEvent(ev)[source]
scrollContentsBy(dx, dy)[source]
_handle_contents_changed()[source]
_handle_selection_changed()[source]
_handle_cursor_position_changed()[source]
_handle_update_request(_rect, _dy)[source]

Move line edit to input start pos.

resizeEvent(ev)[source]
_move_and_resize_line_edit()[source]
_update_user_input()[source]
_start_flush_timer()[source]
_flush_text_buffer()[source]

Inserts all text from buffer.

_make_prompt()[source]
_make_prompt_block(prompt='')[source]
_insert_prompt(prompt='')[source]
_insert_stdin_text(cursor, text)[source]

Inserts highlighted text.

Parameters
  • cursor (QTextCursor) –

  • text (str) –

_do_insert_stdin_text(cursor, text)[source]
_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) –

_insert_text(cursor, text, with_prompt)[source]
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) –

_get_current_text()[source]
_get_prefix()[source]
_highlight_current_input()[source]
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.

_issue_command(text)[source]

Issues command.

Parameters

text (str) –

_do_check_command(text)[source]
_handle_command_checked(text, complete)[source]

Issues command.

Parameters

text (str) –

_do_issue_command(text)[source]
_handle_msg_available(msg_type, text)[source]
_handle_command_finished()[source]
_move_history(text, backwards)[source]

Moves history.

_do_move_history(text, backwards)[source]
_display_history_item(history_item, prefix)[source]
_autocomplete(text)[source]

Autocompletes current text in the prompt (or output options if multiple matches).

Parameters

text (str) –

_do_autocomplete(text)[source]
_display_completions(text, prefix, completions)[source]
_restart_persistent(_=False)[source]

Restarts underlying persistent process.

_do_restart_persistent()[source]
_handle_restarted()[source]
_interrupt_persistent(_=False)[source]

Sends a task to executor which will interrupt the underlying persistent process.

_do_interrupt_persistent()[source]

Interrupts the underlying persistent process.

_kill_persistent(_=False)[source]

Sends a task to executor which will kill the underlying persistent process.

_do_kill_persistent()[source]

Kills underlying persistent process.

_extend_menu(menu)[source]

Appends two more actions: Restart, and Interrupt.

Parameters

menu (QMenu) – where to append

contextMenuEvent(ev)[source]

Reimplemented to extend menu with custom actions.

class spinetoolbox.widgets.persistent_console_widget.AnsiEscapeCodeHandler(fg_color, bg_color)[source]
_make_default_format()[source]
endFormatScope()[source]
setFormatScope(char_format)[source]
parse_text(text)[source]
spinetoolbox.widgets.persistent_console_widget._ansi_color(code, bright=False)[source]
spinetoolbox.widgets.plain_parameter_value_editor

An editor widget for editing plain number database (relationship) parameter values.

Module Contents
Classes

PlainParameterValueEditor

A widget to edit float or boolean type parameter values.

class spinetoolbox.widgets.plain_parameter_value_editor.PlainParameterValueEditor(parent_widget=None)[source]

Bases: PySide6.QtWidgets.QWidget

A widget to edit float or boolean type parameter values.

Parameters

parent_widget (QWidget) – a parent widget

_set_number_or_string_enabled(on)[source]
_set_string_enabled(on)[source]
set_value(value)[source]

Sets the value to be edited in this widget.

value()[source]

Returns the value currently being edited.

spinetoolbox.widgets.plot_canvas

A Qt widget to use as a matplotlib backend.

Module Contents
Classes

LegendPosition

Generic enumeration.

PlotCanvas

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.

BOTTOM[source]
RIGHT[source]
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

property axes[source]

figure’s axes

Type

matplotlib.axes.Axes

property legend_axes[source]

figure’s legend axes

Type

matplotlib.axes.Axes

has_twinned_axes()[source]

Checks whether the axes have been twinned.

Returns

True if axes have been twinned, False otherwise

Return type

bool

twinned_axes()[source]

Returns twinned axes.

Returns

twinned axes

Return type

list of Axes

spinetoolbox.widgets.plot_widget

A Qt widget showing a toolbar and a matplotlib plotting canvas.

Module Contents
Classes

PlotWidget

A widget that contains a toolbar and a plotting canvas.

_PlotDataView

Custom QTableView class with copy and paste methods.

_PlotDataWidget

Functions

prepare_plot_in_window_menu(menu)

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

PlotCanvas

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

plot_windows[source]

A global list of plot windows.

closeEvent(event)[source]

Removes the window from plot_windows and closes.

contextMenuEvent(event)[source]

Shows plot context menu.

_get_plot_data()[source]

Gathers plot data into a table.

Returns

data as table

Return type

list of list

copy_plot_data()[source]

Copies plot data to clipboard.

show_plot_data()[source]

Opens a separate window that shows the plot data.

add_legend(handles)[source]

Adds a legend to the plot’s legend axes.

Parameters

handles (list) – legend handles

use_as_window(parent_window, document_name)[source]

Prepares the widget to be used as a window and adds it to plot_windows list.

Parameters
  • parent_window (QWidget) – a parent window

  • document_name (str) – a string to add to the window title

static _unique_window_name(document_name)[source]

Returns an unique identifier for a new plot window.

class spinetoolbox.widgets.plot_widget._PlotDataView(parent=None)[source]

Bases: spinetoolbox.widgets.custom_qtableview.CopyPasteTableView

Custom QTableView class with copy and paste methods.

contextMenuEvent(event)[source]
class spinetoolbox.widgets.plot_widget._PlotDataWidget(rows, parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

set_size_according_to_parent()[source]

Sets the size of the widget according to the parent widget’s dimensions and the data in the table

spinetoolbox.widgets.plot_widget.prepare_plot_in_window_menu(menu)[source]

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.

Module Contents
Classes

_InstallPluginModel

_ManagePluginsModel

InstallPluginDialog

Initialize class

ManagePluginsDialog

Initialize class

class spinetoolbox.widgets.plugin_manager_widgets._InstallPluginModel[source]

Bases: PySide6.QtGui.QStandardItemModel

data(index, role=None)[source]
class spinetoolbox.widgets.plugin_manager_widgets._ManagePluginsModel[source]

Bases: _InstallPluginModel

flags(index)[source]
class spinetoolbox.widgets.plugin_manager_widgets.InstallPluginDialog(parent)[source]

Bases: PySide6.QtWidgets.QDialog

Initialize class

item_selected[source]
populate_list(names)[source]
_handle_search_text_changed(_text)[source]
_filter_model()[source]
_handle_ok_clicked(_=False)[source]
_emit_item_selected(index)[source]
_update_ok_button_enabled(_selected, _deselected)[source]
class spinetoolbox.widgets.plugin_manager_widgets.ManagePluginsDialog(parent)[source]

Bases: PySide6.QtWidgets.QDialog

Initialize class

item_removed[source]
item_updated[source]
populate_list(names)[source]
_create_plugin_widget(plugin_name, can_update)[source]
_emit_item_removed(plugin_name)[source]
_emit_item_updated(plugin_name)[source]
spinetoolbox.widgets.project_item_drag

Classes for custom QListView.

Module Contents
Classes

ProjectItemDragMixin

Custom class with dragging support.

NiceButton

ProjectItemButtonBase

Custom class with dragging support.

ProjectItemButton

Custom class with dragging support.

ProjectItemSpecButton

Custom class with dragging support.

ShadeMixin

ShadeProjectItemSpecButton

Custom class with dragging support.

ShadeButton

_ChoppedIcon

_ChoppedIconEngine

ProjectItemSpecArray

An array of ProjectItemSpecButton that can be expanded/collapsed.

class spinetoolbox.widgets.project_item_drag.ProjectItemDragMixin(*args, **kwargs)[source]

Custom class with dragging support.

drag_about_to_start[source]
mouseMoveEvent(event)[source]

Start dragging action if needed

mouseReleaseEvent(event)[source]

Forget drag start position

class spinetoolbox.widgets.project_item_drag.NiceButton(*args, **kwargs)[source]

Bases: PySide6.QtWidgets.QToolButton

setText(text)[source]
set_orientation(orientation)[source]
class spinetoolbox.widgets.project_item_drag.ProjectItemButtonBase(toolbox, item_type, icon, parent=None)[source]

Bases: ProjectItemDragMixin, NiceButton

Custom class with dragging support.

set_colored_icons(colored)[source]
_handle_drag_about_to_start()[source]
mousePressEvent(event)[source]

Register drag start position

abstract _make_mime_data_text()[source]
class spinetoolbox.widgets.project_item_drag.ProjectItemButton(toolbox, item_type, icon, parent=None)[source]

Bases: ProjectItemButtonBase

Custom class with dragging support.

double_clicked[source]
_make_mime_data_text()[source]
mouseDoubleClickEvent(event)[source]
class spinetoolbox.widgets.project_item_drag.ProjectItemSpecButton(toolbox, item_type, icon, spec_name='', parent=None)[source]

Bases: ProjectItemButtonBase

Custom class with dragging support.

property spec_name[source]
_make_mime_data_text()[source]
contextMenuEvent(event)[source]
mouseDoubleClickEvent(event)[source]
class spinetoolbox.widgets.project_item_drag.ShadeMixin[source]
paintEvent(ev)[source]
class spinetoolbox.widgets.project_item_drag.ShadeProjectItemSpecButton(toolbox, item_type, icon, spec_name='', parent=None)[source]

Bases: ShadeMixin, ProjectItemSpecButton

Custom class with dragging support.

clone()[source]
class spinetoolbox.widgets.project_item_drag.ShadeButton(*args, **kwargs)[source]

Bases: ShadeMixin, NiceButton

class spinetoolbox.widgets.project_item_drag._ChoppedIcon(icon, size)[source]

Bases: PySide6.QtGui.QIcon

update()[source]
class spinetoolbox.widgets.project_item_drag._ChoppedIconEngine(icon, size)[source]

Bases: PySide6.QtGui.QIconEngine

update()[source]
pixmap(size, mode, state)[source]
class spinetoolbox.widgets.project_item_drag.ProjectItemSpecArray(toolbox, model, item_type, icon)[source]

Bases: PySide6.QtWidgets.QToolBar

An array of ProjectItemSpecButton that can be expanded/collapsed.

Parameters
set_colored_icons(colored)[source]
update()[source]
_update_button_visible_icon_color()[source]
set_color(color)[source]
paintEvent(ev)[source]
_get_first_chopped_index()[source]

Returns the index of the first chopped action (chopped = not drawn because of space).

Returns

list(QAction) int or NoneType

_add_filling(actions, ind)[source]

Adds a button to fill empty space after the last visible action.

Parameters
  • actions (list(QAction)) – actions

  • ind (int or NoneType) – index of the first chopped one or None if all are visible

_get_filling(previous)[source]

Returns the position and size of the filling widget.

Parameters

previous (QWidget) – last visible widget

Returns

position x int: position y int: width int: height

Return type

int

_populate_extension_menu(actions, ind)[source]

Populates extension menu with chopped actions.

Parameters
  • actions (list(QAction)) – actions

  • ind (int or NoneType) – index of the first chopped one or None if all are visible

showEvent(ev)[source]
_update_button_geom(orientation=None)[source]

Updates geometry of buttons given the orientation

Parameters

orientation (Qt.Orientation) –

_show_spec_form(_checked=False)[source]
toggle_visibility(_checked=False)[source]
set_visible(visible)[source]
_insert_specs(parent, first, last)[source]
_remove_specs(parent, first, last)[source]
_remove_spec(row)[source]
_reset_specs()[source]
_add_spec(row)[source]
spinetoolbox.widgets.properties_widget

Contains PropertiesWidgetBase.

Module Contents
Classes

PropertiesWidgetBase

Properties widget base class.

class spinetoolbox.widgets.properties_widget.PropertiesWidgetBase(toolbox, base_color=None)[source]

Bases: PySide6.QtWidgets.QWidget

Properties widget base class.

property fg_color[source]
set_item(project_item)[source]

Sets the active project item.

Parameters

project_item (ProjectItem) – active project item

unset_item()[source]

Unsets the active project item.

set_color_and_icon(base_color, icon=None)[source]
eventFilter(obj, ev)[source]
paintEvent(ev)[source]

Paints background

spinetoolbox.widgets.report_plotting_failure

Functions to report failures in plotting to the user.

Module Contents
Functions

report_plotting_failure(error, parent_widget)

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.

Module Contents
Classes

SelectDatabaseItems

Widget that allows selecting database items.

Functions

add_check_boxes(check_boxes, checked_states, ...)

Adds check boxes to grid layout.

batch_set_check_state(boxes, checked)

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

checked_state_changed[source]
COLUMN_COUNT = 3[source]
_DATA_ITEMS = ('entity', 'entity_group', 'parameter_value', 'entity_metadata', 'parameter_value_metadata')[source]
_SCENARIO_ITEMS = ('alternative', 'scenario', 'scenario_alternative')[source]
checked_states()[source]

Collects the checked states of database items.

Returns

mapping from item name to checked state boolean

Return type

dict

any_checked()[source]

Checks if any of the checkboxes is checked.

Returns

True if any check box is checked, False otherwise

Return type

bool

any_structural_item_checked()[source]
_select_data_items(_=False)[source]

Checks all data items.

_select_scenario_items(_=False)[source]

Checks all scenario items.

spinetoolbox.widgets.set_description_dialog

A widget for editing project description

Module Contents
Classes

SetDescriptionDialog

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
property description[source]
_set_ok_enabled()[source]
accept()[source]
spinetoolbox.widgets.settings_widget

Widget for controlling user settings.

Module Contents
Classes

SettingsWidgetBase

param qsettings

Toolbox settings

SpineDBEditorSettingsMixin

SpineDBEditorSettingsWidget

A widget to change user's preferred settings, but only for the Spine db editor.

SettingsWidget

A widget to change user's preferred settings.

Functions

_get_kernel_name_by_exe(p, kernel_model)

Returns the kernel name corresponding to given executable or an empty string if not found.

_selected_project_matches_kernel_project(...)

Checks if given Julia kernel's project matches the given Julia project.

_samefile(a, b)

class spinetoolbox.widgets.settings_widget.SettingsWidgetBase(qsettings)[source]

Bases: PySide6.QtWidgets.QWidget

Parameters

qsettings (QSettings) – Toolbox settings

property qsettings[source]
connect_signals()[source]

Connect signals.

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

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.

save_settings()[source]

Gets selections and saves them to persistent memory.

update_ui_and_close()[source]

Updates UI to reflect current settings and close.

save_and_close()[source]

Saves settings and close.

class spinetoolbox.widgets.settings_widget.SpineDBEditorSettingsMixin[source]
connect_signals()[source]

Connect signals.

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.

update_ui()[source]
set_hide_empty_classes(checked=False)[source]
set_auto_expand_entities(checked=False)[source]
set_merge_dbs(checked=False)[source]
set_snap_entities(checked=False)[source]
set_max_entity_dimension_count(value=None)[source]
set_build_iters(value=None)[source]
set_spread_factor(value=None)[source]
set_neg_weight_exp(value=None)[source]
_set_graph_property(name, value)[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.

property db_mngr[source]
show()[source]
class spinetoolbox.widgets.settings_widget.SettingsWidget(toolbox)[source]

Bases: SpineDBEditorSettingsMixin, SettingsWidgetBase

A widget to change user’s preferred settings.

Parameters

toolbox (ToolboxUI) – Parent widget.

property db_mngr[source]
connect_signals()[source]

Connect signals.

_make_python_kernel_context_menu()[source]

Returns a context-menu for Python kernel comboBox.

_make_julia_kernel_context_menu()[source]

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.

_show_install_julia_wizard(_=False)[source]

Opens Install Julia Wizard.

_show_add_up_spine_opt_wizard(_=False)[source]

Opens the add/update SpineOpt wizard.

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.

show_python_kernel_context_menu_on_combobox(pos)[source]

Shows the context-menu on Python kernels combobox.

show_julia_kernel_context_menu_on_combobox(pos)[source]

Shows the context-menu on Julia kernels combobox.

show_python_kernel_context_menu_on_combobox_list(pos)[source]

Shows the context-menu on Python kernels combobox popup list.

show_julia_kernel_context_menu_on_combobox_list(pos)[source]

Shows the context-menu on Julia kernels combobox popup list.

_open_python_kernel_resource_dir(_=False)[source]

Opens Python kernels resource dir.

_open_julia_kernel_resource_dir(_=False)[source]

Opens Julia kernels resource dir.

open_rsc_dir(item)[source]

Open path hidden in given item’s tooltip in file browser.

browse_work_path(_=False)[source]

Open file browser where user can select the path to wanted work directory.

show_color_dialog(_=False)[source]

Lets user pick the background color from a color dialog.

update_bg_color()[source]

Set tool button icon as the selected color and update Design View scene background color.

update_scene_bg(_=False)[source]

Draw background on scene depending on radiobutton states.

update_items_path(checked=False)[source]
set_toolbar_colored_icons(checked=False)[source]
_update_properties_widget(_checked=False)[source]
read_settings()[source]

Read saved settings from app QSettings instance and update UI to display them.

_read_engine_settings()[source]

Reads Engine settings and sets the corresponding UI elements.

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

_get_julia_settings()[source]
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

start_fetching_julia_kernels()[source]

Starts a thread for fetching Julia kernels.

stop_fetching_julia_kernels()[source]

Terminates the kernel fetcher thread.

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()[source]

Starts a thread for fetching Python kernels.

stop_fetching_python_kernels()[source]

Terminates the kernel fetcher thread.

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.

closeEvent(ev)[source]
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 containing items, which contain kernel spec details as item data

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.settings_widget._samefile(a, b)[source]
spinetoolbox.widgets.statusbars

Functions to make and handle QStatusBars.

Module Contents
Classes

MainStatusBar

A status bar for the main toolbox window.

class spinetoolbox.widgets.statusbars.MainStatusBar(toolbox)[source]

Bases: PySide6.QtWidgets.QStatusBar

A status bar for the main toolbox window.

Parameters

toolbox (ToolboxUI) –

_ALL_RUNS = 'All executions'[source]
_populate_executions_menu()[source]
reset_executions_button_text()[source]
_select_execution(action)[source]
spinetoolbox.widgets.time_pattern_editor

An editor widget for editing a time pattern type (relationship) parameter values.

Module Contents
Classes

TimePatternEditor

A widget for editing time patterns.

class spinetoolbox.widgets.time_pattern_editor.TimePatternEditor(parent=None)[source]

Bases: PySide6.QtWidgets.QWidget

A widget for editing time patterns.

Parameters

parent (QWidget) – parent widget

_show_table_context_menu(position)[source]

Opens the table’s context menu.

Parameters

position (QPoint) – menu’s position on the table

set_value(value)[source]

Sets the parameter_value to be edited.

value()[source]

Returns the parameter_value currently being edited.

_open_header_editor(column)[source]
spinetoolbox.widgets.time_series_fixed_resolution_editor

Contains logic for the fixed step time series editor widget.

Module Contents
Classes

TimeSeriesFixedResolutionEditor

A widget for editing time series data with a fixed time step.

Functions

_resolution_to_text(resolution)

Converts a list of durations into a string of comma-separated durations.

_text_to_resolution(text)

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

_resolution_changed()[source]

Updates the models after resolution change.

_show_table_context_menu(position)[source]

Shows the table’s context menu.

Parameters

position (QPoint) – menu’s position in table view’s coordinates

_select_date(selected_date)[source]
set_value(value)[source]

Sets the parameter_value for editing in this widget.

_show_calendar()[source]
_start_time_changed()[source]

Updates the model due to start time change.

_update_plot(topLeft=None, bottomRight=None, roles=None)[source]

Updated the plot.

value()[source]

Returns the parameter_value currently being edited.

_open_header_editor(column)[source]
spinetoolbox.widgets.time_series_variable_resolution_editor

Contains logic for the variable resolution time series editor widget.

Module Contents
Classes

TimeSeriesVariableResolutionEditor

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

_show_table_context_menu(position)[source]

Shows the table’s context menu.

Parameters

position (QPoint) – menu’s position on the table

set_value(value)[source]

Sets the time series being edited.

_update_plot(topLeft=None, bottomRight=None, roles=None)[source]

Updates the plot widget.

value()[source]

Return the time series currently being edited.

_open_header_editor(column)[source]
spinetoolbox.widgets.toolbars

Functions to make and handle QToolBars.

Module Contents
Classes

ToolBar

Base class for Toolbox toolbars.

PluginToolBar

A plugin toolbar.

MainToolBar

The main application toolbar: Items | Execute

PaddingLabel

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

abstract 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

class spinetoolbox.widgets.toolbars.PluginToolBar(name, parent)[source]

Bases: ToolBar

A plugin toolbar.

Parameters

parent (ToolboxUI) – QMainWindow instance

setup(plugin_specs, disabled_names)[source]

Sets up the toolbar.

Parameters
  • plugin_specs (dict) – mapping from specification name to specification

  • disabled_names (Iterable of str) – specifications that should be disabled

set_color(color)[source]

Sets toolbar’s background color.

Parameters

color (QColor) – background color

_update_spec_button_name(old_name, new_name)[source]
class spinetoolbox.widgets.toolbars.MainToolBar(execute_project_action, execute_selection_action, stop_execution_action, parent)[source]

Bases: ToolBar

The main application toolbar: Items | Execute

Parameters
  • execute_project_action (QAction) – action to execute project

  • execute_selection_action (QAction) – action to execute selected items

  • stop_execution_action (QAction) – action to stop execution

  • parent (ToolboxUI) – QMainWindow instance

_SEPARATOR = ';;'[source]
set_project_actions_enabled(enabled)[source]

Enables or disables project related actions.

Parameters

enabled (bool) – True to enable actions, False to disable

set_color(color)[source]

Sets toolbar’s background color.

Parameters

color (QColor) – background color

setup()[source]
add_project_item_buttons()[source]
_add_project_item_button(item_type, factory, colored)[source]
set_colored_icons(colored)[source]
_make_tool_button(icon, text, slot, 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

_add_tool_button(button)[source]

Adds a button to the toolbar.

Parameters

button (QToolButton) – button to add

add_execute_buttons()[source]

Adds project execution buttons to the toolbar.

dragLeaveEvent(event)[source]
dragEnterEvent(event)[source]
dragMoveEvent(event)[source]
dropEvent(event)[source]
_update_drop_actions(event)[source]

Updates source and target actions for drop operation:

Parameters

event (QDragMoveEvent) –

paintEvent(ev)[source]

Draw a line as drop indicator.

_drop_line()[source]
icon_ordering()[source]
class spinetoolbox.widgets.toolbars.PaddingLabel(*args, **kwargs)[source]

Bases: PySide6.QtWidgets.QLabel

Submodules

spinetoolbox.__main__

Spine Toolbox application main file.

Module Contents
spinetoolbox.__main__.return_code[source]
spinetoolbox._version
Module Contents
spinetoolbox._version.TYPE_CHECKING = False[source]
spinetoolbox._version.VERSION_TUPLE[source]
spinetoolbox._version.version: str[source]
spinetoolbox._version.__version__: str[source]
spinetoolbox._version.__version_tuple__: VERSION_TUPLE[source]
spinetoolbox._version.version_tuple: VERSION_TUPLE[source]
spinetoolbox.config

Application constants and style sheets

Module Contents
spinetoolbox.config.LATEST_PROJECT_VERSION = 11[source]
spinetoolbox.config.REQUIRED_SPINE_OPT_VERSION = '0.6.9'[source]
spinetoolbox.config.INVALID_CHARS = ['<', '>', ':', '"', '/', '\\', '|', '?', '*', '.'][source]
spinetoolbox.config.INVALID_FILENAME_CHARS = ['<', '>', ':', '"', '/', '\\', '|', '?', '*'][source]
spinetoolbox.config._frozen[source]
spinetoolbox.config._path_to_executable[source]
spinetoolbox.config.APPLICATION_PATH[source]
spinetoolbox.config._program_root[source]
spinetoolbox.config.DEFAULT_WORK_DIR[source]
spinetoolbox.config.DOCUMENTATION_PATH[source]
spinetoolbox.config.ONLINE_DOCUMENTATION_URL = 'https://spine-toolbox.readthedocs.io/en/master/'[source]
spinetoolbox.config.PLUGINS_PATH[source]
spinetoolbox.config.PLUGIN_REGISTRY_URL = 'https://spine-tools.github.io/PluginRegistry/registry.json'[source]
spinetoolbox.config.JUPYTER_KERNEL_TIME_TO_DEAD = 20[source]
spinetoolbox.config.PROJECT_FILENAME = 'project.json'[source]
spinetoolbox.config.PROJECT_LOCAL_DATA_DIR_NAME = 'local'[source]
spinetoolbox.config.PROJECT_LOCAL_DATA_FILENAME = 'project_local_data.json'[source]
spinetoolbox.config.SPECIFICATION_LOCAL_DATA_FILENAME = 'specification_local_data.json'[source]
spinetoolbox.config.PROJECT_ZIP_FILENAME = 'project_package'[source]
spinetoolbox.config.STATUSBAR_SS = 'QStatusBar{background-color: #EBEBE0; border-width: 1px; border-color: gray; border-style: groove;}'[source]
spinetoolbox.config.BG_COLOR = '#19232D'[source]
spinetoolbox.config.FG_COLOR = '#F0F0F0'[source]
spinetoolbox.config.SETTINGS_SS[source]
spinetoolbox.config.TEXTBROWSER_SS[source]
spinetoolbox.config.MAINWINDOW_SS[source]
spinetoolbox.execution_managers

Classes to manage tool instance execution in various forms.

Module Contents
Classes

ExecutionManager

Base class for all tool instance execution managers.

QProcessExecutionManager

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

execution_finished[source]
abstract start_execution(workdir=None)[source]

Starts the execution.

Parameters

workdir (str) – Work directory

abstract stop_execution()[source]

Stops the execution.

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

program()[source]

Program getter method.

args()[source]

Program argument getter method.

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

process_started()[source]

Run when subprocess has started.

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.

stop_execution()[source]

See base class.

on_process_finished(exit_code, exit_status)[source]

Runs when subprocess has finished.

Parameters
  • exit_code (int) – Return code from external program (only valid for normal exits)

  • exit_status (int) – Crash or normal exit (QProcess::ExitStatus)

on_ready_stdout()[source]

Emit data from stdout.

on_ready_stderr()[source]

Emit data from stderr.

spinetoolbox.fetch_parent

The FetchParent and FlexibleFetchParent classes.

Module Contents
Classes

FetchParent

param index

an index to speedup looking up fetched items

ItemTypeFetchParent

param index

an index to speedup looking up fetched items

FlexibleFetchParent

param index

an index to speedup looking up fetched items

FetchIndex

dict() -> new empty dictionary

_ItemCallback

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.

property index[source]
abstract property fetch_item_type[source]

Returns the DB item type to fetch, e.g., “entity_class”.

Returns

str

property is_obsolete[source]
property is_fetched[source]
property is_busy[source]
_changes_pending[source]
apply_changes_immediately()[source]
reset()[source]

Resets fetch parent as if nothing was ever fetched.

position(db_map)[source]
increment_position(db_map)[source]
_apply_pending_changes()[source]
bind_item(item, db_map)[source]
_make_restore_item_callback(db_map)[source]
_make_update_item_callback(db_map)[source]
_make_remove_item_callback(db_map)[source]
_is_valid(version)[source]
add_item(item, db_map, version=None)[source]
update_item(item, db_map, version=None)[source]
remove_item(item, db_map, version=None)[source]
key_for_index(db_map)[source]

Returns the key for this parent in the index.

Parameters

db_map (DiffDatabaseMapping) –

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(), or handle_items_removed() with all the items that pass this test.

Parameters
  • item (dict) – The item

  • db_map (DiffDatabaseMapping) –

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 (DiffDatabaseMapping) –

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 DiffDatabaseMapping 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 DiffDatabaseMapping instances to list of dict-items for which accepts_item() returns True.

abstract handle_items_updated(db_map_data)[source]

Called by SpineDBWorker when items are updated in the DB.

Parameters

db_map_data (dict) – Mapping DiffDatabaseMapping 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 DiffDatabaseMapping 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 DiffDatabaseMapping instances to list of dict-items for which accepts_item() returns True.

abstract handle_items_updated(db_map_data)[source]

Called by SpineDBWorker when items are updated in the DB.

Parameters

db_map_data (dict) – Mapping DiffDatabaseMapping instances to list of dict-items for which accepts_item() returns True.

__str__()[source]
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 (DiffDatabaseMapping) –

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 DiffDatabaseMapping 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 DiffDatabaseMapping 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 DiffDatabaseMapping 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(), or handle_items_removed() with all the items that pass this test.

Parameters
  • item (dict) – The item

  • db_map (DiffDatabaseMapping) –

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 (DiffDatabaseMapping) –

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.

reset()[source]
abstract process_item(item, db_map)[source]
position(db_map)[source]
increment_position(db_map)[source]
get_items(key, db_map)[source]
class spinetoolbox.fetch_parent._ItemCallback(fn, *args)[source]
__call__(item)[source]
__str__()[source]

Return str(self).

spinetoolbox.headless

Contains facilities to open and execute projects without GUI.

Module Contents
Classes

HeadlessLogger

A LoggerInterface compliant logger that uses Python's standard logging facilities.

ModifiableProject

A simple project that is available for modification script.

ActionsWithProject

A 'task' which opens Toolbox project and operates on it.

Status

Status codes returned from headless execution.

Functions

headless_main(args)

Executes a project using QCoreApplication.

open_project(project_dict, project_dir, logger)

Opens a project.

_specification_dicts(project_dict, project_dir, logger)

Loads project item specification dictionaries.

class spinetoolbox.headless.HeadlessLogger[source]

Bases: PySide6.QtCore.QObject

A LoggerInterface compliant logger that uses Python’s standard logging facilities.

msg[source]

Emits a notification message.

msg_success[source]

Emits a message on success

msg_warning[source]

Emits a warning message.

msg_error[source]

Emits an error message.

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).

information_box[source]

Requests an ‘information message box’ (e.g. a message window) to be opened with a given title and message.

error_box[source]

Requests an ‘error message box’ to be opened with a given title and message.

_log_message(message)[source]

Prints an information message.

_log_warning(message)[source]

Prints a warning message.

_log_error(message)[source]

Prints an error message.

_show_information_box(title, message)[source]

Prints an information message with a title.

_show_error_box(title, message)[source]

Prints an error message with a title.

_print(message, out_stream)[source]

Filters HTML tags from message before printing it to given file.

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

property project_dir[source]
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

items_to_dict()[source]

Stores project items back to dictionaries.

Returns

item dictionaries

Return type

dict

connections_to_dict()[source]

Stores connections back to dictionaries.

Returns

connection dictionaries

Return type

list of 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.

_dags()[source]
_execute()[source]

Executes this task.

_open_project()[source]

Opens a project.

Returns

status code

Return type

Status

_check_project_version(project_dict)[source]

Checks project dict version.

Parameters

project_dict (dict) – project dict

Returns

status code

Return type

Status

_exec_mod_script()[source]

Executes project modification script given in command line arguments.

Returns

status code

Return type

Status

_execute_project()[source]

Executes all DAGs in a project.

Returns

status code

Return type

Status

_process_engine_event(event_type, data)[source]
event(e)[source]
_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

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 dir

  • logger (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 dir

  • logger (LoggerInterface) – a logger

Returns

a mapping from item type to a list of specification dicts

Return type

dict

class spinetoolbox.headless.Status[source]

Bases: enum.IntEnum

Status codes returned from headless execution.

Initialize self. See help(type(self)) for accurate signature.

OK = 0[source]
ERROR = 1[source]
ARGUMENT_ERROR = 2[source]
spinetoolbox.helpers

General helper functions and classes.

Module Contents
Classes

LinkType

Graphics scene's link types.

IconListManager

A class to manage icons for icon list widgets.

TransparentIconEngine

Specialization of QIconEngine with transparent background.

CharIconEngine

Specialization of QIconEngine used to draw font-based icons.

ColoredIcon

ColoredIconEngine

ProjectDirectoryIconProvider

QFileIconProvider that provides a Spine icon to the

ChildCyclingKeyPressFilter

Event filter class for catching next and previous child key presses.

QuietLogger

SignalWaiter

A 'traffic light' that allows waiting for a signal to be emitted in another thread.

CustomSyntaxHighlighter

HTMLTagFilter

HTML tag filter.

Functions

home_dir()

Returns user's home dir

format_log_message(msg_type, message[, show_datetime])

Adds color tags and optional time stamp to message.

busy_effect(func)

Decorator to change the mouse cursor to 'busy' while a function is processed.

create_dir(base_path[, folder, verbosity])

Create (input/output) directories recursively.

rename_dir(old_dir, new_dir, toolbox, box_title)

Renames directory. Called by ProjectItemModel.set_item_name()

open_url(url)

Opens the given url in the appropriate Web browser for the user's desktop environment,

set_taskbar_icon()

Set application icon to Windows taskbar.

supported_img_formats()

Checks if reading .ico files is supported.

pyside6_version_check()

Check that PySide6 version is at least 6.4.

get_datetime(show[, date])

Returns date and time string for appending into Event Log messages.

copy_files(src_dir, dst_dir[, includes, excludes])

Function for copying files. Does not copy folders.

erase_dir(path[, verbosity])

Deletes a directory and all its contents without prompt.

recursive_overwrite(logger, src, dst[, ignore, silent])

Copies everything from source directory to destination directory recursively.

tuple_itemgetter(itemgetter_func, num_indexes)

Change output of itemgetter to always be a tuple even for a single index.

format_string_list(str_list)

Returns a html unordered list from the given list of strings.

rows_to_row_count_tuples(rows)

Breaks a list of rows into a list of (row, count) tuples corresponding to chunks of successive rows.

object_icon(display_icon)

Creates and returns a QIcon corresponding to display_icon.

color_pixmap(pixmap, color)

make_icon_id(icon_code, color_code)

Takes icon and color codes, and return equivalent integer.

interpret_icon_id(display_icon)

Takes a display icon id and returns an equivalent tuple of icon and color code.

default_icon_id()

Creates a default icon id.

ensure_window_is_on_screen(window, size)

Checks if window is on screen and if not, moves and resizes it to make it visible on the primary screen.

first_non_null(s)

Returns the first element in Iterable s that is not None.

get_save_file_name_in_last_dir(qsettings, key, parent, ...)

Calls QFileDialog.getSaveFileName in the directory that was selected last time the dialog was accepted.

get_open_file_name_in_last_dir(qsettings, key, parent, ...)

try_number_from_string(text)

Tries to convert a string to integer or float.

focused_widget_has_callable(parent, callable_name)

Returns True if the currently focused widget or one of its ancestors has the given callable.

call_on_focused_widget(parent, callable_name)

Calls the given callable on the currently focused widget or one of its ancestors.

select_gams_executable(parent, line_edit)

Opens file browser where user can select a Gams executable (i.e. gams.exe on Windows).

select_julia_executable(parent, line_edit)

Opens file browser where user can select a Julia executable (i.e. julia.exe on Windows).

select_julia_project(parent, line_edit)

Shows file browser and inserts selected julia project dir to give line_edit.

select_python_interpreter(parent, line_edit)

Opens file browser where user can select a python interpreter (i.e. python.exe on Windows).

select_conda_executable(parent, line_edit)

Opens file browser where user can select a conda executable.

select_certificate_directory(parent, line_edit)

Shows file browser and inserts selected certificate directory to given line edit.

file_is_valid(parent, file_path, msgbox_title[, ...])

Checks that given path is not a directory and it's a file that actually exists.

dir_is_valid(parent, dir_path, msgbox_title)

Checks that given path is a directory. Needed in

make_settings_dict_for_engine(app_settings)

Converts Toolbox settings to a dictionary acceptable by Engine.

make_icon_background(color)

make_icon_toolbar_ss(color)

color_from_index(i, count[, base_hue, saturation, value])

unique_name(prefix, existing)

Creates a unique name in the form prefix (xx) where xx is a counter value.

get_upgrade_db_promt_text(url, current, expected)

parse_specification_file(spec_path, logger)

Parses specification file.

load_specification_from_file(spec_path, ...)

Returns an Item specification from a definition file.

specification_from_dict(spec_dict, local_data_dict, ...)

Returns item specification from a dictionary.

plugins_dirs(app_settings)

Loads plugins.

load_plugin_dict(plugin_dir, logger)

Loads plugin dict from plugin directory.

load_plugin_specifications(plugin_dict, ...)

Loads plugin's specifications.

load_specification_local_data(config_dir)

Loads specifications' project-specific data.

parameter_identifier(database, parameter, names, ...)

Concatenates given information into parameter value identifier string.

disconnect(signal, *slots)

Disconnects signal for the duration of a 'with' block.

signal_waiter(signal[, condition, timeout])

inquire_index_name(model, column, title, parent_widget)

Asks for indexed parameter's index name and updates model accordingly.

preferred_row_height(widget[, factor])

restore_ui(window, app_settings, settings_group)

Restores UI state from previous session.

save_ui(window, app_settings, settings_group)

Saves UI state for next session.

bisect_chunks(current_data, new_data[, key])

Finds insertion points for chunks of data using binary search.

load_project_dict(project_config_dir, logger)

Loads project dictionary from project directory.

load_local_project_data(project_config_dir, logger)

Loads local project data.

merge_dicts(source, target)

Merges two dictionaries that may contain nested dictionaries recursively.

fix_lightness_color(color[, lightness])

scrolling_to_bottom(widget[, tolerance])

_is_metadata_item(item)

Identifies a database metadata record.

same_path(path1, path2)

Checks if two paths are equal.

solve_connection_file(connection_file, ...)

Returns the connection_file path, if it exists on this computer. If the path

Attributes

_matplotlib_version

DB_ITEM_SEPARATOR

Display string to separate items such as entity names.

spinetoolbox.helpers._matplotlib_version[source]
class spinetoolbox.helpers.LinkType[source]

Bases: enum.Enum

Graphics scene’s link types.

CONNECTION = 'connection'[source]
JUMP = 'jump'[source]
spinetoolbox.helpers.home_dir()[source]

Returns user’s home dir

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. Called by ProjectItemModel.set_item_name()

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.set_taskbar_icon()[source]

Set application icon to Windows taskbar.

spinetoolbox.helpers.supported_img_formats()[source]

Checks if reading .ico files is supported.

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

init_model()[source]

Init model that can be used to display all icons in a list.

_model_data(index, role)[source]

Creates pixmaps as they’re requested by the data() method, to reduce loading time.

Parameters
  • index (QModelIndex) – index to the model

  • role (int) – data role

Returns

role-dependent model data

Return type

Any

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.

pixmap(size=QSize(512, 512), mode=None, state=None)[source]
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) –

paint(painter, rect, mode=None, state=None)[source]
class spinetoolbox.helpers.ColoredIcon(icon_file_name, icon_color, icon_size, colored=None)[source]

Bases: PySide6.QtGui.QIcon

set_colored(colored)[source]
color(mode=QIcon.Normal)[source]
class spinetoolbox.helpers.ColoredIconEngine(icon_file_name, icon_color, icon_size, colored=None)[source]

Bases: PySide6.QtGui.QIconEngine

color(mode=QIcon.Normal)[source]
set_colored(colored)[source]
_do_make_pixmap(mode, state)[source]
_make_pixmap(mode, state)[source]
pixmap(size, mode, state)[source]
spinetoolbox.helpers.color_pixmap(pixmap, color)[source]
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.

icon(info)[source]

Returns an icon for the file described by info.

Parameters

info (QFileInfo) – File (or directory) info

Returns

Icon for a file system resource with the given info

Return type

QIcon

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.

eventFilter(obj, event)[source]
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).

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). Used in SettingsWidget and KernelEditor.

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 file browser and inserts selected julia project dir to give line_edit. Used in SettingsWidget and KernelEditor.

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). Used in SettingsWidget and KernelEditor.

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.file_is_valid(parent, file_path, msgbox_title, extra_check=None)[source]

Checks that given path is not a directory and it’s a file that actually 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

class spinetoolbox.helpers.QuietLogger[source]
__getattr__(_)[source]
__call__(*args, **kwargs)[source]
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.make_icon_background(color)[source]
spinetoolbox.helpers.make_icon_toolbar_ss(color)[source]
spinetoolbox.helpers.color_from_index(i, count, base_hue=0.0, saturation=1.0, value=1.0)[source]
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.get_upgrade_db_promt_text(url, current, expected)[source]
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

trigger(*args)[source]

Signal receiving slot.

wait()[source]

Wait for signal to be received.

spinetoolbox.helpers.signal_waiter(signal, condition=None, timeout=None)[source]
class spinetoolbox.helpers.CustomSyntaxHighlighter(*arg, **kwargs)[source]

Bases: PySide6.QtGui.QSyntaxHighlighter

property formats[source]
set_style(style)[source]
yield_formats(text)[source]
highlightBlock(text)[source]
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.preferred_row_height(widget, factor=1.5)[source]
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.fix_lightness_color(color, lightness=240)[source]
spinetoolbox.helpers.scrolling_to_bottom(widget, tolerance=1)[source]
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.

drain()[source]
handle_data(data)[source]
handle_starttag(tag, attrs)[source]
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

spinetoolbox.kernel_fetcher

Contains a class for fetching kernel specs in a thread.

Module Contents
Classes

KernelFetcher

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

kernel_found[source]
stop_fetcher[source]
stop_thread()[source]

Slot for handling a request to stop the thread.

get_all_regular_kernels()[source]

Finds all kernel specs as quickly as possible.

get_all_conda_kernels()[source]

Finds auto-generated Conda kernels.

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.load_project_items

Functions to load project item modules.

Module Contents
Functions

load_project_items(items_package_name)

Loads project item modules.

_find_module_material(module)

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.load_project_items._find_module_material(module)[source]
spinetoolbox.log_mixin

Contains LogMixin.

Module Contents
Classes

LogMixin

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

add_event_message(filter_id, msg_type, msg_text)[source]

Adds a message to the log document.

Parameters
  • filter_id (str) – filter identifier

  • msg_type (str) – message type

  • msg_text (str) – message text

add_process_message(filter_id, msg_type, msg_text)[source]

Adds a message to the log document.

Parameters
  • filter_id (str) – filter identifier

  • msg_type (str) – message type

  • msg_text (str) – message text

spinetoolbox.logger_interface

A logger interface.

Module Contents
Classes

LoggerInterface

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[source]

Emits a notification message.

msg_success[source]

Emits a message on success

msg_warning[source]

Emits a warning message.

msg_error[source]

Emits an error message.

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).

information_box[source]

Requests an ‘information message box’ (e.g. a message window) to be opened with a given title and message.

error_box[source]

Requests an ‘error message box’ to be opened with a given title and message.

spinetoolbox.main

Provides the main() function.

Module Contents
Functions

main()

Creates main window GUI and starts main event loop.

_make_argument_parser()

Returns a command line argument parser configured for Toolbox use.

_add_pywin32_system32_to_path()

Adds a directory to PATH on Windows that is required to make pywin32 work

Attributes

dirname

plugin_path

spinetoolbox.main.dirname[source]
spinetoolbox.main.plugin_path[source]
spinetoolbox.main.main()[source]

Creates main window GUI and starts main event loop.

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
Classes

MetaObject

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

set_name(name)[source]

Set object name and short name. Note: Check conflicts (e.g. name already exists) before calling this method.

Parameters

name (str) – New (long) name for this object

set_description(description)[source]

Set object description.

Parameters

description (str) – Object description

spinetoolbox.plotting

Functions for plotting on PlotWidget.

Module Contents
Classes

PlotType

Generic enumeration.

IndexName

XYData

Two-dimensional data for plotting.

TreeNode

A labeled node in tree structure.

ParameterTableHeaderSection

Header section info for Database editor's parameter tables.

_PlotStackedBars

Functions

convert_indexed_value_to_tree(value)

Converts indexed values to tree nodes recursively.

turn_node_to_xy_data(root_node, y_label_position[, ...])

Constructs plottable data and indexes recursively.

raise_if_not_common_x_labels(data_list)

Raises an exception if data has different x axis labels.

raise_if_incompatible_x(data_list)

Raises an exception if the types of x data don't match.

reduce_indexes(data_list)

Removes redundant indexes from given XYData.

combine_data_with_same_indexes(data_list)

Combines data with same data indexes into the same x axis.

_always_single_y_axis(plot_type)

Returns True if a single y-axis should be used.

plot_data(data_list[, plot_widget, plot_type])

Returns a plot widget with plots of the given data.

_plot_single_y_axis(data_list, y_label, axes, plot_type)

Plots all data on single y-axis.

_plot_stacked_line(data_list, y_label, axes)

Plots all data as stacked lines.

_plot_bar(data_list, y_label, axes)

Plots all data as bars.

_plot_double_y_axis(data_list, y_labels, plot_widget, ...)

Plots all data on two y-axes.

_make_x_plottable(xs)

Converts x-axis values to something matplotlib can handle.

_make_plot_function(plot_type, x_data_type, axes)

Decides plot method and default keyword arguments based on XYData.

_plot_or_step(x_data_type, axes)

Makes choice between Axes.plot() and Axes.step().

_bar(x, y, axes, **kwargs)

Plots bar chart on axes but returns patches instead of bar container.

_group_bars(data_list)

Gives data with same x small offsets to prevent bar stacking.

_clear_plot(plot_widget)

Removes plots and legend from plot widget.

_limit_string_x_tick_labels(data, plot_widget)

Limits the number of x tick labels in case x-axis consists of strings.

_table_display_row(row)

Calculates a human-readable row number.

plot_parameter_table_selection(model, model_indexes, ...)

Returns a plot widget with plots of the selected indexes.

plot_value_editor_table_selection(model, model_indexes)

Returns a plot widget with plots of the selected indexes.

plot_pivot_table_selection(model, model_indexes[, ...])

Returns a plot widget with plots of the selected indexes.

plot_db_mngr_items(items, db_maps[, plot_widget])

Returns a plot widget with plots of database manager parameter value items.

_has_x_column(model, source_model)

Checks if pivot source model has x column.

_set_default_node(root_node, key, label)

Gets node from the contents of root_node adding a new node if necessary.

_get_parsed_value(model_index, display_row)

Gets parsed value from model.

_pivot_index_names(indexes)

Gathers index names from pivot table.

_pivot_display_row(row, source_model)

Calculates display row for pivot table.

_convert_to_leaf(y)

Converts parameter value to leaf TreeElement.

add_row_to_exception(row, display_row)

Adds row information to PlottingError if it is raised in the with block.

add_array_plot(plot_widget, value)

Adds an array plot to a plot widget.

add_time_series_plot(plot_widget, value)

Adds a time series step plot to a plot widget.

Attributes

LEGEND_PLACEMENT_THRESHOLD

_BASE_SETTINGS

_SCATTER_PLOT_SETTINGS

_LINE_PLOT_SETTINGS

_SCATTER_LINE_PLOT_SETTINGS

_TIME_SERIES_PLOT_SETTINGS

spinetoolbox.plotting.LEGEND_PLACEMENT_THRESHOLD = 8[source]
class spinetoolbox.plotting.PlotType[source]

Bases: enum.Enum

Generic enumeration.

Derive from this class to define new enumerations.

SCATTER[source]
SCATTER_LINE[source]
LINE[source]
STACKED_LINE[source]
BAR[source]
STACKED_BAR[source]
spinetoolbox.plotting._BASE_SETTINGS[source]
spinetoolbox.plotting._SCATTER_PLOT_SETTINGS[source]
spinetoolbox.plotting._LINE_PLOT_SETTINGS[source]
spinetoolbox.plotting._SCATTER_LINE_PLOT_SETTINGS[source]
spinetoolbox.plotting._TIME_SERIES_PLOT_SETTINGS[source]
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.IndexName[source]
label: str[source]
id: int[source]
class spinetoolbox.plotting.XYData[source]

Two-dimensional data for plotting.

x: List[Union[float, int, str, numpy.datetime64]][source]
y: List[Union[float, int]][source]
x_label: IndexName[source]
y_label: str[source]
data_index: List[str][source]
index_names: List[IndexName][source]
class spinetoolbox.plotting.TreeNode[source]

A labeled node in tree structure.

label: Union[str, IndexName][source]
content: Dict[source]
class spinetoolbox.plotting.ParameterTableHeaderSection[source]

Header section info for Database editor’s parameter tables.

label: str[source]
separator: Optional[str][source]
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

TreeNode

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

class spinetoolbox.plotting._PlotStackedBars(axes)[source]
__call__(x, height, **kwargs)[source]
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._plot_or_step(x_data_type, axes)[source]

Makes choice between Axes.plot() and Axes.step().

Parameters
  • x_data_type (Type) – data type of x-axis

  • axes (Axes) – plot axes

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

PlotWidget

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

PlotWidget

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

PlotWidget

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
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.

Parameters
  • root_node (TreeNode) – root node

  • key (Hashable) – key to root_node contents

  • label (str) – label of possible new node

Returns

node at given key

Return type

TreeNode

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
Classes

PluginManager

Class for managing plugins.

_PluginWorker

Functions

_download_file(remote, local)

_download_plugin(plugin, plugin_local_dir)

spinetoolbox.plugin_manager._download_file(remote, local)[source]
spinetoolbox.plugin_manager._download_plugin(plugin, plugin_local_dir)[source]
class spinetoolbox.plugin_manager.PluginManager(toolbox)[source]

Class for managing plugins.

Parameters

toolbox (ToolboxUI) – Toolbox instance.

property plugin_toolbars[source]
property plugin_specs[source]
load_installed_plugins()[source]

Loads installed plugins and adds their specifications to toolbars.

reload_plugins_with_local_data()[source]

Reloads plugins that have project specific local data.

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

_create_worker()[source]
_clean_up_worker(worker)[source]
_load_registry()[source]
show_install_plugin_dialog(_=False)[source]
_do_show_install_plugin_dialog()[source]
_install_plugin(plugin_name)[source]

Installs plugin from the registry and loads it.

Parameters

plugin_name (str) – plugin name

_load_installed_plugin(plugin_local_dir)[source]
show_manage_plugins_dialog(_=False)[source]
_do_show_manage_plugins_dialog()[source]
_remove_plugin(plugin_name)[source]

Removes installed plugin.

Parameters

plugin_name (str) – plugin name

_update_plugin(plugin_name)[source]
exception spinetoolbox.plugin_manager.PluginWorkFailed[source]

Bases: Exception

Exception to signal plugin worker that something failed.

Initialize self. See help(type(self)) for accurate signature.

class spinetoolbox.plugin_manager._PluginWorker[source]

Bases: PySide6.QtCore.QObject

failed[source]
finished[source]
succeeded[source]
start(function, *args, **kwargs)[source]
_do_work()[source]
clean_up()[source]
spinetoolbox.project

Spine Toolbox project class.

Module Contents
Classes

ItemNameStatus

Generic enumeration.

SpineToolboxProject

Class for Spine Toolbox projects.

Functions

node_successors(g)

Returns a dict mapping nodes in topological order to a list of successors.

_edges_causing_loops(g)

Returns a list of edges whose removal from g results in it becoming acyclic.

_ranks(node_successors)

Calculates node ranks.

class spinetoolbox.project.ItemNameStatus[source]

Bases: enum.Enum

Generic enumeration.

Derive from this class to define new enumerations.

OK[source]
INVALID[source]
EXISTS[source]
SHORT_NAME_EXISTS[source]
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

property all_item_names[source]
property settings[source]
property connections[source]
property app_settings[source]
project_about_to_be_torn_down[source]

Emitted before project is being torn down.

project_execution_about_to_start[source]

Emitted just before the entire project is executed.

project_execution_finished[source]

Emitted after the entire project execution finishes.

connection_established[source]

Emitted after new connection has been added to project.

connection_about_to_be_removed[source]

Emitted before connection removal.

connection_updated[source]

Emitted after a connection has been updated.

jump_added[source]

Emitted after a jump has been added.

jump_about_to_be_removed[source]

Emitted before a jump is removed.

jump_updated[source]

Emitted after a jump has been replaced by another.

item_added[source]

Emitted after a project item has been added.

item_about_to_be_removed[source]

Emitted before project item removal.

item_renamed[source]

Emitted after project item has been renamed.

specification_added[source]

Emitted after a specification has been added.

specification_about_to_be_removed[source]

Emitted before a specification will be removed.

specification_replaced[source]

Emitted after a specification has been replaced.

specification_saved[source]

Emitted after a specification has been saved.

LOCAL_EXECUTION_JOB_ID = '1'[source]
toolbox()[source]

Returns Toolbox main window.

Returns

main window

Return type

ToolboxUI

_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

call_set_description(description)[source]
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

connection_from_dict(connection_dict)[source]
jump_from_dict(jump_dict)[source]
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

_specification_id()[source]

Creates an id for specification.

Returns

new id

Return type

int

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, silent=True)[source]

Adds a project to item project.

Parameters
  • item (ProjectItem) – item to add

  • silent (bool) – if True, don’t log messages

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

ProjectItem

get_items()[source]

Returns all project items.

Returns

all project items

Return type

list of ProjectItem

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

ItemNameStatus

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
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

remove_jump(jump)[source]

Removes a jump from the project.

Parameters

jump (Jump) – jump to remove

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

_update_jump_icons()[source]

Updates icons for all jumps in the project.

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_iterator()[source]

Iterates directed graphs in the project.

Yields

DiGraph

dag_with_node(node)[source]

Returns the DiGraph that contains the given node (project item) name (str).

restore_project_items(items_dict, item_factories, silent)[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

  • silent (bool) – if True, suppress a log messages

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

_execute_dags(dags, execution_permits_list)[source]
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

_handle_engine_worker_finished(worker)[source]
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

execute_project()[source]

Executes all dags in the project.

_validate_dags(dags)[source]

Validates dags and logs error messages.

Parameters

dags (Iterable) – dags to validate

Returns

validated dag

Return type

list

stop()[source]

Stops execution.

notify_resource_changes_to_predecessors(item)[source]

Updates resources for direct predecessors of given item.

Parameters

item (ProjectItem) – item whose resources have changed

_update_incoming_connection_and_jump_resources(item_name, trigger_resources)[source]
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

_update_outgoing_connection_and_jump_resources(item_name, trigger_resources)[source]
_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

_update_successor(successor, incoming_connections, resource_cache)[source]
_update_predecessor(predecessor, outgoing_connections, resource_cache)[source]
_is_dag_valid(dag)[source]
_update_ranks(dag)[source]
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

finalize_remote_execution(job_id)[source]

Sends a request to server to remove the project directory and removes the project ZIP file from client.y

Parameters

job_id (str) – job id

tear_down()[source]

Cleans up project.

spinetoolbox.project.node_successors(g)[source]

Returns a dict mapping nodes in topological order to a list of successors.

Parameters

g (DiGraph) –

Returns

dict

spinetoolbox.project._edges_causing_loops(g)[source]

Returns a list of edges whose removal from g results in it becoming acyclic.

Parameters

g (DiGraph) –

Returns

list

spinetoolbox.project._ranks(node_successors)[source]

Calculates node ranks.

Parameters

node_successors (dict) – a mapping from successor name to a list of predecessor names

Returns

a mapping from node name to rank

Return type

dict

spinetoolbox.project_commands

QUndoCommand subclasses for modifying the project.

Module Contents
Classes

SpineToolboxCommand

SetItemSpecificationCommand

Command to set the specification for a Tool.

MoveIconCommand

Command to move icons in the Design view.

SetProjectDescriptionCommand

Command to set the project description.

AddProjectItemsCommand

Command to add items.

RemoveAllProjectItemsCommand

Command to remove all items from project.

RemoveProjectItemsCommand

Command to remove items.

RenameProjectItemCommand

Command to rename project items.

AddConnectionCommand

Command to add connection between project items.

RemoveConnectionsCommand

Command to remove links.

AddJumpCommand

Command to add a jump between project items.

RemoveJumpsCommand

Command to remove jumps.

SetJumpConditionCommand

Command to set jump condition.

UpdateJumpCmdLineArgsCommand

Command to update Jump command line args.

SetFiltersOnlineCommand

Command to toggle filter value.

SetConnectionDefaultFilterOnlineStatus

Command to set connection's default filter online status.

SetConnectionOptionsCommand

Command to set connection options.

AddSpecificationCommand

Command to add item specification to a project.

ReplaceSpecificationCommand

Command to replace item specification in project.

RemoveSpecificationCommand

Command to remove specs from a project.

SaveSpecificationAsCommand

Command to remove item specs from a project.

class spinetoolbox.project_commands.SpineToolboxCommand[source]

Bases: PySide6.QtGui.QUndoCommand

property is_critical[source]

Returns True if this command needs to be undone before closing the project without saving changes.

successfully_undone = False[source]

Flag to register the outcome of undoing a critical command, so toolbox can react afterwards.

class spinetoolbox.project_commands.SetItemSpecificationCommand(item, spec, old_spec)[source]

Bases: SpineToolboxCommand

Command to set the specification for a Tool.

Parameters
  • item (ProjectItem) – the Item

  • spec (ProjectItemSpecification) – the new spec

  • old_spec (ProjectItemSpecification) – the old spec

redo()[source]
undo()[source]
class spinetoolbox.project_commands.MoveIconCommand(icon, project)[source]

Bases: SpineToolboxCommand

Command to move icons in the Design view.

Parameters
redo()[source]
undo()[source]
_move_to(positions)[source]
class spinetoolbox.project_commands.SetProjectDescriptionCommand(project, description)[source]

Bases: SpineToolboxCommand

Command to set the project description.

Parameters
redo()[source]
undo()[source]
class spinetoolbox.project_commands.AddProjectItemsCommand(project, items_dict, item_factories, silent=True)[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

redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
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

property is_critical[source]

Returns True if this command needs to be undone before closing the project without saving changes.

redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
class spinetoolbox.project_commands.RemoveConnectionsCommand(project, connections)[source]

Bases: SpineToolboxCommand

Command to remove links.

Parameters
  • project (SpineToolboxProject) – project

  • connections (list of LoggingConnection) – the connections

redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
class spinetoolbox.project_commands.RemoveJumpsCommand(project, jumps)[source]

Bases: SpineToolboxCommand

Command to remove jumps.

Parameters
redo()[source]
undo()[source]
class spinetoolbox.project_commands.SetJumpConditionCommand(jump_properties, jump, condition)[source]

Bases: SpineToolboxCommand

Command to set jump condition.

Parameters
  • jump_properties (JumpPropertiesWidget) – jump’s properties tab

  • jump (Jump) – target jump

  • condition (str) – jump condition

redo()[source]
undo()[source]
class spinetoolbox.project_commands.UpdateJumpCmdLineArgsCommand(jump_properties, jump, cmd_line_args)[source]

Bases: SpineToolboxCommand

Command to update Jump command line args.

Parameters
  • jump_properties (JumpPropertiesWidget) – the item

  • cmd_line_args (list) – list of command line args

redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
class spinetoolbox.project_commands.SetConnectionDefaultFilterOnlineStatus(project, connection, default_status)[source]

Bases: SpineToolboxCommand

Command to set connection’s default filter online status.

Parameters
redo()[source]
undo()[source]
class spinetoolbox.project_commands.SetConnectionOptionsCommand(project, connection, options)[source]

Bases: SpineToolboxCommand

Command to set connection options.

Parameters
redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
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

property is_critical[source]

Returns True if this command needs to be undone before closing the project without saving changes.

redo()[source]
undo()[source]
class spinetoolbox.project_commands.RemoveSpecificationCommand(project, name)[source]

Bases: SpineToolboxCommand

Command to remove specs from a project.

Parameters
redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
spinetoolbox.project_item_icon

Classes for drawing graphics items on QGraphicsScene.

Module Contents
Classes

ProjectItemIcon

Base class for project item icons drawn in Design View.

ConnectorButton

Connector button graphics item. Used for Link drawing between project items.

ExecutionIcon

An icon to show information about the item's execution.

ExclamationIcon

An icon to notify that a ProjectItem is missing some configuration.

RankIcon

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

ITEM_EXTENT = 64[source]
FONT_SIZE_PIXELS = 12[source]
rect()[source]
_update_path()[source]
update_path(rounded)[source]
_do_update_path(rounded)[source]
finalize(name, x, y)[source]

Names the icon and moves it by given amount.

Parameters
  • name (str) – icon’s name

  • x (int) – horizontal offset

  • y (int) – vertical offset

_setup()[source]

Setup item’s attributes.

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]

Set a new text to name item.

Parameters

new_name (str) – icon’s name

set_name_attributes()[source]

Set name QGraphicsSimpleTextItem attributes (font, size, position, etc.)

_reposition_name_item()[source]

Set name item position (centered on top of the master icon).

conn_button(position='left')[source]

Returns item’s connector button.

Parameters

position (str) – “left”, “right” or “bottom”

Returns

connector button

Return type

QWidget

Collects outgoing connection links.

Returns

outgoing links

Return type

list of LinkBase

Collects incoming connection links.

Returns

outgoing links

Return type

list of LinkBase

_closest_connector(pos)[source]

Returns the closest connector button to given scene pos.

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

hoverMoveEvent(event)[source]
hoverLeaveEvent(event)[source]

Disables the drop shadow when mouse leaves icon boundaries.

Parameters

event (QGraphicsSceneMouseEvent) – Event

mousePressEvent(event)[source]

Updates scene’s icon group.

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.

notify_item_move()[source]
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 items 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) –

_handle_collisions()[source]

Handles collisions with other items.

make_room_for_item(other)[source]

Makes room for another item.

Parameters

item (ProjectItemIcon) –

_restablish_bumped_items()[source]

Moves bumped items back to their original position if no collision would happen anymore.

select_item()[source]

Update GUI to show the details of the selected item.

paint(painter, option, widget=None)[source]

Sets a dashed pen if selected.

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”

property parent[source]
brush[source]
hover_brush[source]
rect()[source]
update_path(parent_radius)[source]
parent_name()[source]

Returns project item name owning this connector button.

project_item()[source]

Returns the project item this connector button is attached to.

Returns

project item

Return type

ProjectItem

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

set_hover_brush()[source]
set_normal_brush()[source]
hoverEnterEvent(event)[source]

Sets a darker shade to connector button when mouse enters its boundaries.

Parameters

event (QGraphicsSceneMouseEvent) – Event

hoverLeaveEvent(event)[source]

Restore original brush when mouse leaves connector button boundaries.

Parameters

event (QGraphicsSceneMouseEvent) – Event

itemChange(change, value)[source]

If this is being removed from the scene while it’s the origin of the link drawer, put the latter to sleep.

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

_CHECK = '\uf00c'[source]
_CROSS = '\uf00d'[source]
_CLOCK = '\uf017'[source]
_SKIP = '\uf054'[source]
item_name()[source]
_repaint(text, color)[source]
mark_execution_waiting()[source]
mark_execution_ignored()[source]
mark_execution_started()[source]
mark_execution_finished(item_finish_state)[source]
hoverEnterEvent(event)[source]
hoverLeaveEvent(event)[source]
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

FONT_SIZE_PIXELS = 14[source]
clear_notifications()[source]

Clear all notifications.

add_notification(text)[source]

Add a notification.

remove_notification(subtext)[source]

Remove the first notification that includes given subtext.

hoverEnterEvent(event)[source]

Shows notifications as tool tip.

Parameters

event (QGraphicsSceneMouseEvent) – Event

hoverLeaveEvent(event)[source]

Hides tool tip.

Parameters

event (QGraphicsSceneMouseEvent) – Event

class spinetoolbox.project_item_icon.RankIcon(parent)[source]

Bases: PySide6.QtWidgets.QGraphicsTextItem

An icon to show the rank of a ProjectItem within its DAG.

Parameters

parent (ProjectItemIcon) – the parent item

_make_path(radius)[source]
update_path(radius)[source]
set_rank(rank)[source]
spinetoolbox.project_settings

Contains project-specific settings.

Module Contents
Classes

ProjectSettings

Spine Toolbox project settings.

class spinetoolbox.project_settings.ProjectSettings[source]

Spine Toolbox project settings.

enable_execute_all: bool = True[source]
to_dict()[source]

Serializes the settings into a dictionary.

Returns

serialized settings

Return type

dict

static from_dict(settings_dict)[source]

Deserializes settings from dictionary.

Parameters

settings_dict (dict) – serialized settings

Returns

deserialized settings

Return type

ProjectSettings

spinetoolbox.project_upgrader

Contains ProjectUpgrader class used in upgrading and converting projects and project dicts from earlier versions to the latest version.

Module Contents
Classes

ProjectUpgrader

Class to upgrade/convert projects from earlier versions to the current version.

Functions

_fix_1d_array_to_array(mappings)

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:
  1. Move “specifications” from “project” -> “Tool” to just “project”

  2. 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:
  1. 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:
  1. 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:
  1. Data store URL labels do not have ‘{‘ and ‘}’ anymore

  2. Importer stores resource labels instead of serialized paths in “file_selection”.

  3. Gimlet’s “selections” is now called “file_selection”

  4. Gimlet stores resource labels instead of serialized paths in “file_selection”.

  5. 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:
  1. 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:
  1. 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:
  1. 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:
  1. Remove connections from Gimlets and GDXExporters

  2. 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:
  1. Add [“project”][“settings”] key

Parameters

old (dict) – Version 10 project dictionary

Returns

Version 11 project dictionary

Return type

dict

static make_unique_importer_specification_name(importer_name, label, k)[source]
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(p)[source]

Checks that the given project JSON dictionary contains a valid version 11 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 project, False otherwise

Return type

bool

backup_project_file(project_dir, v)[source]

Makes a backup copy of project.json file.

force_save(p, project_dir)[source]

Saves given project dictionary to project.json file. Used to force save project.json file when the project dictionary has been upgraded.

spinetoolbox.project_upgrader._fix_1d_array_to_array(mappings)[source]

Replaces ‘1d array’ with ‘array’ for parameter type in Importer mappings.

With spinedb_api >= 0.3, ‘1d array’ parameter type was replaced by ‘array’. Other settings in a mapping are backwards compatible except the name.

spinetoolbox.qthread_pool_executor

Qt-based thread pool executor.

Module Contents
Classes

_CustomQSemaphore

QtBasedQueue

A Qt-based clone of queue.Queue.

QtBasedFuture

A Qt-based clone of concurrent.futures.Future.

QtBasedThread

A Qt-based clone of threading.Thread.

QtBasedThreadPoolExecutor

A Qt-based clone of concurrent.futures.ThreadPoolExecutor

SynchronousExecutor

Functions

_set_future_result_and_exc(future, fn, *args, **kwargs)

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

tryAcquire(n, timeout=None)[source]
class spinetoolbox.qthread_pool_executor.QtBasedQueue[source]

A Qt-based clone of queue.Queue.

put(item)[source]
get(timeout=None)[source]
class spinetoolbox.qthread_pool_executor.QtBasedFuture[source]

A Qt-based clone of concurrent.futures.Future.

set_result(result)[source]
set_exception(exc)[source]
result(timeout=None)[source]
exception(timeout=None)[source]
add_done_callback(callback)[source]
class spinetoolbox.qthread_pool_executor.QtBasedThread(target=None, args=())[source]

Bases: PySide6.QtCore.QThread

A Qt-based clone of threading.Thread.

run()[source]
class spinetoolbox.qthread_pool_executor.QtBasedThreadPoolExecutor(max_workers=None)[source]

A Qt-based clone of concurrent.futures.ThreadPoolExecutor

submit(fn, *args, **kwargs)[source]
_spawn_thread()[source]
_do_work()[source]
shutdown()[source]
class spinetoolbox.qthread_pool_executor.SynchronousExecutor[source]
submit(fn, *args, **kwargs)[source]
shutdown()[source]
spinetoolbox.qthread_pool_executor._set_future_result_and_exc(future, fn, *args, **kwargs)[source]
spinetoolbox.spine_db_commands

QUndoCommand subclasses for modifying the db.

Module Contents
Classes

AgedUndoStack

AgedUndoCommand

param parent

The parent command, used for defining macros.

SpineDBCommand

Base class for all commands that modify a Spine DB.

AddItemsCommand

Base class for all commands that modify a Spine DB.

UpdateItemsCommand

Base class for all commands that modify a Spine DB.

RemoveItemsCommand

Base class for all commands that modify a Spine DB.

class spinetoolbox.spine_db_commands.AgedUndoStack[source]

Bases: PySide6.QtGui.QUndoStack

property redo_age[source]
property undo_age[source]
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.

property age[source]
id()[source]

override

ours()[source]
mergeWith(command)[source]
redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
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

redo()[source]
undo()[source]
class spinetoolbox.spine_db_commands.RemoveItemsCommand(db_mngr, db_map, item_type, ids, **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

redo()[source]
undo()[source]
spinetoolbox.spine_db_icon_manager

Provides SpineDBIconManager.

Module Contents
Classes

_SceneSvgRenderer

SpineDBIconManager

A class to manage object_class icons for spine db editors.

SceneIconEngine

Specialization of QIconEngine used to draw scene-based icons.

Functions

_align_text_in_item(item)

_center_scene(scene)

spinetoolbox.spine_db_icon_manager._align_text_in_item(item)[source]
spinetoolbox.spine_db_icon_manager._center_scene(scene)[source]
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.

_create_icon_renderer(icon_code, color_code)[source]
icon_renderer(icon_code, color_code)[source]
color_class_renderer(entity_class, color_code)[source]
_create_class_renderer(class_name)[source]
_create_multi_class_renderer(dimension_name_list)[source]
class_renderer(entity_class)[source]
multi_class_renderer(dimension_name_list)[source]
_create_group_renderer(class_name)[source]
group_renderer(entity_class)[source]
static icon_from_renderer(renderer)[source]
class spinetoolbox.spine_db_icon_manager.SceneIconEngine(scene)[source]

Bases: spinetoolbox.helpers.TransparentIconEngine

Specialization of QIconEngine used to draw scene-based icons.

paint(painter, rect, mode=None, state=None)[source]
spinetoolbox.spine_db_manager

The SpineDBManager class

Module Contents
Classes

SpineDBManager

Class to manage DBs within a project.

Functions

do_create_new_spine_database(url)

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.

Initializes the instance.

Parameters
  • settings (QSettings) – Toolbox settings

  • parent (QObject, optional) – parent object

property db_maps[source]
property db_urls[source]
error_msg[source]
items_added[source]

Emitted whenever items are added to a DB.

Parameters
  • str – item type, such as “object_class”

  • dict – mapping DiffDatabaseMapping 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 DiffDatabaseMapping 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 DiffDatabaseMapping to list of updated dict-items.

_connect_signals()[source]
receive_error_msg(db_map_error_log)[source]
receive_session_refreshed(db_maps)[source]
receive_session_committed(db_maps, cookie)[source]
receive_session_rolled_back(db_maps)[source]
_get_worker(db_map)[source]

Returns a worker.

Parameters

db_map (DiffDatabaseMapping) –

Returns

SpineDBWorker

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 (DiffDatabaseMapping) –

  • 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 (DiffDatabaseMapping) –

Returns

SpineDBIconManager

update_icons(db_map, item_type, items)[source]

Runs when items are added or updated. Setups icons.

static db_map_key(db_map)[source]

Creates an identifier for given db_map.

Parameters

db_map (DiffDatabaseMapping) – 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

DiffDatabaseMapping

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

DiffDatabaseMapping

create_new_spine_database(url, logger)[source]
close_session(url)[source]

Pops any db map on the given url and closes its connection.

Parameters

url (str) –

close_all_sessions()[source]

Closes connections to all database mappings.

get_db_map(url, logger, ignore_version_error=False, codename=None, create=False, upgrade=False)[source]

Returns a DiffDatabaseMapping 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) –

  • codename (str, NoneType, optional) –

  • upgrade (bool, optional) –

  • create (bool, optional) –

Returns

DiffDatabaseMapping, NoneType

_do_get_db_map(url, codename, create, upgrade)[source]

Returns a memorized DiffDatabaseMapping instance from url. Called by get_db_map.

Parameters
  • url (str, URL) –

  • codename (str, NoneType) –

  • upgrade (bool) –

  • create (bool) –

Returns

DiffDatabaseMapping

query(db_map, sq_name)[source]

For tests.

add_db_map_listener(db_map, listener)[source]

Adds listener for given db_map.

remove_db_map_listener(db_map, listener)[source]

Removes db_map from the maps listener listens to.

db_map_listeners(db_map)[source]
register_listener(listener, *db_maps)[source]

Register given listener for all given db_map’s signals.

Parameters
  • listener (object) –

  • db_maps (DiffDatabaseMapping) –

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 (DiffDatabaseMapping) –

  • 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)

is_dirty(db_map)[source]

Returns True if mapping has pending changes.

Parameters

db_map (DiffDatabaseMapping) – 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 DiffDatabaseMapping

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 DiffDatabaseMapping

clean_up()[source]
refresh_session(*db_maps)[source]
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 (DiffDatabaseMapping) – database map

  • entity_class_id (int) – entity class id

  • for_group (bool) – if True, return the group object icon instead

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 (DiffDatabaseMapping) – 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 (DiffDatabaseMapping) –

  • item_type (str) –

  • id (int) –

Returns

cached item

Return type

CacheItem

get_field(db_map, item_type, id_, field)[source]
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 (DiffDatabaseMapping) –

  • 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 (DiffDatabaseMapping) –

  • 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 (DiffDatabaseMapping) –

  • 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.

_format_list_value(db_map, item_type, value, list_value_id)[source]
get_value(db_map, item_type, id_, role=Qt.ItemDataRole.DisplayRole)[source]

Returns the value or default value of a parameter.

Parameters
  • db_map (DiffDatabaseMapping) –

  • item_type (str) – either “parameter_definition”, “parameter_value”, or “list_value”

  • id (int) – The parameter_value or definition id

  • role (int, optional) –

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

static _parse_value(db_value, value_type=None)[source]
_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 (DiffDatabaseMapping) –

  • 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 (DiffDatabaseMapping) –

  • 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 (DiffDatabaseMapping) –

  • 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 (DiffDatabaseMapping) –

  • id (int) – The parameter_value_list id

  • role (int, optional) –

get_scenario_alternative_id_list(db_map, scen_id)[source]
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(DiffDatabaseMapping, 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 DiffDatabaseMapping

add_scenarios(db_map_data)[source]

Adds scenarios to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_entity_classes(db_map_data)[source]

Adds entity classes to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_entities(db_map_data)[source]

Adds entities to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_entity_groups(db_map_data)[source]

Adds entity groups to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_entity_alternatives(db_map_data)[source]

Adds entity alternatives to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_parameter_definitions(db_map_data)[source]

Adds parameter definitions to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

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 DiffDatabaseMapping

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 DiffDatabaseMapping

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 DiffDatabaseMapping

add_metadata(db_map_data)[source]

Adds metadata to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_entity_metadata(db_map_data)[source]

Adds entity metadata to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

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 DiffDatabaseMapping

_add_ext_item_metadata(db_map_data, item_type)[source]
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 DiffDatabaseMapping

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 DiffDatabaseMapping

update_alternatives(db_map_data)[source]

Updates alternatives in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_scenarios(db_map_data)[source]

Updates scenarios in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_entity_classes(db_map_data)[source]

Updates entity classes in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_entities(db_map_data)[source]

Updates entities in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_entity_alternatives(db_map_data)[source]

Updates entity alternatives in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_parameter_definitions(db_map_data)[source]

Updates parameter definitions in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_parameter_values(db_map_data)[source]

Updates parameter values in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

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 DiffDatabaseMapping

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 DiffDatabaseMapping

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 DiffDatabaseMapping

update_metadata(db_map_data)[source]

Updates metadata in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_entity_metadata(db_map_data)[source]

Updates entity metadata in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

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 DiffDatabaseMapping

_update_ext_item_metadata(db_map_data, item_type)[source]
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 DiffDatabaseMapping

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 DiffDatabaseMapping

set_scenario_alternatives(db_map_data)[source]

Sets scenario alternatives in db.

Parameters

db_map_data (dict) – lists of items to set keyed by DiffDatabaseMapping

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

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.

remove_items(db_map_typed_ids, identifier=None, **kwargs)[source]

Pushes commands to remove items to undo stack.

get_command_identifier()[source]
do_add_items(db_map, item_type, data, check=True)[source]
do_update_items(db_map, item_type, data, check=True)[source]
do_remove_items(db_map, item_type, ids)[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

static db_map_ids(db_map_data)[source]
static db_map_class_ids(db_map_data)[source]
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.

find_groups_by_entity(db_map_ids)[source]

Finds and returns groups for the given entity ids.

duplicate_scenario(scen_data, dup_name, db_map)[source]
duplicate_entity(entity_data, orig_name, dup_name, db_maps)[source]
_get_data_for_export(db_map_item_ids)[source]
export_data(caller, db_map_item_ids, file_path, file_filter)[source]
_is_url_available(url, logger)[source]
export_to_sqlite(file_path, data_for_export, caller)[source]

Exports given data into SQLite file.

export_to_json(file_path, data_for_export, caller)[source]

Exports given data into JSON file.

export_to_excel(file_path, data_for_export, caller)[source]

Exports given data into Excel file.

get_items_for_commit(db_map, commit_id)[source]
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

_get_existing_spine_db_editor(db_url_codenames)[source]
open_db_editor(db_url_codenames)[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

spinetoolbox.spine_db_parcel

SpineDBParcel class.

Module Contents
Classes

SpineDBParcel

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 and inner_push methods do something more specific

Initializes the parcel object.

Parameters

db_mngr (SpineDBManager) –

property data[source]
_get_field_values(db_map, item_type, field, ids)[source]

Returns a list of field values for items of given type, having given ids.

push_entity_class_ids(db_map_ids)[source]

Pushes entity_class ids.

push_entity_ids(db_map_ids)[source]

Pushes entity ids.

push_parameter_value_list_ids(db_map_ids)[source]

Pushes parameter_value_list ids.

push_parameter_definition_ids(db_map_ids)[source]

Pushes parameter_definition ids.

push_parameter_value_ids(db_map_ids)[source]

Pushes parameter_value ids.

push_entity_group_ids(db_map_ids)[source]

Pushes entity group ids.

push_alternative_ids(db_map_ids)[source]

Pushes alternative ids.

push_scenario_ids(db_map_ids)[source]

Pushes scenario ids.

push_scenario_alternative_ids(db_map_ids)[source]

Pushes scenario_alternative 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.

full_push_scenario_ids(db_map_ids)[source]
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.

inner_push_parameter_value_ids(db_map_ids)[source]

Pushes parameter_value ids.

_update_ids(db_map_ids, key)[source]

Updates ids for given database item.

Parameters
  • db_map_ids (dict) – mapping from DatabaseMapping to ids or Asterisk

  • key (str) – the key

_setdefault(db_map)[source]

Adds new id sets for given db_map or returns existing ones.

Parameters

db_map (DatabaseMapping) – a database map

Returns

mapping from item name to set of ids

Return type

dict

spinetoolbox.spine_db_worker

The SpineDBWorker class

Module Contents
Classes

SpineDBWorker

Does all the communication with a certain DB for SpineDBManager, in a non-GUI thread.

Attributes

_CHUNK_SIZE

spinetoolbox.spine_db_worker._CHUNK_SIZE = 10000[source]
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.

_query_advanced[source]
_get_parents(item_type)[source]
clean_up()[source]
get_db_map(*args, **kwargs)[source]
register_fetch_parent(parent)[source]

Registers the given parent.

Parameters

parent (FetchParent) – parent to add

_iterate_cache(parent)[source]

Iterates the cache 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

_do_fetch_more(parent)[source]
_fetch_more_later(parents)[source]
_busy_db_map_fetch_more(item_type)[source]
_handle_query_advanced(item_type, chunk)[source]
_populate_commit_cache(item_type, items)[source]
fetch_all()[source]
close_db_map()[source]
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

_wake_up_parents(item_type, items)[source]
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

remove_items(item_type, ids)[source]

Removes items from database.

Parameters
  • item_type (str) – item type

  • ids (set) – ids of items to remove

restore_items(item_type, ids)[source]

Readds items to database.

Parameters
  • item_type (str) – item type

  • ids (set) – ids of items to restore

refresh_session()[source]

Refreshes session.

spinetoolbox.spine_engine_manager

Contains SpineEngineManagerBase.

Module Contents
Classes

SpineEngineManagerBase

LocalSpineEngineManager

RemoteSpineEngineManager

Responsible for remote project execution.

Functions

make_engine_manager([remote_execution_enabled, job_id])

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 stop_engine()[source]

Stops a running engine.

abstract answer_prompt(item_name, accepted)[source]

Answers prompt.

Parameters
  • item_name (str) – The item that emitted the prompt

  • accepted (bool) – 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

abstract get_persistent_completions(persistent_key, text)[source]

Returns a list of auto-completion options from given text.

Parameters
  • persistent_key (tuple) – persistent identifier

  • text (str) – text to complete

Returns

list of str

abstract get_persistent_history_item(persistent_key, text, prefix, backwards)[source]

Returns an item from persistent history.

Parameters

persistent_key (tuple) – persistent identifier

Returns

history item or empty string if none

Return type

str

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)

stop_engine()[source]

Stops a running engine.

answer_prompt(item_name, accepted)[source]

Answers prompt.

Parameters
  • item_name (str) – The item that emitted the prompt

  • accepted (bool) – 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

kernel_managers()[source]
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

get_persistent_completions(persistent_key, text)[source]

Returns a list of auto-completion options from given text.

Parameters
  • persistent_key (tuple) – persistent identifier

  • text (str) – text to complete

Returns

list of str

get_persistent_history_item(persistent_key, text, prefix, backwards)[source]

Returns an item from persistent history.

Parameters

persistent_key (tuple) – persistent identifier

Returns

history item or empty string if none

Return type

str

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.

get_engine_event()[source]

Returns the next engine execution event.

clean_up()[source]

Closes EngineClient and joins _runner thread if still active.

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.

answer_prompt(item_name, accepted)[source]

See base class.

restart_kernel(connection_file)[source]

See base class.

shutdown_kernel(connection_file)[source]

See base class.

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

restart_persistent(persistent_key)[source]

See base class.

interrupt_persistent(persistent_key)[source]

See base class.

kill_persistent(persistent_key)[source]

See base class.

get_persistent_completions(persistent_key, text)[source]

See base class.

get_persistent_history_item(persistent_key, text, prefix, backwards)[source]

Returns an item from persistent history.

Parameters

persistent_key (tuple) – persistent identifier

Returns

history item or empty string if none

Return type

str

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
Classes

SpineEngineWorker

param engine_data

engine data

Functions

_handle_dag_execution_started(project_items)

_handle_node_execution_ignored(project_items)

_handle_node_execution_started(item, direction)

_handle_node_execution_finished(item, direction, ...)

_handle_event_message_arrived(item, filter_id, ...)

_handle_process_message_arrived(item, filter_id, ...)

_handle_prompt_arrived(prompt, engine_mngr[, logger])

_handle_flash_arrived(connection)

_mark_all_items_failed(items)

Fails all project items.

spinetoolbox.spine_engine_worker._handle_dag_execution_started(project_items)[source]
spinetoolbox.spine_engine_worker._handle_node_execution_ignored(project_items)[source]
spinetoolbox.spine_engine_worker._handle_node_execution_started(item, direction)[source]
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._handle_prompt_arrived(prompt, engine_mngr, logger=None)[source]
spinetoolbox.spine_engine_worker._handle_flash_arrived(connection)[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 or LoggingJump

  • logger (LoggerInterface) – a logger

  • job_id (str) – Job id for remote execution

property job_id[source]
property engine_data[source]

Engine data dictionary.

finished[source]
_mark_items_ignored[source]
_dag_execution_started[source]
_node_execution_started[source]
_node_execution_finished[source]
_event_message_arrived[source]
_process_message_arrived[source]
_prompt_arrived[source]
_flash_arrived[source]
_all_items_failed[source]
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

_handle_event_message_arrived_silent(item, filter_id, msg_type, msg_text)[source]
_handle_process_message_arrived_silent(item, filter_id, msg_type, msg_text)[source]
stop_engine()[source]
engine_final_state()[source]
thread()[source]
_connect_log_signals(silent)[source]
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

do_work()[source]

Does the work and emits finished when done.

_process_event(event_type, data)[source]
_handle_prompt(prompt)[source]
_handle_flash(flash)[source]
_handle_standard_execution_msg(msg)[source]
_handle_persistent_execution_msg(msg)[source]
_handle_kernel_execution_msg(msg)[source]
_handle_process_msg(data)[source]
_do_handle_process_msg(item_name, filter_id, msg_type, msg_text)[source]
_handle_event_msg(data)[source]
_do_handle_event_msg(item_name, filter_id, msg_type, msg_text)[source]
_handle_node_execution_started(data)[source]
_do_handle_node_execution_started(item_name, direction)[source]

Starts item icon animation when executing forward.

_handle_node_execution_finished(data)[source]
_do_handle_node_execution_finished(item_name, direction, state, item_state)[source]
_handle_server_status_msg(data)[source]
clean_up()[source]
spinetoolbox.ui_main

Contains ToolboxUI class.

Module Contents
Classes

ToolboxUI

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.

msg[source]
msg_success[source]
msg_error[source]
msg_warning[source]
msg_proc[source]
msg_proc_error[source]
information_box[source]
error_box[source]
jupyter_console_requested[source]
kernel_shutdown[source]
persistent_console_requested[source]
eventFilter(obj, ev)[source]
_setup_properties_title()[source]
connect_signals()[source]

Connect signals.

_open_active_item_dir(_checked=False)[source]
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_qsettings()[source]

Updates obsolete settings.

_update_execute_enabled()[source]
_update_execute_selected_enabled()[source]
update_window_modified(clean)[source]

Updates window modified status and save actions depending on the state of the undo stack.

parse_project_item_modules()[source]

Collects data from project item factories.

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

SpineToolboxProject

qsettings()[source]

Returns application preferences object.

item_specification_factories()[source]

Returns project item specification factories.

Returns

specification factories

Return type

list of ProjectItemSpecificationFactory

update_window_title()[source]

Updates main window title.

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

_toolbars()[source]

Yields all toolbars in the window.

_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.

refresh_toolbars()[source]

Set toolbars’ color using highest possible contrast.

show_recent_projects_menu()[source]

Updates and sets up the recent projects menu to File-Open recent menu item.

fetch_kernels()[source]

Starts a thread for fetching local kernels.

stop_fetching_kernels()[source]

Terminates kernel fetcher thread.

restore_override_cursor()[source]

Restores default mouse cursor.

save_project()[source]

Saves project.

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)[source]

Closes the current project.

Parameters

ask_confirmation (bool) – if False, no confirmation whatsoever is asked from user

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.

init_project_item_model()[source]

Initializes project item model. Create root and category items and add them to the model.

init_specification_model()[source]

Initializes specification model.

make_item_properties_uis()[source]
_make_properties_tab(properties_ui)[source]
add_project_items(items_dict, silent=False)[source]

Pushes an AddProjectItemsCommand to the undo stack.

Parameters
  • items_dict (dict) – mapping from item name to item dictionary

  • silent (bool) – if True, suppress log messages

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

restore_ui()[source]

Restore UI state from previous session.

clear_ui()[source]

Clean UI to make room for a new or opened project.

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

item_selection_changed(selected, deselected)[source]

Synchronizes selection with scene. The scene handles item/link de/activation.

refresh_active_elements(active_project_item, active_link_item, selected_item_names)[source]
_activate_properties_tab()[source]
_set_active_project_item(active_project_item)[source]
Parameters

active_project_item (ProjectItemBase or NoneType) –

Sets active link and connects to corresponding properties widget.

Parameters

active_link_item (LoggingConnection or LoggingJump, optional) –

activate_no_selection_tab()[source]

Shows ‘No Selection’ tab.

activate_item_tab()[source]

Shows active project item properties tab according to item type.

Shows link properties tab.

update_properties_ui()[source]
_get_active_properties_widget()[source]
add_specification(specification)[source]

Pushes an AddSpecificationCommand to undo stack.

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) – A 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

remove_all_items()[source]

Pushes a RemoveAllProjectItemsCommand to the undo stack.

register_anchor_callback(url, callback)[source]

Registers a callback for a given anchor in event log, see open_anchor(). Used by ToolFactory.repair_specification().

Parameters
  • url (str) – The anchor url

  • callback (function) – A function to call when the anchor is clicked on event log.

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

show_specification_context_menu(ind, global_pos)[source]

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

new_db_editor()[source]
_handle_zoom_minus_pressed()[source]

Slot for handling case when ‘-‘ button in menu is pressed.

_handle_zoom_plus_pressed()[source]

Slot for handling case when ‘+’ button in menu is pressed.

_handle_zoom_reset_pressed()[source]

Slot for handling case when ‘reset zoom’ button in menu is pressed.

add_zoom_action()[source]

Setups zoom widget action in view menu.

restore_dock_widgets()[source]

Dock all floating and or hidden QDockWidgets back to the main window.

_add_execute_actions()[source]

Adds execution handler actions to the main window.

set_debug_qactions()[source]

Sets shortcuts for QActions that may be needed in debugging.

add_menu_actions()[source]

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]

Append regular message to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_success_message(msg)[source]

Append message with green text color to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_error_message(msg)[source]

Append message with red color to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_warning_message(msg)[source]

Append message with yellow (golden) color to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_process_message(msg)[source]

Writes message from stdout to process output QTextBrowser.

Parameters

msg (str) – String written to QTextBrowser

add_process_error_message(msg)[source]

Writes message from stderr to process output QTextBrowser.

Parameters

msg (str) – String written to QTextBrowser

override_console_and_execution_list()[source]
_override_console()[source]

Sets the jupyter console of the active project item in Jupyter Console and updates title.

_do_override_console(console)[source]
_override_execution_list()[source]

Displays executions of the active project item in Executions and updates title.

_restore_original_console()[source]

Sets the Console back to the original.

_set_override_console(console)[source]
_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.

show_add_project_item_form(item_type, x=0, y=0, spec='')[source]

Show add project item widget.

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

static get_all_multi_tab_spec_editors(item_type)[source]
_get_existing_spec_editor(item_type, specification, item)[source]
show_settings()[source]

Show Settings widget.

show_about()[source]

Show About Spine Toolbox form.

show_user_guide()[source]

Open Spine Toolbox documentation index page in browser.

show_getting_started_guide()[source]

Open Spine Toolbox Getting Started HTML page in browser.

retrieve_project()[source]

Retrieves project from server.

engine_server_settings()[source]

Returns the user given Spine Engine Server settings in a tuple.

show_item_context_menu(pos)[source]

Context menu for project items listed in the project QTreeView.

Parameters

pos (QPoint) – Mouse position

show_project_or_item_context_menu(pos, index)[source]

Creates and shows the project item context menu.

Parameters
  • pos (QPoint) – Mouse position

  • index (QModelIndex, optional) – Index of concerned item or None

Context menu for connection links.

Parameters
  • pos (QPoint) – Mouse position

  • link (Link(QGraphicsPathItem)) – The concerned link

refresh_edit_action_states()[source]

Sets the enabled/disabled state for copy, paste, duplicate, and remove 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

a list containing zero or more tasks

_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

_confirm_exit()[source]

Confirms exiting from user.

Returns

True if exit should proceed, False if user cancelled

_confirm_project_close()[source]

Confirms exit from user and saves the project if requested.

Returns

True if exiting should proceed, False if user cancelled

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

clear_recent_projects()[source]

Clears recent projects list in File->Open recent menu.

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) – a 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_to_clipboard()[source]

Copies the selected project items to system’s clipboard.

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

duplicate_project_item(duplicate_files=False)[source]

Duplicates the selected project items.

_share_item_edit_actions()[source]

Adds generic actions to project tree view and Design View.

_show_message_box(title, message)[source]

Shows an information message box.

_show_error_box(title, message)[source]
_connect_project_signals()[source]

Connects signals emitted by project.

_execute_project(_=False)[source]

Executes all DAGs in project.

_execute_selection(_=False)[source]

Executes selected items.

_stop_execution(_=False)[source]

Stops execution in progress.

_set_execution_in_progress()[source]
_unset_execution_in_progress()[source]
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

project_item_icon(item_type)[source]
_open_project_directory(_)[source]

Opens project’s root directory in system’s file browser.

_open_project_item_directory(_)[source]

Opens project item’s directory in system’s file browser.

_remove_selected_items(_)[source]

Pushes commands to remove selected project items and links from project.

_rename_project_item(_)[source]

Renames current project item.

item_category_context_menu()[source]

Creates a context menu for category items.

Returns

category context menu

Return type

QMenu

project_item_context_menu(additional_actions)[source]

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’)

persistent_killed(item, filter_id)[source]
add_persistent_stdin(item, filter_id, data)[source]
add_persistent_stdout(item, filter_id, data)[source]
add_persistent_stderr(item, filter_id, data)[source]
_get_console(item, filter_id)[source]
_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.

_close_consoles()[source]

Closes all Persistent and Jupyter Console widgets.

restore_and_activate()[source]

Brings the app main window into focus.

static _make_log_entry_title(title)[source]
start_execution(timestamp)[source]

Starts execution.

Parameters

timestamp (str) – time stamp

add_log_message(item_name, filter_id, message)[source]

Adds a message to an item’s execution log.

Parameters
  • item_name (str) – item name

  • filter_id (str) – filter identifier

  • message (str) – formatted message

spinetoolbox.version

Version info for Spine Toolbox package. Inspired by python sys.version and sys.version_info.

Module Contents
Classes

VersionInfo

A class for a named tuple containing the five components of the version number: major, minor,

Attributes

split

__version_info__

__version__

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’.

major: int[source]
minor: int[source]
micro: int[source]
releaselevel: str[source]
serial: int[source]
__str__() str[source]

Create a version string following PEP 440

spinetoolbox.version.split[source]
spinetoolbox.version.__version_info__[source]
spinetoolbox.version.__version__[source]

Package Contents

spinetoolbox.__version__[source]
spinetoolbox.__version_info__[source]
1

Created with sphinx-autoapi

Indices and tables