Welcome to Spine Toolbox’s User Guide!

Spine Toolbox is an application, which provides means to define, manage, and execute complex data processing and computation tasks, such as energy system models.

If you are new to Spine Toolbox, Getting Started section is a good place to start. If you want to run SpineOpt.jl using Spine Toolbox, How to set up SpineOpt.jl provides the step-by-step instructions on how to get started. For information on how to set up Python, Julia, and Gams for Spine Toolbox, see Setting up 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 for Spine Toolbox. The last section contains the complete code reference of Spine Toolbox.

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.

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.

  • Item Execution Log shows the output of executed project items.

  • Python console provides an interface to interact with the Python programming language, and also allows Spine Toolbox to execute Python Tools.

  • Julia console provides an interface to interact with the Julia programming language, and also allows Spine Toolbox to execute Julia Tools.

  • Executions 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 Main section contains the project items that you can drag-and-drop onto the Design View and 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 press Enter. 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 angle_double_right 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 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/release06_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 tabbar (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/release06_getting_started_first_tool_spec_created.png

Tool specifications are saved in JSON format by default 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 the ‘hello_world.json’ file 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 add tool specification from file… button (add_tool_specification) 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, Items list, under the ‘Tools’ category. It should look similar to this:

_images/release06_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 from the main window File->Save project button 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/release06_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 item execution details in the Item Execution Log and the details about the whole execution in Event Log.

_images/release06_getting_started_after_first_execution.png

Note

For more information about execution modes in Spine Toolbox, please see Setting up 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, Gdx Exporter, 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, or by selecting Edit specification from the ‘hello world’ Tool specification context menu in the toolbar, or from the ‘say hello world’ Tool context-menu (Specification…->Edit specification).

In Input & Output files dock widget, click the file_link 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/release06_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/release06_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 items, 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. It should look similar to this:

Adding data files to a Data Connection

Select the ‘pass input txt’ Data Connection item to view its properties in the Properties dock widget.

_images/release06_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/release06_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 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/release06_getting_started_dc_to_tool_connected.png

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

_images/release06_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.

How to set up SpineOpt.jl

  1. Install Julia (v1.2 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.5.4\bin\julia.exe). Your selections should look similar to this now.

    _images/settings_tools_filled_for_spineopt_github.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 appears on 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 for more advanced use cases. For more information on how to select a specific Python or Julia version, see Setting up External Tools).

Note

The SpineOpt Plugin Toolbar contains two 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.

Tutorials

Welcome to the Spine Toolbox’s tutorials page. The following tutorials are available:

Simple System tutorial

Welcome to Spine Toolbox’s Symple System tutorial.

This tutorial provides a step-by-step guide to setup a simple energy system on Spine Toolbox and is organized as follows:

Introduction

Model assumptions
  • Two power plants take fuel from a source node and release electricity to another node in order to supply a demand.

  • Power plant ‘a’ has a capacity of 100 MWh, a variable operating cost of 25 euro/fuel unit, and generates 0.7 MWh of electricity per unit of fuel.

  • Power plant ‘b’ has a capacity of 200 MWh, a variable operating cost of 50 euro/fuel unit, and generates 0.8 MWh of electricity per unit of fuel.

  • The demand at the electricity node is 150 MWh.

  • The fuel node is able to provide infinite energy.

_images/simple_system_schematic.png

Guide

Installing requirements

Note

This tutorial is written for latest Spine Toolbox and SpineOpt development versions.

  • If you haven’t, follow the instructions here to install Spine Toolbox and SpineOpt in your system.

  • If you already have Spine Toolbox and SpineOpt installed, please follow the instructions here and here to upgrade to the latest versions.

Installing the SpineOpt plugin
  1. Launch Spine Toolbox and select Plugins -> Install plugin… from the main menu. The Install plugin dialog will pop up. Select SpineOpt from the list and press Ok.

    _images/install_spine_opt_plugin.png

    A new toolbar will appear, looking similar to this:

    _images/spine_opt_plugin_tool_bar.png
Setting up project
  1. Select File -> New project… from Spine Toolbox main menu. Browse to a location where you want to create the project and create a new folder for it, called e.g. ’SimpleSystem’, and then click Open.

  2. Drag the Data Store icon ds_icon from the tool bar and drop it into the Design View. This will open the Add Data Store dialog. Type ‘input’ as the Data Store name and click Ok.

  3. Repeat the above procedure to create a Data Store called ‘output’.

  4. Create a database for the ‘input‘ Data Store:

    1. Select the input Data Store item in the Design View to show the Data Store Properties (on the right side of the window, usually).

    2. In Data Store Properties, select the sqlite dialect at the top, and hit New Spine db. A dialog will pop up to let you select a name for the database file; just accept the default name.

  5. Repeat the above procedure to create a database for the ‘output’ Data Store.

  6. Drag the Run SpineOpt icon tool_icon from the SpineOpt tool bar into the Design View. This will open the Add Tool dialog. Accept the default name (‘Run SpineOpt 1’) and click Ok.

    Note

    Each item in the Design view is equipped with three connectors (the small squares at the item boundaries).

  7. Click on one of ‘input’ connectors to start a connection, and then on one of ‘Run SpineOpt 1’ connectors to close it.

  8. Repeat the procedure to create a connection from ‘Run SpineOpt 1’ to ‘output’. It should look something like this:

    _images/simple_system_item_connections.png
  9. Setup the arguments for the Run SpineOpt Tool:

    1. Select the Run SpineOpt Tool to show the Tool Properties (on the right side of the window, usually). You should see two elements listed under Available resources, {db_url@input} and {db_url@output}.

    2. Drag the first resource, {db_url@input}, and drop it in Command line arguments; then drag the second resource, {db_url@output}, and drop it right below the previous one. The panel should be now looking like this:

      _images/simple_system_cmdline_args.png
    3. Double-check that the order of the arguments is correct: first, {db_url@input}, and second, {db_url@output}. (You can drag and drop to reorganize them if needed.)

  10. From the main menu, select File -> Save project.

Entering input data
Importing the SpineOpt database template
  1. Download the basic SpineOpt database template (right click on the link, then select Save link as…)

  2. Select the ‘input’ Data Store item in the Design View.

  3. Go to Data Store Properties and hit Open editor. This will open the newly created database in the Spine DB editor, looking similar to this:

    _images/case_study_a5_spine_db_editor_empty.png

    Note

    The Spine DB editor is a dedicated interface within Spine Toolbox for visualizing and managing Spine databases.

  4. Press Alt + F to display the main menu, select File -> Import…, and then select the template file you previously downloaded. The contents of that file will be imported into the current database, and you should then see classes like ‘commodity’, ‘connection’ and ‘model’ under the root node in the Object tree (on the left).

  5. From the main menu, select Session -> Commit. Enter ‘Import SpineOpt template’ as message in the popup dialog, and click Commit.

Note

The SpineOpt basic template contains (i) the fundamental entity classes and parameter definitions that SpineOpt recognizes and expects; and (ii) some predefined entities for a common deterministic model with a ‘flat’ temporal structure.

Creating objects
  1. Always in the Spine DB editor, locate the Object tree (typically at the top-left). Expand the root element if not expanded.

  2. Right click on the node class, and select Add objects from the context menu. The Add objects dialog will pop up.

  3. Enter the names for the system nodes as seen in the image below, then press Ok. This will create two objects of class node, called fuel_node and electricity_node.

    _images/simple_system_add_nodes.png
  4. Right click on the unit class, and select Add objects from the context menu. The Add objects dialog will pop up.

  5. Enter the names for the system units as seen in the image below, then press Ok. This will create two objects of class unit, called power_plant_a and power_plant_b.

    _images/simple_system_add_units.png

Note

In SpineOpt, nodes are points where an energy balance takes place, whereas units are energy conversion devices that can take energy from nodes, and release energy to nodes.

  1. Right click on the output class, and select Add objects from the context menu. The Add objects dialog will pop up.

  2. Enter unit_flow under object name as in the image below, then press Ok. This will create one object of class unit, called unit_flow.

    _images/simple_system_add_output.png

Note

In SpineOpt, outputs represent optimization variables that can be written to the output database as part of a report.

Note

To modify an object after you enter it, right click on it and select Edit… from the context menu.

Establishing relationships
  1. Always in the Spine DB editor, locate the Relationship tree (typically at the bottom-left). Expand the root element if not expanded.

  2. Right click on the unit__from_node class, and select Add relationships from the context menu. The Add relationships dialog will pop up.

  3. Select the names of the two units and their sending nodes, as seen in the image below; then press Ok. This will establish that both power_plant_a and power_plant_b take energy from the fuel_node.

    _images/simple_system_add_unit__from_node_relationships.png
  4. Right click on the unit__to_node class, and select Add relationships from the context menu. The Add relationships dialog will pop up.

  5. Select the names of the two units and their receiving nodes, as seen in the image below; then press Ok. This will establish that both power_plant_a and power_plant_b release energy into the electricity_node.

    _images/simple_system_add_unit__to_node_relationships.png
  6. Right click on the report__output class, and select Add relationships from the context menu. The Add relationships dialog will pop up.

  7. Enter report1 under report, and unit_flow under output, as seen in the image below; then press Ok. This will tell SpineOpt to write the value of the unit_flow optimization variable to the output database, as part of report1.

    _images/simple_system_add_report__output_relationships.png
Specifying object parameter values
  1. Back to Object tree, expand the node class and select electricity_node.

  2. Locate the Object parameter table (typically at the top-center).

  3. In the Object parameter table (typically at the top-center), select the demand parameter and the Base alternative, and enter the value 100 as seen in the image below. This will establish that there’s a demand of ‘100’ at the electricity node.

    _images/simple_system_electricity_demand.png
  4. Select fuel_node in the Object tree.

  5. In the Object parameter table, select the balance_type parameter and the Base alternative, and enter the value balance_type_none as seen in the image below. This will establish that the fuel node is not balanced, and thus provide as much fuel as needed.

    _images/simple_system_fuel_balance_type.png
Specifying relationship parameter values
  1. In Relationship tree, expand the unit__from_node class and select power_plant_a | fuel_node.

  2. In the Relationship parameter table (typically at the bottom-center), select the vom_cost parameter and the Base alternative, and enter the value 25 as seen in the image below. This will set the operating cost for power_plant_a.

    _images/simple_system_power_plant_a_vom_cost.png
  3. Select power_plant_b | fuel_node in the Relationship tree.

  4. In the Relationship parameter table, select the vom_cost parameter and the Base alternative, and enter the value 50 as seen in the image below. This will set the operating cost for power_plant_b.

    _images/simple_system_power_plant_b_vom_cost.png
  5. In Relationship tree, expand the unit__to_node class and select power_plant_a | electricity_node.

  6. In the Relationship parameter table, select the unit_capacity parameter and the Base alternative, and enter the value 100 as seen in the image below. This will set the capacity for power_plant_a.

    _images/simple_system_power_plant_a_capacity.png
  7. Select power_plant_b | electricity_node in the Relationship tree.

  8. In the Relationship parameter table, select the unit_capacity parameter and the Base alternative, and enter the value 200 as seen in the image below. This will set the capacity for power_plant_b.

    _images/simple_system_power_plant_b_capacity.png
  9. In Relationship tree, select the unit__node__node class, and come back to the Relationship parameter table.

  10. In the Relationship parameter table, select power_plant_a | electricity_node | fuel_node under object name list, fix_ratio_out_in_unit_flow under parameter name, Base under alternative name, and enter 0.7 under value. Repeat the operation for power_plant_b, but this time enter 0.8 under value. This will set the conversion ratio from fuel to electricity for power_plant_a and power_plant_b to 0.7 and 0.8, respectively. It should like the image below.

    _images/simple_system_fix_ratio_out_in_unit_flow.png

When you’re ready, commit all changes to the database.

Executing the workflow
  1. Go back to Spine Toolbox’s main window, and hit the Execute project button execute_project from the tool bar.

    You should see ‘Executing All Directed Acyclic Graphs’ printed in the Event log (at the bottom left by default).

  2. Select the ‘Run SpineOpt 1’ Tool. You should see the output from SpineOpt in the Julia Console.

Examining the results
  1. Select the output data store and open the Spine DB editor.

  2. Press Alt + F to display the main menu, and select Pivot -> Index.

  3. Select report__unit__node__direction__stochastic_scenario under Relationship tree, and the first cell under alternative in the Frozen table.

  4. The Pivot table will be populated with results from the SpineOpt run. It will look something like the image below.

_images/simple_system_results_pivot_table.png

Spine Tutorial - Simple Hydro Power Planning

Welcome to this Spine Toolbox tutorial of a simple hydro power planning problem. The tutorial models one day of operation of two hydrodologically-coupled hydro power power plants.

Introduction

Model assumptions

For each hydro power plant, the following information is known.

  • The capacity, or the maximal electricity output.

  • The maximal amount of water the reservoirs can store.

  • The content of the reservoir at the beginning of the simulation period.

  • The minimal amount of spilled water required. Spilled water does not produce any electricity as it it does not go through the turbine; it helps the fish to pass the hydro power plant.

  • The minimal amount of total water flow, spilled + discharged required.

  • The water delay time between power plants is neglected.

  • The local inflow, or amount of water that naturally enters the reservoir at every hour. In this study, it is assumed constant over the entire simulation period.

The system is operated so as to maximize total profit over the day. In this simple exercise, the value of stored water (contained in the reservoirs at the end of the planning period) is not taken into account. Capacity constraints, maximal reservoir level constrains, and so on are limits the system.

Modelling choices

Modelling the electric system is simple, a common electricity node receives the power produced by the power plants. One electricity load unit then takes electricity from that node.

The river system is, however, more detailed. Each hydro power plant is modelled using the following elements:

  • An upper water node, located at the entrance of the plant.

  • A lower water node, located at the exit of the plant.

  • A flow node where discharged and spilled water is released into.

  • A power plant unit, that discharges water from the upper node into the lower node, and feeds electricity produced in the process to the common electricity node.

  • A spillway unit, that takes spilled water from the upper node and releases it to the flow node.

  • A discharge unit, that takes water from the lower node and releases it to the flow node.

Below is a schematic of the model. For clarity, the schematic only presents one power station:

_images/two_hydro_schema.png

Guide

Installing requirements

Note

This tutorial is written for latest Spine Toolbox and SpineOpt master versions.

Follow the instructions here to install Spine Toolbox and SpineOpt in your system.

Creating a new project

Each Spine Toolbox project resides in its own directory, where the user can store data, programming scripts and other necessary material. The Toolbox application also creates its own special subdirectory .spinetoolbox, for project settings, etc.

To create a new project, select File -> New project… from Spine Toolbox main menu. Browse to a location where you want to create the project and create a new folder for it, e.g., ‘Two_hydro’, and then click Select Folder.

Configuring SpineOpt
  1. To use SpineOpt in your project, you need to create a Tool specification for it. Click on the small arrow next to the Tool icon tool_icon (in the Main section of the tool bar), and press New… The Tool specification editor will popup:

    _images/edit_tool_specification_blank.png
  2. Type ‘SpineOpt’ as the name of the specification and select ‘Julia’ as the tool type. Deselect Execute in work directory.

  3. Press file-regular next to Main program file to create a new Julia file. Enter a file name, e.g. ‘run_spineopt.jl’, and click Save.

  4. Back in the Tool specification editor, select the file you just created under Main program file. Then, enter the following text in the text editor to the right:

    using SpineOpt
    
    run_spineopt(ARGS...)
    

    At this point, the form should be looking like this:

    _images/edit_tool_specification_spine_opt.png
  5. Press Ctrl+S to save everything, then close the Tool specification editor.

Setting up a project
  1. Drag the Data Store icon ds_icon from the tool bar and drop it into the Design View. This will open the Add Data Store dialogue. Type ‘input’ as the Data Store name and click Ok.

  2. Repeat the above procedure to create a Data Store called ‘output’.

  3. Create a database for the ‘input’ Data Store:

  1. Select the input Data Store item in the Design View to show the Data Store Properties (on the right side of the window, usually).

  2. In Data Store Properties, select the sqlite dialect at the top, and click New Spine db.

  1. Repeat the above procedure to create a database for the ‘output’ Data Store.

  2. Click on the small arrow next to the Tool icon tool_icon and drag the ‘SpineOpt’ item from the drop-down menu into the Design View. This will open the Add Tool dialogue. Type ‘SpineOpt’ as the Tool name and click Ok.

    Note

    Each item in the Design view is equipped with three connectors (the small squares at the item boundaries).

  3. Drag the Data Connection icon dc_icon from the tool bar and drop it into the Design View. This will open the Add Data connection dialogue. Type in ‘Data Connection’ and click on Ok.

  4. To import the model of the planning problem into the Spine database, you need to create an Import specification. Create an Import specification by clicking on the small arrow next to the Importer item (in the Main section of the toolbar) and press New. The Importer specification editor will pop-up:

  5. Type ‘Import Model’ as the name of the specification. Save the specification by using Ctrl+S and close the window.

  6. Drag the newly created Import Model Importer item icon importer_icon from the tool bar and drop it into the Design View. This will open the Add Importer dialogue. Type in ‘Import Model’ and click on Ok.

  7. Connect ‘Data Connection’ with ‘Import Model’ by first clicking on one of the Data Connection’s connectors and then on one of the Importer’s connectors.

  8. Repeat the procedure to create a path from ‘Data Connection’ to ‘output’. Now the project should look similar to this as shown below:

    _images/items_connections.png
  9. Setup the arguments for the SpineOpt Tool:

  1. Select the SpineOpt Tool to show the Tool Properties (on the right side of the window, usually). You should see two elements listed below Available resources, {db_url@input} and {db_url@output}.

  2. Drag the first resource, {db_url@input}, and drop it in Command line arguments, just as shown in the image below.

    _images/case_study_a5_spine_opt_tool_properties.png
  3. Drag the second resource, {db_url@output}, and drop it right below the previous one. The panel should be now looking like this:

    _images/case_study_a5_spine_opt_tool_properties_cmdline_args.png
  4. Double-check that the order of the arguments is correct: first, {db_url@input}, and second, {db_url@output}. (You can drag and drop to reorganize them if needed.)

  1. From the main menu, select File -> Save project.

Importing the model
  1. Download the SpineOpt database template , the data and the accompanying mapping (right click on the links, then select Save link as…).

  2. Add a reference to the file containing the model.

  1. Select the Data Connection item in the Design View to show the Data Connection properties window (on the right side of the window usually).

  2. In Data Connection Properties, click on the plus icon and select the previously downloaded Excel file.

  3. Next, double click on the Import model in the Design view. A window called Select connector for Import Model will pop-up, select Excel and klick OK. Next, still in the Importer specification editor, click the alternatives icon in the top right and import the mappings previously downloaded. Finally, save by clicking Ctrl+S and exit the Importer specification editor.

Executing the workflow
Importing raw data with the importer

Once the workflow is defined and source file is in place, the project is ready to import the data to the input database. While holding Ctrl, select Data Connection, Import Model, and input. Directly click the Execute selection button execute_selection on the tool bar.

You should see ‘Executing Selected Directed Acyclic Graphs’ printed in the Event log (on the lower left by default). SpineOpt output messages will appear in the Process Log panel in the middle. After some processing, ‘DAG 1/1 completed successfully’ appears and the execution is complete.

Importing the SpineOpt database template
  1. Select the input Data Store item in the Design View. Go to Data Store Properties and click on Open editor. This will open the newly created database in the Spine DB editor, looking similar to this:

    _images/two_hydro_db_editor.png

    Note

    The Spine DB editor is a dedicated interface within Spine Toolbox for visualizing and managing Spine databases.

  2. Press Alt + F to display the main menu, select File -> Import…, and then select the template file you previously downloaded. (Tip: Make sure you search for a folder with .json ending.) The contents of that file will be imported into the current database, and you should then see classes like ‘commodity’, ‘connection’ and ‘model’ under the root node in the Object tree (on the left) with colourful icons.

  3. From the menu in the top right corner, select Session -> Commit. Enter ‘Import SpineOpt template’ as message in the popup dialogue and click Commit. Exit the Spine DB editor.

    Note

    The SpineOpt template contains the fundamental object and relationship classes, as well as parameter definitions, that SpineOpt recognizes and expects. You can think of it as the generic structure of the model, as opposed to the specific data for a particular instance.

Execute the model

Finally, the project is ready to be executed. Hold Ctrl, select SpineOpt and output. Directly, click on Execute selection execute_selection.

Examining the results

Select the output data store and open the Spine DB editor. To checkout the flow on the electricity load (i.e., the total electricity production in the system), go to Object tree, expand the unit object class, and select electricity_load. Next, go to Relationship parameter value and double-click the first cell under value. The Parameter value editor will pop up. You should see something like this:

_images/two_hydro_output_electricity_unit_flow.png

Case Study A5 tutorial

Welcome to this Spine Toolbox Case Study tutorial. Case Study A5 is one of the Spine Project case studies designed to verify Toolbox and Model capabilities. To this end, it reproduces an already existing study about hydropower on the Skellefte river, which models one week of operation of the fifteen power stations along the river.

This tutorial provides a step-by-step guide to run Case Study A5 on Spine Toolbox and is organized as follows:

Introduction

Model assumptions

For each power station in the river, the following information is known:

  • The capacity, or maximal electricity output. This datum also provides the maximal water discharge as per the efficiency curve (see next point).

  • The efficiency curve, or conversion rate from water to electricity. In this study, a piece-wise linear efficiency with two segments is assumed. Moreover, this curve is monotonically decreasing, i.e., the efficiency in the first segment is strictly greater than the efficiency in the second segment.

  • The maximal reservoir level (maximal amount of water that can be stored in the reservoir).

  • The reservoir level at the beginning of the simulation period and at the end.

  • The minimal amount of water that the plant must discharge at every hour. This is usually zero (except for one of the plants).

  • The minimal amount of water that needs to be spilled at every hour. Spilled water does not go through the turbine and thus is not used for producing electricity; it just helps keeping the reservoir level at bay.

  • The downstream plant, or next plant in the river course.

  • The time that it takes for the water to reach the downstream plant. This time can be different depending on whether the water is discharged (goes through the turbine) or spilled.

  • The local inflow, or amount of water that naturally enters the reservoir at every hour. In this study, it is assumed constant over the entire simulation period.

  • The hourly average water discharge. It is assumed that before the beginning of the simulation, this amount of water has constantly been discharged at every hour.

The system is operated so as to maximize the total profit over the planning week, while respecting capacity constraints, maximal reservoir level constrains, etc. Hourly profit per plant is simply computed as the product of the electricity price and the production.

Modelling choices

The model of the electric system is fairly simple, only two elements are needed:

  • A common electricity node.

  • A load unit that takes electricity from that node.

On the contrary, the model of the river system is more detailed. Each power station in the river is modelled using the following elements:

  • An upper water node, located at the entrance of the station.

  • A lower water node, located at the exit of the station.

  • A power plant unit, that discharges water from the upper node into the lower node, and feeds electricity produced in the process to the common electricity node.

  • A spillway connection, that takes spilled water from the upper node and releases it to the downstream upper node.

  • A discharge connection, that takes water from the lower node and releases it to the downstream upper node.

Below is a schematic of the model. For clarity, only the Rebnis station is presented in full detail:

_images/case_study_a5_schematic.png

Installing requirements

Note

This tutorial is written for latest Spine Toolbox and SpineOpt master versions.

Follow the instructions here to install Spine Toolbox and SpineOpt in your system.

Creating a new project

Each Spine Toolbox project resides in its own directory, where the user can store data, programming scripts and other necessary material. The Toolbox application also creates its own special subdirectory .spinetoolbox, for project settings, etc.

To create a new project, select File -> New project… from Spine Toolbox main menu. Browse to a location where you want to create the project and create a new folder for it, e.g. ‘cs_a5_importer’, and then click Select Folder.

Configuring SpineOpt
  1. To use SpineOpt in your project, you need to create a Tool specification for it. Click on the small arrow next to the Tool icon tool_icon (in the Main section of the tool bar), and press New… The Tool specification editor will popup:

    _images/edit_tool_specification_blank.png
  2. Type ‘SpineOpt’ as the name of the specification and select ‘Julia’ as the tool type. Deselect Execute in work directory.

  3. Press file-regular next to Main program file to create a new Julia file. Enter a file name, e.g. ‘run_spineopt.jl’, and click Save.

  4. Back in the Tool specification editor, select the file you just created under Main program file. Then, enter the following text in the text editor to the right:

    using SpineOpt
    
    run_spineopt(ARGS...)
    

    At this point, the form should be looking like this:

    _images/edit_tool_specification_spine_opt.png
  5. Press Ctrl+S to save everything, then close the Tool specification editor.

Setting up a project
  1. Drag the Data Store icon ds_icon from the tool bar and drop it into the Design View. This will open the Add Data Store dialogue. Type ‘input’ as the Data Store name and click Ok.

  2. Repeat the above procedure to create a Data Store called ‘output’.

  3. Create a database for the ‘input‘ Data Store:

    1. Select the input Data Store item in the Design View to show the Data Store Properties (on the right side of the window, usually).

    2. In Data Store Properties, select the sqlite dialect at the top, and hit New Spine db.

  4. Repeat the above procedure to create a database for the ‘output’ Data Store.

  5. Drag the ‘SpineOpt’ item from the tool bar into the Design View. This will open the Add Tool dialogue. Type ‘SpineOpt’ as the Tool name and click Ok.

    Note

    Each item in the Design view is equipped with three connectors (the small squares at the item boundaries).

  6. Click on one of ‘input’ connectors and then on one of ‘SpineOpt’ connectors. This will create a connection from the former to the latter.

  7. Repeat the procedure to create a connection from SpineOpt to output. It should look something like this:

    _images/case_study_a5_item_connections.png
  8. Setup the arguments for the SpineOpt Tool:

    1. Select the SpineOpt Tool to show the Tool Properties (on the right side of the window, usually). You should see two elements listed under Available resources, {db_url@input} and {db_url@output}.

    2. Drag the first resource, {db_url@input}, and drop it in Command line arguments, just as shown in the image below.

      _images/case_study_a5_spine_opt_tool_properties.png
    3. Drag the second resource, {db_url@output}, and drop it right below the previous one. The panel should be now looking like this:

      _images/case_study_a5_spine_opt_tool_properties_cmdline_args.png
    4. Double-check that the order of the arguments is correct: first, {db_url@input}, and second, {db_url@output}. (You can drag and drop to reorganize them if needed.)

  9. From the main menu, select File -> Save project.

Importing the SpineOpt database template
  1. Download the SpineOpt database template (right click on the link, then select Save link as…)

  2. Select the input Data Store item in the Design View.

  3. Go to Data Store Properties and hit Open editor. This will open the newly created database in the Spine DB Editor, looking similar to this:

    _images/case_study_a5_spine_db_editor_empty.png

    Note

    The Spine DB editor is a dedicated interface within Spine Toolbox for visualizing and managing Spine databases.

  4. Press Alt + F to display the editor menu, select File -> Import…, and then select the template file you previously downloaded (in case it is not displayed in the folder where you saved it, doublecheck that you selected . The contents of that file will be imported into the current database, and you should then see classes like ‘commodity’, ‘connection’ and ‘model’ under the root node in the Object tree (on the left).

  5. From the editor menu (Alt + F), select Session -> Commit. Enter ‘Import SpineOpt template’ as message in the popup dialog, and click Commit.

Note

The SpineOpt template contains the fundamental object and relationship classes, as well as parameter definitions, that SpineOpt recognizes and expects. You can think of it as the generic structure of the model, as opposed to the specific data for a particular instance. In the remainder of this section, we will add that specific data for the Skellefte river.

Entering data

There are two options in this tutorial to enter data in the Database. The first one is to enter data manually and the second to use the importer functionality. These are described in the next two subsections respectively.

Entering data manually
Creating objects
  1. To add power plants to the model, stay in the Spine DB Editor and create objects of class unit as follows:

    1. Select the list of plant names from the text-box below and copy it to the clipboard (Ctrl+C):

      Rebnis_pwr_plant
      Sadva_pwr_plant
      Bergnäs_pwr_plant
      Slagnäs_pwr_plant
      Bastusel_pwr_plant
      Grytfors_pwr_plant
      Gallejaur_pwr_plant
      Vargfors_pwr_plant
      Rengård_pwr_plant
      Båtfors_pwr_plant
      Finnfors_pwr_plant
      Granfors_pwr_plant
      Krångfors_pwr_plant
      Selsfors_pwr_plant
      Kvistforsen_pwr_plant
      
    2. Go to Object tree (on the top left of the window, usually), right-click on unit and select Add objects from the context menu. This will open the Add objects dialog.

    3. Select the first cell under the object name column and press Ctrl+V. This will paste the list of plant names from the clipboard into that column; the object class name column will be filled automatically with ‘unit‘. The form should now be looking similar to this:

      _images/add_power_plant_units.png
    4. Click Ok.

    5. Back in the Spine DB Editor, under Object tree, double click on unit to confirm that the objects are effectively there.

    6. Commit changes with the message ‘Add power plants’.

  2. Add discharge and spillway connections by creating objects of class connection with the following names:

    Rebnis_to_Bergnäs_disch
    Sadva_to_Bergnäs_disch
    Bergnäs_to_Slagnäs_disch
    Slagnäs_to_Bastusel_disch
    Bastusel_to_Grytfors_disch
    Grytfors_to_Gallejaur_disch
    Gallejaur_to_Vargfors_disch
    Vargfors_to_Rengård_disch
    Rengård_to_Båtfors_disch
    Båtfors_to_Finnfors_disch
    Finnfors_to_Granfors_disch
    Granfors_to_Krångfors_disch
    Krångfors_to_Selsfors_disch
    Selsfors_to_Kvistforsen_disch
    Kvistforsen_to_downstream_disch
    Rebnis_to_Bergnäs_spill
    Sadva_to_Bergnäs_spill
    Bergnäs_to_Slagnäs_spill
    Slagnäs_to_Bastusel_spill
    Bastusel_to_Grytfors_spill
    Grytfors_to_Gallejaur_spill
    Gallejaur_to_Vargfors_spill
    Vargfors_to_Rengård_spill
    Rengård_to_Båtfors_spill
    Båtfors_to_Finnfors_spill
    Finnfors_to_Granfors_spill
    Granfors_to_Krångfors_spill
    Krångfors_to_Selsfors_spill
    Selsfors_to_Kvistforsen_spill
    Kvistforsen_to_downstream_spill
    
  3. Add water nodes by creating objects of class node with the following names:

    Rebnis_upper
    Sadva_upper
    Bergnäs_upper
    Slagnäs_upper
    Bastusel_upper
    Grytfors_upper
    Gallejaur_upper
    Vargfors_upper
    Rengård_upper
    Båtfors_upper
    Finnfors_upper
    Granfors_upper
    Krångfors_upper
    Selsfors_upper
    Kvistforsen_upper
    Rebnis_lower
    Sadva_lower
    Bergnäs_lower
    Slagnäs_lower
    Bastusel_lower
    Grytfors_lower
    Gallejaur_lower
    Vargfors_lower
    Rengård_lower
    Båtfors_lower
    Finnfors_lower
    Granfors_lower
    Krångfors_lower
    Selsfors_lower
    Kvistforsen_lower
    
  4. Next, create the following objects (all names in lower-case):

    1. instance of class model.

    2. water and electricity of class commodity.

    3. electricity_node of class node.

    4. electricity_load of class unit.

    5. some_week of class temporal_block.

    6. deterministic of class stochastic_structure.

    7. realization of class stochastic_scenario.

  5. Finally, create the following objects to get results back from Spine Opt (again, all names in lower-case):

    1. my_report of class report.

    2. unit_flow, connection_flow, and node_state of class output.

Note

To modify an object after you enter it, right click on it and select Edit… from the context menu.

Specifying object parameter values
  1. To specify the general behaviour of our model, stay in the Spine DB Editor and enter model parameter values as follows:

    1. Select the model parameter value data from the text-box below and copy it to the clipboard (Ctrl+C):

      model	instance	duration_unit	Base	"hour"
      model	instance	model_end	Base	{"type": "date_time", "data": "2019-01-08T00:00:00"}
      model	instance	model_start	Base	{"type": "date_time", "data": "2019-01-01T00:00:00"}
      
    2. Select instance in the Object tree and inspect the table in Object parameter value (on the top-center of the window, usually). Make sure that the columns in the table are ordered as follows (drag and drop columns if you need to change their order):

      object_class_name | object_name | parameter_name | alternative_name | value | database
      
    3. Select the first cell under object_class_name and press Ctrl+V. This will paste the model parameter value data from the clipboard into the table. The form should be looking like this:

      _images/case_study_a5_model_parameters.png
  2. Specify the resolution of our temporal block some_week in the same way using the data below:

    temporal_block	some_week	resolution	Base	{"type": "duration", "data": "1h"}
    
  3. Specify the behaviour of all system nodes with the data below, where:

    1. demand represents the local inflow (negative in most cases).

    2. fix_node_state represents fixed reservoir levels (at the beginning and the end).

    3. has_state indicates whether or not the node is a reservoir (true for all the upper nodes).

    4. state_coeff is the reservoir ‘efficienty’ (always 1, meaning that there aren’t any loses).

    5. node_state_cap is the maximum level of the reservoirs.

    To do this in one single step, simply select node in the Object tree and paste the following values in the first empty cell:

    node	Bastusel_upper	demand	Base	-0.2579768519
    node	Bergnäs_upper	demand	Base	-22.29
    node	Båtfors_upper	demand	Base	-2
    node	Finnfors_upper	demand	Base	0
    node	Gallejaur_upper	demand	Base	15.356962963
    node	Granfors_upper	demand	Base	0
    node	Grytfors_upper	demand	Base	-3.78
    node	Krångfors_upper	demand	Base	0
    node	Kvistforsen_upper	demand	Base	-1.3273809524
    node	Rebnis_upper	demand	Base	-3.68
    node	Rengård_upper	demand	Base	-10.37
    node	Sadva_upper	demand	Base	-5.43
    node	Selsfors_upper	demand	Base	0
    node	Slagnäs_upper	demand	Base	0
    node	Vargfors_upper	demand	Base	-3.5584953704
    node	Bastusel_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 5581.44, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 5417.28}}
    node	Bergnäs_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 114543.6, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 105898.8}}
    node	Båtfors_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 1117.2, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 891.1}}
    node	Finnfors_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 234.0, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 234.0}}
    node	Gallejaur_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 1224.0, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 2808.0}}
    node	Granfors_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 232.4, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 212.8}}
    node	Grytfors_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 1060.8, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 1110.72}}
    node	Krångfors_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 201.3, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 207.9}}
    node	Kvistforsen_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 769.066666704, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 560.0}}
    node	Rebnis_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 70243.509200184, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 59524.122689676}}
    node	Rengård_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 1022.0, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 770.0}}
    node	Sadva_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 99057.7777728, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 93831.111108}}
    node	Selsfors_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 40.0, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 200.0}}
    node	Slagnäs_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 384.0, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 537.6}}
    node	Vargfors_upper	fix_node_state	Base	{"type": "time_series", "data": {"2019-01-01T00:00:00": 3386.76, "2019-01-01T01:00:00": NaN, "2019-01-07T23:00:00": 3847.68}}
    node	Bastusel_upper	has_state	Base	true
    node	Bergnäs_upper	has_state	Base	true
    node	Båtfors_upper	has_state	Base	true
    node	Finnfors_upper	has_state	Base	true
    node	Gallejaur_upper	has_state	Base	true
    node	Granfors_upper	has_state	Base	true
    node	Grytfors_upper	has_state	Base	true
    node	Krångfors_upper	has_state	Base	true
    node	Kvistforsen_upper	has_state	Base	true
    node	Rebnis_upper	has_state	Base	true
    node	Rengård_upper	has_state	Base	true
    node	Sadva_upper	has_state	Base	true
    node	Selsfors_upper	has_state	Base	true
    node	Slagnäs_upper	has_state	Base	true
    node	Vargfors_upper	has_state	Base	true
    node	Bastusel_upper	state_coeff	Base	1
    node	Bergnäs_upper	state_coeff	Base	1
    node	Båtfors_upper	state_coeff	Base	1
    node	Finnfors_upper	state_coeff	Base	1
    node	Gallejaur_upper	state_coeff	Base	1
    node	Granfors_upper	state_coeff	Base	1
    node	Grytfors_upper	state_coeff	Base	1
    node	Krångfors_upper	state_coeff	Base	1
    node	Kvistforsen_upper	state_coeff	Base	1
    node	Rebnis_upper	state_coeff	Base	1
    node	Rengård_upper	state_coeff	Base	1
    node	Sadva_upper	state_coeff	Base	1
    node	Selsfors_upper	state_coeff	Base	1
    node	Slagnäs_upper	state_coeff	Base	1
    node	Vargfors_upper	state_coeff	Base	1
    node	Bastusel_upper	node_state_cap	Base	8208
    node	Bergnäs_upper	node_state_cap	Base	216120
    node	Båtfors_upper	node_state_cap	Base	1330
    node	Finnfors_upper	node_state_cap	Base	300
    node	Gallejaur_upper	node_state_cap	Base	3600
    node	Granfors_upper	node_state_cap	Base	280
    node	Grytfors_upper	node_state_cap	Base	1248
    node	Krångfors_upper	node_state_cap	Base	330
    node	Kvistforsen_upper	node_state_cap	Base	1120
    node	Rebnis_upper	node_state_cap	Base	205560
    node	Rengård_upper	node_state_cap	Base	1400
    node	Sadva_upper	node_state_cap	Base	168000
    node	Selsfors_upper	node_state_cap	Base	500
    node	Slagnäs_upper	node_state_cap	Base	768
    node	Vargfors_upper	node_state_cap	Base	4008
    
Establishing relationships

Tip

To enter the same text on several cells, copy the text into the clipboard, then select all target cells and press Ctrl+V.

  1. Create relationships of the class unit__from_node to represent that a power plant receives water from the station’s upper water node, and that the electricity load takes electricity from the common electricity node. Both the power plants and the electricity load belong to the class unit.

    1. Select the list of unit and node names from below and copy it to the clipboard (Ctrl+C).

      Rebnis_pwr_plant	Rebnis_upper
      Sadva_pwr_plant	Sadva_upper
      Bergnäs_pwr_plant	Bergnäs_upper
      Slagnäs_pwr_plant	Slagnäs_upper
      Bastusel_pwr_plant	Bastusel_upper
      Grytfors_pwr_plant	Grytfors_upper
      Gallejaur_pwr_plant	Gallejaur_upper
      Vargfors_pwr_plant	Vargfors_upper
      Rengård_pwr_plant	Rengård_upper
      Båtfors_pwr_plant	Båtfors_upper
      Finnfors_pwr_plant	Finnfors_upper
      Granfors_pwr_plant	Granfors_upper
      Krångfors_pwr_plant	Krångfors_upper
      Selsfors_pwr_plant	Selsfors_upper
      Kvistforsen_pwr_plant	Kvistforsen_upper
      electricity_load	electricity_node
      
    2. In the Spine DB Editor, go to Relationship tree (on the bottom left of the window, usually), right-click on unit__from_node and select Add relationships from the context menu. This will open the Add relationships dialog.

    3. Select the first cell under the unit column and press Ctrl+V. This will paste the list of plant and node names from the clipboard into the table. The form should be looking like this:

      _images/add_pwr_plant_water_from_node.png
    4. Click Ok.

    5. Back in the Spine DB Editor, under Relationship tree, double click on unit__from_node to confirm that the relationships are effectively there.

    6. From the main menu (Alt + F), select Session -> Commit to open the Commit changes dialog. Enter ‘Add from nodes of power plants‘ as the commit message and click Commit.

  2. Create relationships of the class unit__to_node to represent that a power plant releases water to the station’s lower water node, and that the power plants supply electricity to the common electricity node. Use the following data and do as before:

    Rebnis_pwr_plant	Rebnis_lower
    Sadva_pwr_plant	Sadva_lower
    Bergnäs_pwr_plant	Bergnäs_lower
    Slagnäs_pwr_plant	Slagnäs_lower
    Bastusel_pwr_plant	Bastusel_lower
    Grytfors_pwr_plant	Grytfors_lower
    Gallejaur_pwr_plant	Gallejaur_lower
    Vargfors_pwr_plant	Vargfors_lower
    Rengård_pwr_plant	Rengård_lower
    Båtfors_pwr_plant	Båtfors_lower
    Finnfors_pwr_plant	Finnfors_lower
    Granfors_pwr_plant	Granfors_lower
    Krångfors_pwr_plant	Krångfors_lower
    Selsfors_pwr_plant	Selsfors_lower
    Kvistforsen_pwr_plant	Kvistforsen_lower
    Rebnis_pwr_plant	electricity_node
    Sadva_pwr_plant	electricity_node
    Bergnäs_pwr_plant	electricity_node
    Slagnäs_pwr_plant	electricity_node
    Bastusel_pwr_plant	electricity_node
    Grytfors_pwr_plant	electricity_node
    Gallejaur_pwr_plant	electricity_node
    Vargfors_pwr_plant	electricity_node
    Rengård_pwr_plant	electricity_node
    Båtfors_pwr_plant	electricity_node
    Finnfors_pwr_plant	electricity_node
    Granfors_pwr_plant	electricity_node
    Krångfors_pwr_plant	electricity_node
    Selsfors_pwr_plant	electricity_node
    Kvistforsen_pwr_plant	electricity_node
    

    Note

    At this point, you might be wondering what’s the purpose of the unit__node__node relationship class. Shouldn’t it be enough to have unit__from_node and unit__to_node to represent the topology of the system? The answer is yes; but in addition to topology, we also need to represent the conversion process that happens in the unit, where the water from one node is turned into electricty for another node. And for this purpose, we use a relationship parameter value on the unit__node__node relationships (see Specifying relationship parameter values).

  3. Create relationships of the class connection__from_node to represent that water can be either discharged or spilled. If discharged, it is taken from the lower water node of the station, if spilled it is taken from the upper water node of the station. Use the following data and do as before:

    Bastusel_to_Grytfors_disch	Bastusel_lower
    Bergnäs_to_Slagnäs_disch	Bergnäs_lower
    Båtfors_to_Finnfors_disch	Båtfors_lower
    Finnfors_to_Granfors_disch	Finnfors_lower
    Gallejaur_to_Vargfors_disch	Gallejaur_lower
    Granfors_to_Krångfors_disch	Granfors_lower
    Grytfors_to_Gallejaur_disch	Grytfors_lower
    Krångfors_to_Selsfors_disch	Krångfors_lower
    Kvistforsen_to_downstream_disch	Kvistforsen_lower
    Rebnis_to_Bergnäs_disch	Rebnis_lower
    Rengård_to_Båtfors_disch	Rengård_lower
    Sadva_to_Bergnäs_disch	Sadva_lower
    Selsfors_to_Kvistforsen_disch	Selsfors_lower
    Slagnäs_to_Bastusel_disch	Slagnäs_lower
    Vargfors_to_Rengård_disch	Vargfors_lower
    Bastusel_to_Grytfors_spill	Bastusel_upper
    Bergnäs_to_Slagnäs_spill	Bergnäs_upper
    Båtfors_to_Finnfors_spill	Båtfors_upper
    Finnfors_to_Granfors_spill	Finnfors_upper
    Gallejaur_to_Vargfors_spill	Gallejaur_upper
    Granfors_to_Krångfors_spill	Granfors_upper
    Grytfors_to_Gallejaur_spill	Grytfors_upper
    Krångfors_to_Selsfors_spill	Krångfors_upper
    Kvistforsen_to_downstream_spill	Kvistforsen_upper
    Rebnis_to_Bergnäs_spill	Rebnis_upper
    Rengård_to_Båtfors_spill	Rengård_upper
    Sadva_to_Bergnäs_spill	Sadva_upper
    Selsfors_to_Kvistforsen_spill	Selsfors_upper
    Slagnäs_to_Bastusel_spill	Slagnäs_upper
    Vargfors_to_Rengård_spill	Vargfors_upper
    
  4. Create relationships of the class connection__to_node to represent that both discharge and spill are released into the upper node of the next downstream station. Use the following data and do as before:

    Bastusel_to_Grytfors_disch	Grytfors_upper
    Bastusel_to_Grytfors_spill	Grytfors_upper
    Bergnäs_to_Slagnäs_disch	Slagnäs_upper
    Bergnäs_to_Slagnäs_spill	Slagnäs_upper
    Båtfors_to_Finnfors_disch	Finnfors_upper
    Båtfors_to_Finnfors_spill	Finnfors_upper
    Finnfors_to_Granfors_disch	Granfors_upper
    Finnfors_to_Granfors_spill	Granfors_upper
    Gallejaur_to_Vargfors_disch	Vargfors_upper
    Gallejaur_to_Vargfors_spill	Vargfors_upper
    Granfors_to_Krångfors_disch	Krångfors_upper
    Granfors_to_Krångfors_spill	Krångfors_upper
    Grytfors_to_Gallejaur_disch	Gallejaur_upper
    Grytfors_to_Gallejaur_spill	Gallejaur_upper
    Krångfors_to_Selsfors_disch	Selsfors_upper
    Krångfors_to_Selsfors_spill	Selsfors_upper
    Rebnis_to_Bergnäs_disch	Bergnäs_upper
    Rebnis_to_Bergnäs_spill	Bergnäs_upper
    Rengård_to_Båtfors_disch	Båtfors_upper
    Rengård_to_Båtfors_spill	Båtfors_upper
    Sadva_to_Bergnäs_disch	Bergnäs_upper
    Sadva_to_Bergnäs_spill	Bergnäs_upper
    Selsfors_to_Kvistforsen_disch	Kvistforsen_upper
    Selsfors_to_Kvistforsen_spill	Kvistforsen_upper
    Slagnäs_to_Bastusel_disch	Bastusel_upper
    Slagnäs_to_Bastusel_spill	Bastusel_upper
    Vargfors_to_Rengård_disch	Rengård_upper
    Vargfors_to_Rengård_spill	Rengård_upper
    

    Note

    At this point, you might be wondering what’s the purpose of the connection__node__node relationship class. Shouldn’t it be enough to have connection__from_node and connection__to_node to represent the topology of the system? The answer is yes; but in addition to topology, we also need to represent the delay in the river branches. And for this purpose, we use a relationship parameter value on the connection__node__node relationships (see Specifying relationship parameter values).

  5. Create relationships of the class node__commodity to represent that each node has to be in balance, for water nodes with respect to water, for electricity nodes with respect to electricity. This way, you link all nodes to either the commocity water or the commodity electricity. Use the following data and do as before:

    Rebnis_upper	water
    Sadva_upper	water
    Bergnäs_upper	water
    Slagnäs_upper	water
    Bastusel_upper	water
    Grytfors_upper	water
    Gallejaur_upper	water
    Vargfors_upper	water
    Rengård_upper	water
    Båtfors_upper	water
    Finnfors_upper	water
    Granfors_upper	water
    Krångfors_upper	water
    Selsfors_upper	water
    Kvistforsen_upper	water
    Rebnis_lower	water
    Sadva_lower	water
    Bergnäs_lower	water
    Slagnäs_lower	water
    Bastusel_lower	water
    Grytfors_lower	water
    Gallejaur_lower	water
    Vargfors_lower	water
    Rengård_lower	water
    Båtfors_lower	water
    Finnfors_lower	water
    Granfors_lower	water
    Krångfors_lower	water
    Selsfors_lower	water
    Kvistforsen_lower	water
    electricity_node	electricity
    
  6. Define that all nodes in our model have to be balanced at each time step. To do this, you create a relationship of the class model__default_temporal_block between the model instance and the temporal_block some_week in the same way as before.

  7. Define that our model is deterministic. To do this, you create a relationship of the class model__default_stochastic_structure between the model instance and the stochastic structure deterministic, as well as a relationship of class stochastic_structure__stochastic_scenario between the stochastid structure deterministic and the stochastic scenario realization in the same way as before.

  8. In order to get the results from running Spine Opt written to the ouput database, create relationships of the class report__output between the report my_report and each of the following output objects: unit_flow, connection_flow, and node_state. In addition, you also need to create a relationship of the class model__report between the model instance and the report my_report.

Specifying parameter values of the relationships
  1. Finally, the values of all parameters have to be entered. Specify the capacity of all hydropower plants, and their respective variable operating cost by entering unit__from_node parameter values as follows:

    1. Select the data from the text-box below and copy it to the clipboard (Ctrl+C):

      unit__from_node	Bastusel_pwr_plant,Bastusel_upper	unit_capacity	Base	127.5
      unit__from_node	Bergnäs_pwr_plant,Bergnäs_upper	unit_capacity	Base	120
      unit__from_node	Båtfors_pwr_plant,Båtfors_upper	unit_capacity	Base	210
      unit__from_node	Finnfors_pwr_plant,Finnfors_upper	unit_capacity	Base	176.25
      unit__from_node	Gallejaur_pwr_plant,Gallejaur_upper	unit_capacity	Base	228.75
      unit__from_node	Granfors_pwr_plant,Granfors_upper	unit_capacity	Base	180
      unit__from_node	Grytfors_pwr_plant,Grytfors_upper	unit_capacity	Base	123.75
      unit__from_node	Krångfors_pwr_plant,Krångfors_upper	unit_capacity	Base	180
      unit__from_node	Kvistforsen_pwr_plant,Kvistforsen_upper	minimum_operating_point	Base	0.0888888888889
      unit__from_node	Kvistforsen_pwr_plant,Kvistforsen_upper	unit_capacity	Base	225
      unit__from_node	Rebnis_pwr_plant,Rebnis_upper	unit_capacity	Base	60
      unit__from_node	Rengård_pwr_plant,Rengård_upper	unit_capacity	Base	165
      unit__from_node	Sadva_pwr_plant,Sadva_upper	unit_capacity	Base	52.5
      unit__from_node	Selsfors_pwr_plant,Selsfors_upper	unit_capacity	Base	225
      unit__from_node	Slagnäs_pwr_plant,Slagnäs_upper	unit_capacity	Base	120
      unit__from_node	Vargfors_pwr_plant,Vargfors_upper	unit_capacity	Base	232.5
      unit__from_node	electricity_load,electricity_node	vom_cost	Base	{"type": "time_series", "index": {"start": "2019-01-01 00:00:00", "resolution": "1h", "ignore_year": false, "repeat": false}, "data": [-162.03, -156.36, -151.06, -153.52, -158.91, -164.02, -175.56, -283.11, -278.76, -299.57, -285.28, -207.34, -194.95, -190.41, -185.4, -183.41, -191.54, -202.9, -197.69, -195.33, -186.72, -178.87, -174.71, -168.75, -172.89, -172.13, -171.66, -173.27, -176.97, -179.63, -226.41, -271.96, -399.3, -402.53, -353.28, -330.79, -294.54, -271.29, -248.71, -226.79, -240.93, -374.44, -255.54, -210.47, -186.65, -178.21, -173.18, -166.44, -165.09, -162.91, -161.11, -162.53, -166.04, -169.16, -174.28, -185.37, -195.79, -189.92, -187.74, -181.96, -179.12, -178.36, -177.13, -177.03, -177.69, -184.8, -187.27, -179.49, -175.23, -172.67, -169.07, -165.37, -170.06, -171.48, -171.58, -174.14, -180.3, -185.89, -195.37, -328.65, -365.91, -315.0, -242.68, -230.73, -225.33, -225.8, -213.38, -207.32, -215.37, -243.81, -243.53, -215.56, -192.05, -187.88, -181.15, -172.15, -174.16, -171.05, -170.77, -174.82, -179.62, -178.87, -191.49, -229.64, -336.07, -242.07, -228.5, -201.85, -196.67, -192.34, -190.36, -187.44, -186.68, -190.26, -191.21, -187.53, -179.34, -171.9, -166.53, -160.59, -166.08, -157.74, -145.36, -145.64, -147.42, -149.77, -153.33, -141.33, -145.08, -150.52, -153.42, -159.43, -159.05, -149.49, -147.89, -150.52, -157.08, -172.37, -174.06, -171.15, -160.46, -147.8, -141.61, -134.39, -144.41, -140.19, -138.59, -140.0, -139.53, -140.28, -144.03, -146.57, -149.39, -156.24, -157.93, -156.43, -155.21, -149.86, -148.07, -147.13, -148.82, -162.53, -174.74, -170.89, -163.94, -157.93, -150.7, -143.94]}
      
    2. In the Spine DB Editor, go to Relationship tree (on the bottom left of the window, usually), and click on unit__from_node. Then, go to Relationship parameter value (on the bottom-center of the window, usually). Make sure that the columns in the table are ordered as follows (drag and drop columns if you need to change their order):

      relationship_class_name | object_name_list | parameter_name | alternative_name | value | database
      
    3. Select the first cell under relationship_class_name and press Ctrl+V. This will paste the parameter value data from the clipboard into the table.

  2. Specify the conversion ratio between discharged water and generated electricity for each hydropower station as well as a similar conversion rate (set to 1) to represent that water cannot be lost between upper and lower water nodes. Use the following data to enter the parameter values unit__from_node:

    unit__node__node	Bastusel_pwr_plant,electricity_node,Bastusel_upper	fix_ratio_out_in_unit_flow	Base	0.577810871184
    unit__node__node	Bergnäs_pwr_plant,electricity_node,Bergnäs_upper	fix_ratio_out_in_unit_flow	Base	0.0506329113924
    unit__node__node	Båtfors_pwr_plant,electricity_node,Båtfors_upper	fix_ratio_out_in_unit_flow	Base	0.148282097649
    unit__node__node	Finnfors_pwr_plant,electricity_node,Finnfors_upper	fix_ratio_out_in_unit_flow	Base	0.180985725828
    unit__node__node	Gallejaur_pwr_plant,electricity_node,Gallejaur_upper	fix_ratio_out_in_unit_flow	Base	0.730442000415
    unit__node__node	Granfors_pwr_plant,electricity_node,Granfors_upper	fix_ratio_out_in_unit_flow	Base	0.164556962025
    unit__node__node	Grytfors_pwr_plant,electricity_node,Grytfors_upper	fix_ratio_out_in_unit_flow	Base	0.190257000384
    unit__node__node	Krångfors_pwr_plant,electricity_node,Krångfors_upper	fix_ratio_out_in_unit_flow	Base	0.274261603376
    unit__node__node	Kvistforsen_pwr_plant,electricity_node,Kvistforsen_upper	fix_ratio_out_in_unit_flow	Base	0.472573839662
    unit__node__node	Rebnis_pwr_plant,electricity_node,Rebnis_upper	fix_ratio_out_in_unit_flow	Base	0.810126582278
    unit__node__node	Rengård_pwr_plant,electricity_node,Rengård_upper	fix_ratio_out_in_unit_flow	Base	0.165707710012
    unit__node__node	Sadva_pwr_plant,electricity_node,Sadva_upper	fix_ratio_out_in_unit_flow	Base	0.448462929476
    unit__node__node	Selsfors_pwr_plant,electricity_node,Selsfors_upper	fix_ratio_out_in_unit_flow	Base	0.209282700422
    unit__node__node	Slagnäs_pwr_plant,electricity_node,Slagnäs_upper	fix_ratio_out_in_unit_flow	Base	0.0443037974684
    unit__node__node	Vargfors_pwr_plant,electricity_node,Vargfors_upper	fix_ratio_out_in_unit_flow	Base	0.34299714169
    unit__node__node	Bastusel_pwr_plant,Bastusel_lower,Bastusel_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Bergnäs_pwr_plant,Bergnäs_lower,Bergnäs_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Båtfors_pwr_plant,Båtfors_lower,Båtfors_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Finnfors_pwr_plant,Finnfors_lower,Finnfors_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Gallejaur_pwr_plant,Gallejaur_lower,Gallejaur_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Granfors_pwr_plant,Granfors_lower,Granfors_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Grytfors_pwr_plant,Grytfors_lower,Grytfors_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Krångfors_pwr_plant,Krångfors_lower,Krångfors_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Kvistforsen_pwr_plant,Kvistforsen_lower,Kvistforsen_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Rebnis_pwr_plant,Rebnis_lower,Rebnis_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Rengård_pwr_plant,Rengård_lower,Rengård_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Sadva_pwr_plant,Sadva_lower,Sadva_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Selsfors_pwr_plant,Selsfors_lower,Selsfors_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Slagnäs_pwr_plant,Slagnäs_lower,Slagnäs_upper	fix_ratio_out_in_unit_flow	Base	1
    unit__node__node	Vargfors_pwr_plant,Vargfors_lower,Vargfors_upper	fix_ratio_out_in_unit_flow	Base	1
    
  3. Specify the average discharge and spillage in the first hours of the simulation. Use the following data to enter the parameter values connection__from_node:

    connection__from_node	Bastusel_to_Grytfors_disch,Bastusel_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [110.7, 110.7]}
    connection__from_node	Bergnäs_to_Slagnäs_disch,Bergnäs_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [105.0, 105.0]}
    connection__from_node	Båtfors_to_Finnfors_disch,Båtfors_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [150.2, 150.2]}
    connection__from_node	Finnfors_to_Granfors_disch,Finnfors_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [155.3, 155.3]}
    connection__from_node	Gallejaur_to_Vargfors_disch,Gallejaur_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [118.2, 118.2]}
    connection__from_node	Granfors_to_Krångfors_disch,Granfors_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [155.6, 155.6]}
    connection__from_node	Grytfors_to_Gallejaur_disch,Grytfors_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [117.2, 117.2]}
    connection__from_node	Krångfors_to_Selsfors_disch,Krångfors_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [156.0, 156.0]}
    connection__from_node	Kvistforsen_to_downstream_disch,Kvistforsen_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [158.5, 158.5]}
    connection__from_node	Rebnis_to_Bergnäs_disch,Rebnis_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [21.5, 21.5]}
    connection__from_node	Rengård_to_Båtfors_disch,Rengård_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [141.5, 141.5]}
    connection__from_node	Sadva_to_Bergnäs_disch,Sadva_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [34.6, 34.6]}
    connection__from_node	Selsfors_to_Kvistforsen_disch,Selsfors_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [158.4, 158.4]}
    connection__from_node	Slagnäs_to_Bastusel_disch,Slagnäs_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [106.6, 106.6]}
    connection__from_node	Vargfors_to_Rengård_disch,Vargfors_lower	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [119.6, 119.6]}
    connection__from_node	Bastusel_to_Grytfors_spill,Bastusel_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Bergnäs_to_Slagnäs_spill,Bergnäs_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Båtfors_to_Finnfors_spill,Båtfors_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Finnfors_to_Granfors_spill,Finnfors_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Gallejaur_to_Vargfors_spill,Gallejaur_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Granfors_to_Krångfors_spill,Granfors_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Grytfors_to_Gallejaur_spill,Grytfors_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Krångfors_to_Selsfors_spill,Krångfors_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Kvistforsen_to_downstream_spill,Kvistforsen_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Rebnis_to_Bergnäs_spill,Rebnis_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Rengård_to_Båtfors_spill,Rengård_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Sadva_to_Bergnäs_spill,Sadva_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Selsfors_to_Kvistforsen_spill,Selsfors_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Slagnäs_to_Bastusel_spill,Slagnäs_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    connection__from_node	Vargfors_to_Rengård_spill,Vargfors_upper	fix_connection_flow	Base	{"type": "time_series", "index": {"start": "2018-12-30 00:00:00", "resolution": "2D"}, "data": [0.0, 0.0]}
    
  4. Finally, specify the delay (the time it takes for the water to run between water nodes) and the transfer ratio (being equal to 1) of different water connections. Use the following data to enter the parameter values connection__node_node:

    connection__node__node	Bastusel_to_Grytfors_disch,Grytfors_upper,Bastusel_lower	connection_flow_delay	Base	{"type": "duration", "data": "1h"}
    connection__node__node	Bastusel_to_Grytfors_spill,Grytfors_upper,Bastusel_upper	connection_flow_delay	Base	{"type": "duration", "data": "150m"}
    connection__node__node	Bergnäs_to_Slagnäs_disch,Slagnäs_upper,Bergnäs_lower	connection_flow_delay	Base	{"type": "duration", "data": "1h"}
    connection__node__node	Bergnäs_to_Slagnäs_spill,Slagnäs_upper,Bergnäs_upper	connection_flow_delay	Base	{"type": "duration", "data": "1h"}
    connection__node__node	Båtfors_to_Finnfors_disch,Finnfors_upper,Båtfors_lower	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Båtfors_to_Finnfors_spill,Finnfors_upper,Båtfors_upper	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Finnfors_to_Granfors_disch,Granfors_upper,Finnfors_lower	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Finnfors_to_Granfors_spill,Granfors_upper,Finnfors_upper	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Gallejaur_to_Vargfors_disch,Vargfors_upper,Gallejaur_lower	connection_flow_delay	Base	{"type": "duration", "data": "30m"}
    connection__node__node	Gallejaur_to_Vargfors_spill,Vargfors_upper,Gallejaur_upper	connection_flow_delay	Base	{"type": "duration", "data": "150m"}
    connection__node__node	Granfors_to_Krångfors_disch,Krångfors_upper,Granfors_lower	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Granfors_to_Krångfors_spill,Krångfors_upper,Granfors_upper	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Grytfors_to_Gallejaur_disch,Gallejaur_upper,Grytfors_lower	connection_flow_delay	Base	{"type": "duration", "data": "15m"}
    connection__node__node	Grytfors_to_Gallejaur_spill,Gallejaur_upper,Grytfors_upper	connection_flow_delay	Base	{"type": "duration", "data": "15m"}
    connection__node__node	Krångfors_to_Selsfors_disch,Selsfors_upper,Krångfors_lower	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Krångfors_to_Selsfors_spill,Selsfors_upper,Krångfors_upper	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Rebnis_to_Bergnäs_disch,Bergnäs_upper,Rebnis_lower	connection_flow_delay	Base	{"type": "duration", "data": "2D"}
    connection__node__node	Rebnis_to_Bergnäs_spill,Bergnäs_upper,Rebnis_upper	connection_flow_delay	Base	{"type": "duration", "data": "2D"}
    connection__node__node	Rengård_to_Båtfors_disch,Båtfors_upper,Rengård_lower	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Rengård_to_Båtfors_spill,Båtfors_upper,Rengård_upper	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Sadva_to_Bergnäs_disch,Bergnäs_upper,Sadva_lower	connection_flow_delay	Base	{"type": "duration", "data": "2D"}
    connection__node__node	Sadva_to_Bergnäs_spill,Bergnäs_upper,Sadva_upper	connection_flow_delay	Base	{"type": "duration", "data": "2D"}
    connection__node__node	Selsfors_to_Kvistforsen_disch,Kvistforsen_upper,Selsfors_lower	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Selsfors_to_Kvistforsen_spill,Kvistforsen_upper,Selsfors_upper	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Slagnäs_to_Bastusel_disch,Bastusel_upper,Slagnäs_lower	connection_flow_delay	Base	{"type": "duration", "data": "4h"}
    connection__node__node	Slagnäs_to_Bastusel_spill,Bastusel_upper,Slagnäs_upper	connection_flow_delay	Base	{"type": "duration", "data": "4h"}
    connection__node__node	Vargfors_to_Rengård_disch,Rengård_upper,Vargfors_lower	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Vargfors_to_Rengård_spill,Rengård_upper,Vargfors_upper	connection_flow_delay	Base	{"type": "duration", "data": "3h"}
    connection__node__node	Bastusel_to_Grytfors_disch,Grytfors_upper,Bastusel_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Bastusel_to_Grytfors_spill,Grytfors_upper,Bastusel_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Bergnäs_to_Slagnäs_disch,Slagnäs_upper,Bergnäs_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Bergnäs_to_Slagnäs_spill,Slagnäs_upper,Bergnäs_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Båtfors_to_Finnfors_disch,Finnfors_upper,Båtfors_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Båtfors_to_Finnfors_spill,Finnfors_upper,Båtfors_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Finnfors_to_Granfors_disch,Granfors_upper,Finnfors_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Finnfors_to_Granfors_spill,Granfors_upper,Finnfors_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Gallejaur_to_Vargfors_disch,Vargfors_upper,Gallejaur_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Gallejaur_to_Vargfors_spill,Vargfors_upper,Gallejaur_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Granfors_to_Krångfors_disch,Krångfors_upper,Granfors_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Granfors_to_Krångfors_spill,Krångfors_upper,Granfors_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Grytfors_to_Gallejaur_disch,Gallejaur_upper,Grytfors_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Grytfors_to_Gallejaur_spill,Gallejaur_upper,Grytfors_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Krångfors_to_Selsfors_disch,Selsfors_upper,Krångfors_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Krångfors_to_Selsfors_spill,Selsfors_upper,Krångfors_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Rebnis_to_Bergnäs_disch,Bergnäs_upper,Rebnis_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Rebnis_to_Bergnäs_spill,Bergnäs_upper,Rebnis_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Rengård_to_Båtfors_disch,Båtfors_upper,Rengård_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Rengård_to_Båtfors_spill,Båtfors_upper,Rengård_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Sadva_to_Bergnäs_disch,Bergnäs_upper,Sadva_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Sadva_to_Bergnäs_spill,Bergnäs_upper,Sadva_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Selsfors_to_Kvistforsen_disch,Kvistforsen_upper,Selsfors_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Selsfors_to_Kvistforsen_spill,Kvistforsen_upper,Selsfors_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Slagnäs_to_Bastusel_disch,Bastusel_upper,Slagnäs_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Slagnäs_to_Bastusel_spill,Bastusel_upper,Slagnäs_upper	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Vargfors_to_Rengård_disch,Rengård_upper,Vargfors_lower	fix_ratio_out_in_connection_flow	Base	1
    connection__node__node	Vargfors_to_Rengård_spill,Rengård_upper,Vargfors_upper	fix_ratio_out_in_connection_flow	Base	1
    
  5. When you’re ready, commit all changes to the database via the main menu (Alt + F).

Using the Importer
Additional Steps for Project Setup
  1. Drag the Data Connection icon dc_icon from the tool bar and drop it into the Design View. This will open the Add Data connection dialogue. Type in ‘Data Connection’ and click on Ok.

  2. To import the model of the planning problem into the Spine database, you need to create an Import specification. Create an Import specification by clicking on the small arrow next to the Importer item (in the Main section of the toolbar) and press New. The Importer specification editor will pop-up.

  3. Type ‘Import Model’ as the name of the specification. Save the specification by using Ctrl+S and close the window.

  4. Drag the newly created Import Model Importer item icon importer_icon from the tool bar and drop it into the Design View. This will open the Add Importer dialogue. Type in ‘Import Model’ and click on Ok.

  5. Connect ‘Data Connection’ with ‘Import Model’ by first clicking on one of the Data Connection’s connectors and then on one of the Importer’s connectors. Connect similarly the importer with the input database. Now the project should look similar to this:

    _images/items_connections.png
  6. From the main menu, select File -> Save project.

Importing the model
  1. Download the data and the accompanying mapping (right click on the links, then select Save link as…).

  2. Add a reference to the file containing the model.

  1. Select the Data Connection item in the Design View to show the Data Connection properties window (on the right side of the window usually).

  2. In Data Connection Properties, click on the plus icon and select the previously downloaded Excel file.

  3. Next, double click on the Import model in the Design view. A window called Select connector for Import Model will pop-up, select Excel and klick OK. Next, still in the Importer specification editor, click the alternatives icon in the top right and import the mappings previously downloaded. Finally, save by clicking Ctrl+S and exit the Importer specification editor.

Executing the workflow

Once the workflow is defined and input data is in place, the project is ready to be executed. Hit the Execute project button execute_project on the tool bar.

You should see ‘Executing All Directed Acyclic Graphs’ printed in the Event log (on the lower left by default). SpineOpt output messages will appear in the Process Log panel in the middle. After some processing, ‘DAG 1/1 completed successfully’ appears and the execution is complete.

Examining the results

Select the output data store and open the Spine DB editor.

_images/case_study_a5_output.png

To checkout the flow on the electricity load (i.e., the total electricity production in the system), go to Object tree, expand the unit object class, and select electricity_load, as illustrated in the picture above. Next, go to Relationship parameter value and double-click the first cell under value. The Parameter value editor will pop up. You should see something like this:

_images/case_study_a5_output_electricity_load_unit_flow.png

Setting up External Tools

This section describes the default Python used by Spine Toolbox and how to change that. Here you can also find the instructions on how to set up Julia and Gams for executing Julia and Gams Tools. To get started with SpineOpt.jl, see How to set up SpineOpt.jl. See also Executing Projects and Execution Modes.

Python

No set up required! Python Tools are executed using the default Python, which depends on how you installed Spine Toolbox. The installation options are:

  1. Using a single-file installation bundle (e.g. spine-toolbox-0.6.0-final.2-x64.exe or newer). You can find this file and all releases from Spine Toolbox releases. The installation bundles are only available for Windows at the moment.

  2. Cloning Spine Toolbox Git repository from https://github.com/Spine-project/Spine-Toolbox. Checkout branch release-0.6 or master and run pip install -r requirements.txt in the repo root.

Tip

You can always see the current Python configured for Spine Toolbox from the Tools page in File->Settings….

Default Python for Spine Toolbox installed using an installation bundle

The default Python is the Python in your PATH environment variable. If Python is not in your PATH, the default Python is an ‘embedded’ Python that is shipped with the installation bundle. The ‘embedded’ Python is located in <install_dir>\tools\python.exe, where <install_dir> is C:\Program Files\Spine Toolbox if you installed Spine Toolbox to the default directory for all users.

Important

If you want access to spinedb_api package from Tools and Consoles in Spine Toolbox, bear in mind that the version of spinedb_api must be compatible with the version of Spine Toolbox you are using! Spine Toolbox v0.6.0 is shipped with spinedb_api v0.12.1. If you want to use the Python in your PATH, you must install the correct version of spinedb_api for this Python manually. The correct version in this case is in the release-0.12 branch of spinedb_api git repo (https://github.com/Spine-project/Spine-Database-API/tree/release-0.12). To avoid this additional step, it is recommended that you use the ‘embedded’ Python interpreter that is shipped with the application. You can set up this Python for Spine Toolbox by opening the Tools page of File->Settings… and replacing the path of the Python Interpreter with <install_dir>\tools\python.exe. The ‘embedded’ Python interpreter has access to `spinedb_api` that is shipped with the application.

Here are the recommended settings

_images/settings_tools_python_installed_version.png

Default Python for Spine Toolbox installed using Git

The default Python is the Python that was used in launching the application (i.e. sys.executable). When you start the app for the first time (or if you clear the path), the path to the default Python is shown as placeholder (gray) text in the line edit like this:

_images/settings_tools_default_python_git_version.png

The default Python has access to the spinedb_api version that was installed with the application (the one in in <python_dir>\lib\site-packages\spinedb_api).

Changing the default Python

If you want to use another Python than the default, you can use existing Pythons in your system or you can download additional Pythons from https://www.python.org/downloads/. You can change the default Python on the Tools page of File->Settings… by clicking the browse button and selecting the Python interpreter (python.exe on Windows) you want. You can use any Python in your system.

Note

Executing Python Tools using the Jupyter Console supports Python versions from 2.7 all the way to newest one. Executing Python Tools without using the Jupyter Console supports even earlier Pythons than 2.7. You can start Spine Toolbox only with Python 3.7 or with 3.8, but you can set up a Jupyter Console in Spine Toolbox that uses e.g. Python 2.7. 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

Executing Julia Tools in Spine Toolbox requires that Julia is installed on your system. Julia downloads are available from https://julialang.org/downloads/. You can see the current Julia on the Tools page in File->Settings…. The default Julia is the Julia in your PATH environment variable. Setting some other Julia to the line edit overrides the Julia in PATH. If you want to use 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 line edit (the one that says Using Julia default project when empty).

If you are trying to execute Julia Tools and you see an error message in Event Log complaining about not finding Julia, you either don’t have a Julia installation in your PATH, or the Julia path in Settings is invalid.

GAMS

Executing Gams Tools and the GDXExporter Project Item 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.

As with Julia, the default Gams is the Gams 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 Gams in your PATH if found. You can also override the default Gams by setting some other gams.exe path to the line edit (e.g. C:\GAMS\win64\28.2\gams.exe).

Important

The bitness (32 or 64bit) of Gams has to match the bitness of the Python interpreter.

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 six dock widgets (Project, Properties, Event Log, Process Log, Julia Console, and Python Console), a tool bar, a Design View, and a menu bar with File, Edit, View, and Help menus. The Project dock widget contains a list of project items and Tool specifications that are available in your project. The Properties dock widget shows the properties of the selected project item. Event Log shows messages depending on what you do in Spine Toolbox. Process Log shows messages from processes that are spawned by the application, i.e. it shows the stdout and stderr streams of GAMS, Julia, Python (if Tools are executed without embedded Julia and Python Consoles, see Settings section), and executable programs. Julia and Python Consoles provide full iJulia and a iPython consoles. If you choose to execute Julia tools in the embedded Julia Console, the Julia code will be included into the Julia Console and executed there. You can interact with the iJulia in the Julia Console like you would with any iJulia you use.

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, and Help menus. In the File menu you can create a new project, open an existing project, save the project, upgrade an old project to modern directory-based project, and 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. Drag & Drop Icon tool bar contains the available project item types. The trash button can be used to remove all items from your project. The Execute icons 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 Drag & Drop Icon tool bar, 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 and/or you can resize the views to fit your needs and display size or resolution.

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 My First Project, and created one project item from each of the seven categories. A Data Store called Database, a Data Connection called Data files, A Tool called Julia model, a View called View, an Importer called Importer, an Exporter called Exporter, and a Manipulator called Combiner. The project items are also listed in the Project dock widget.

_images/main_window_my_first_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 on 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 it’s own directory in the <proj_dir>/.spinetoolbox/items/ directory. You can quickly open the project item directory in a file explorer by clicking on the folder-open button located in the lower right corner of each Properties form.

Project Item Descriptions

The following items are currently available:

Data Store 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 Connection 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 while data files reside in the item’s own data directory.

Tool 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 or executable as well. A tool is specified by its specification.

Gimlet gimlet

While being able to run most scripts and copyable executables, Tool cannot handle system commands or executables meant to run from system’s path. This is a job for Gimlet. A Gimlet can execute an arbitrary system command with given command line arguments, input files and work directory.

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

View view

A View item is meant for inspecting data from multiple sources using the Spine db editor. Note that the data is opened in read-only mode so modifications are not possible from the View item.

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

Exporter exporter

Exporter outputs database data into tabulated file formats that can be consumed by Tool or used e.g. by external software for analysis. See Importing and exporting data for more information.

GdxExporter gdx-exporter

Note

GdxExporter is pending for removal and its use in new projects is discouraged. Use Exporter instead.

This item exports databases contained in a Data Store into .gdx format for GAMS Tools. See Importing and exporting data for more information.

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). Then select, whether you want the Tool specification to be executed in the work directory or in its source directory (See Terminology section). 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 file 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.

Additional source files is a list of files that the main program requires in order to run. You can add individual files or whole directories at once to this list.

Tip

You can also drag&drop a directory from your operating systems File Explorer into the Additional source files list.

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 of the Tool’s project 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 to 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 main program file 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",
    "description": "",
    "tooltype": "julia",
    "execute_in_work": true,
    "includes": [
        "script.jl"
    ],
    "inputfiles": [],
    "inputfiles_opt": [],
    "outputfiles": [],
    "cmdline_args": ""
}

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. Execution happens by pressing the play-all (Execute project) or the play-selected (Execute selection) buttons in the main window tool bar. 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.

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

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 DAG 1 above, 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.

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 File Data Connection and Julia Model Tool connected to each other.

_images/execution_data_connection_selected.png

In ths example, Data File has a single file reference data.csv. Data Connections make their files visible to direct successors and thus the connection between Data File 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 a 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 File. Results… button opens the Tool’s result archive directory in system’s file browser (all Tools have their own result directory). 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.

When you click on the play-all button, the execution starts from the Data File 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 File 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 File) 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).

Execution Modes

You can execute Python or Julia Tools in the Jupyter Console or as in the shell. Gams Tools are only executed as in the shell.

Python

Shell execution (default)

On Tools page in File->Settings…, check the Run Python Tools in a subprocess radiobutton (release-0.6) or uncheck the Jupyter Console check box (master). This is the default execution mode for Python Tools.

Jupyter Console / Python Console execution

If you want to use the embedded Python Console (Jupyter Console). Check the Run Python Tools in embedded console radiobutton (release-0.6) or check the Jupyter Console check box (master). There is an extra step involved since the Jupyter Console requires a couple of extra packages (ipykernel and its dependencies) to be installed on the selected Python. In addition, kernel specifications for the selected Python need to be installed beforehand. Spine Toolbox can install these for you, from the Kernel Spec Editor widget that you can open from the Tools page in File->Settings.. by clicking the Kernel Spec Editor button. In the Kernel Spec Editor, give the spec a name and click Make kernel specification button.

Note

You can install Python kernel specifications manually and Spine Toolbox will find them. You can select the kernel spec used in the Jupyter Console from the drop-down menu Select Python kernel spec….

Julia

Shell execution (default)

On Tools page in File->Settings…, check the Run Julia Tools in a subprocess radiobutton (release-0.6) or uncheck the Jupyter Console check box (master). This is the default execution mode for Julia Tools.

Jupyter Console / Julia Console execution

Like the Python Console, Julia Console requires some extra setting up. The Julia Console requires a couple of additional packages (IJulia, etc.) to be installed and built. Spine Toolbox can set this up for you automatically. Just click the Kernel spec Editor button, give the spec a name and click Make kernel specification button.

Note

You can install Julia kernel specifications manually and Spine Toolbox will find them. You can select the kernel spec used in the Jupyter Console from the drop-down menu Select Julia kernel spec….

Settings

Note

The images and some of the text are outdated. See tooltips in the app for up-to-date information.

You can open Spine Toolbox settings from the main window menu File->Settings…, or by pressing F1. Settings are categorized into four tabs; General, Project, Tools, and View. In addition to application settings, each Project item has user adjustable properties (See Project Items)

General settings

_images/settings_general.png

The General tab contains the general application settings.

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

  • Show confirm exit prompt If checked, confirm exit prompt is shown. If unchecked, application exits without prompt.

  • Save project at exit Unchecked: Does not save project and does not show message box. Partially checked: Shows message box (default). Checked: Saves project and does not show message box.

  • Show date and time in Event Log messages If checked, every Event Log message is prepended with a date and time ‘tag’.

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

  • Work directory Directory where processing the Tool takes place. Default place (if left empty) is the /work subdirectory of Spine Toolbox install directory. You can change this directory. Make sure to clean up the directory every now and then.

  • Smooth zoom Controls the way zooming (by using the mouse wheel) behaves in Design View and in Spine database editor. Controls if the zoom in/out is continuous or discrete. On older computers, smooth zoom is not recommended (because it may be slower).

  • Curved links Controls the look of the arrows (connections) on Design View.

  • Design View background Choosing grid shows a black grid as the Design View background. Choosing Solid and then clicking on the square next to it let’s you choose the background color.

  • Data flow animation speed This slider controls the speed of the ‘arrow’ animation on Design View when execution is about to start.

Project settings

_images/settings_project.png

These settings affect the project that is currently open. To save the project to a new directory use the File->Save project as... menu item. Or you can simply copy the project directory anywhere on your file system.

  • Name The default name for new projects is the name of the project directory. You can change the project name here.

  • Description You can type a description for your project here.

Tools settings

_images/settings_tools.png
  • GAMS executable Path to GAMS executable you wish to use to execute GdxExporter project items and Tool project items that use a GAMS Tool specification. See Setting up External Tools.

  • Julia executable Path to Julia executable you wish to use to execute Tool project items that use a Julia Tool specification. See Setting up External Tools.

  • Julia home project Set the Julia home project here.

  • Use embedded Julia Console Check this box to execute Tool project items that use a Julia Tool specification in the built-in Julia Console. If you leave this un-checked, Julia Tool specifications will be executed as in the shell. I.e on Windows this would be the equivalent to running command julia.exe example_script.jl in the command prompt. If you decide to use the embedded Julia Console, the example_script.jl is included into the console and executed there.

  • Python interpreter Path to Python executable you wish to use to execute Tool project items that use a Python Tool specification. See Setting up External Tools.

  • Use embedded Python Console Check this box to execute Python Tool specifications in the embedded Python Console. If you un-check this box, Python Tool specifications will be executed as in the shell. I.e on Windows this would be the equivalent to running command python.exe script.py in the command prompt. If you decide to use the embedded Python Console, script.py is executed there instead.

View settings

_images/settings_view.png
  • Commit session when view is closed This checkbox controls what happens when you close the Spine 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.

  • Sticky selection in object tree Controls how selecting items in Spine database editor’s Object tree using the left mouse button works. If unchecked, single selection is enabled and pressing the Ctrl-button down enables multiple selection. If checked, Multiple selection is enabled and pressing the Ctrl-button down enables single selection.

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.

Note

If you are looking for information on project item properties, see Project Items.

Welcome to Spine database editor’s User Guide!

Spine database editor is a dedicated component of Spine Toolbox, that you can use to visualize and edit data in one or more Spine databases.

Getting started

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.

To open multiple databases in Spine database editor:

  1. Repeat steps 1 to 3 above for each database.

  2. Create a View project item.

  3. Connect each Data Store item to the View item.

  4. Select the View item.

  5. Press Open editor in View Properties.

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 for a given class 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/Scenario tree: it presents scenarios and alternatives defined in the databases.

  • Parameter tag: it presents parameter tags defined in the databases.

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 descentants 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 ocurrence 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 prunned items, display the context menu, hover Restore and select the items you want to restore from the popup menu. To restore all prunned 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’ lenght, 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

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

To filter parameter definitions and values by certain parameter tags, select those tags in Parameter tag toolbar.

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 viceversa, 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 and scenarios from all databases under Alternative/Scenario tree:

_images/alternative_scenario_tree.png

To view the alternatives and scenarios from each database, expand the root item for that database. To view all alternatives, expand the alternative item. To view all scenarios, expand the scenario item. To view the alternatives for a particular scenario, expand the scenario_alternative item under 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 parameter tags

You can find parameter tags from all databases under Parameter tag:

_images/parameter_tag.png

To view the tags from each database, expand the root item for that database.

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, adn 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 and scenarios

From Alternative/Scenario tree

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

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

To add an alternative for a particular scenario, drag the alternative item and drop it over the scenario_alternative list under the corresponding scenario. The position where you drop it determines the alternative’s rank within the scenario.

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

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. To add a new alternative, enter a name in the last cell of the alternative header.

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

To add a new parameter tag, go to Parameter tag and select the last item under the appropriate database, and enter the tag’s name.

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 and 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 rename an alternative, just edit the proper cell in the alternative header.

From Alternative/Scenario tree

To rename a scenario or alternative, just edit the appropriate item in Alternative/Scenario tree. To change scenario alternative ranks, just drag and drop the items under scenario_alternatives.

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 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 and 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 chose Remove from the context menu. To remove alternatives, just edit the proper cells in the alternative header, right-click on the selection and chose Remove from the context menu.

From Alternative/Scenario tree

To remove a scenario or alternative, just select the correspoding items in Alternative/Scenario tree, right-click on the selection and chose Remove from the context menu.

Removing tools and features

To remove a feature, tool, or method, just select the correspoding items in Tool/Feature tree, right-click on the selection and chose Remove from the context menu.

Removing parameter value lists

To remove a parameter value list or any of its values, just select the correspoding items in Parameter value list, right-click on the selection and chose Remove 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 Undo and Redo actions from the Edit 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.

_images/plotting_popup_menu_plot_in_window.png _images/plotting_window_added_plot.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 is available from a right click popup menu or by double clicking a parameter value in one of the Spine database editors.

Choosing value type

_images/value_editor_parameter_type.png

The combo box at the top of the editor window allows changing the type of the current value.

Plain values

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

_images/value_editor_plain.png

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, to add/insert/remove rows or columns (effectively changing map’s dimensions), or to trim empty columns from the right hand side.

Copying and pasting data between cells and external programs works using the usual Ctrl-C and Ctrl-V keyboard shortcuts.

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_variable.png _images/value_editor_time_series_fixed.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 the input field pops 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

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 Import Editor window in which the mappings from source data to Spine database entities are set up. The editor window can be accessed by the Import Editor… button in Importer’s Properties dock. Note, that you have to select one of the files in the Source files list before clicking the button.

_images/importer_properties.png

The Import Editor windows is divided into two parts: Sources shows all the ‘sheets’ contained in the file, some options for reading the file correctly, and a preview table to visualize and configure how the data on the selected sheet would be mapped. Mappings, on the other hand, shows the actual importing settings, the mappings from the input data to database entities.

_images/import_editor_window.png

The options in the Mappings part declare if the currently selected sheet will be imported as an object or relationship and what type of parameters, if any, the sheet contains. The table can be used to configure how the input data is interpreted: which row or column contains the entity class names, parameter values, time stamps and so on.

_images/import_editor_mapping_options.png

It might be helpful to fill in the mapping options using the preview table in the Sources part. Right clicking on the table cells shows a popup menu that lets one to configure how the rows and colunms are read upon importing.

_images/import_editor_preview_table_mapping_menu.png

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. It is possible to control what type of data each column (and, sometimes, each row) contains from the preview table. Clicking the data type indicator button on column headers pops up a menu with a selection of available data types. Right clicking the column header also gives the opportunity to change the data type of all columns at once.

_images/import_editor_column_data_type_menu.png

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 saves its settings or export mappings as a specification that can be reused by other exporters or even 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.

Databases available for export from connected project items such as Data stores are listed in separate boxes below the Specification combobox. An output filename is required for each database.

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

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

_images/exporter_mappings_dock.png

Specification’s mappings are listed in the Mappings dock shown above. 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. Use the Toggle enabled button to toggle the enabled state of all mappings at once.

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

_images/exporter_mapping_options_dock.png _images/exporter_mapping_specification_dock.png

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. Mapping specification, on the other hand, contains a table which defines the structure of the mapping’s output tables.

What database items the mapping outputs is chosen using the Item type combobox in Mapping options dock. For instance, the Object classes option outputs object classes, objects and, optionally, object parameters and related items while the Relationship classes option outputs relationship classes and relationships. 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. 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.

The contents of the table on the Mapping specification dock 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 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 to filter what gets outputted. See Basic regular expression for filtering.

_images/exporter_preview_docks.png

A preview of what will be written to the output is available in the preview dock widgets. 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. The colors on the table correspond to the colors in Mapping specification dock.

Basic regular expressions for filtering

The Filter field in Mapping specification accepts regular expressions to filter what data gets outputted by that mapping item. Below are examples on how to create some basic filters.

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. ^(?!node). would exclude all items names of which start with ‘node’.

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

Note

Currently only sqlite is supported.

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.

Note

The bitness (32 or 64bit) of GAMS must match the bitness of the Python interpreter.

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.

Exporting to GAMS with GdxExporter

Note

GdxExporter is pending for removal and its use in new projects is discouraged. Use Exporter instead.

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.

Note

The bitness (32 or 64bit) of GAMS has to match the bitness of the Python interpreter.

Databases can be exported to GAMS .gdx files by the GdxExporter project item. When a project is executed, GdxExporter writes its output files to its data folder and forwards file paths to project items downstream. If a Tool is to use such a file, remember to add the file as one of the Tool specification’s input files!

The mapping between entities in a Spine database and GAMS is as follows:

Database entity

GAMS entity

Object class

Universal set (or domain)

Object

Universal set member

Object parameter

Parameter

Relationship class

Subset of universal sets

Relationship

Subset member

Relationship parameter

Parameter

Note

Currently, it is not possible to use subsets (relationship classes) as dimensions for other subsets due to technical limitations. For example, if there is a domain A(*) and a subset foo(A), a subset of foo has to be expressed as bar(A) instead of bar(foo).

It is also possible to designate a single object class as a Global parameter. The parameters of the objects of that class will be exported as GAMS scalars.

Some GAMS models need their data to be in a specific order in the .gdx. This is not directly supported by the database. Rather, user has to specify the desired exporting order using the GdxExporter item’s settings.

GdxExporter Project Item

The image below shows the properties dock of GdxExporter with two Data Sources connected to it.

_images/gdx_exporter_properties.png

For each connected Data Store a box with the database’s URL and export file name field is shown on the dock. The Settings… buttons open Gdx Export settings windows to allow editing database specific export parameters such as the order in which entities are exported from the database.

_images/gdx_export_settings_window.png

The Gdx Export settings window (see above) contains a Sets list which shows all GAMS sets (gray background) and subsets that are available in the database. The sets are exported in the order they are shown in the list. The Move Up and Move Down buttons can be used to move the selected set around. Note that you cannot mix sets with subsets so all sets always get exported before the subsets.

The checkbox next to the set name is used to control which sets are actually exported. Note that it is not possible to change this setting for certain sets. Global parameters domain is never exported, only its parameters which become GAMS scalars. Further, sets created for Indexed paramaters are always exported.

The Set Contents box lists the members of the selected set or subset. Their order of export can be changed the same way as with sets by Move Up and Move Down. The Alphabetic button sorts the members alphabetically.

Time series and time patterns cannot be exported as-is. They need to be tied up to a GAMS set. This can be achieved from the window that opens from the Indexed parameters… button. See the Exporting time series and patterns section below for more information.

Finally, one of the sets can be designated as the global parameter set. This is achieved by choosing the set’s name in the Global parameters domain box. Note that this set is not exported, only its parameters are. They end up as GAMS scalars.

Exporting time series and patterns

Since GAMS has no notion of time series or time patterns these types need special handling when exported to a .gdx file. Namely, the time stamps or time periods (i.e. parameter indexes) need be available as GAMS sets in the exported file. It is possible to use an existing set or create a new one for this purpose. The functionality is available in Gdx Parameter Indexing Settings window accessible from the Indexed Parameters… button.

_images/gdx_export_parameter_indexing_window_using_existing_domain.png

The above figure shows the indexing settings when an existing GAMS set is used to replace the original time stamps of a time series in a parameter called ‘size’. The choice between using an existing set or creating a new one can be changed by the Use existing domain and Create new index domain radio buttons. When using an existing set it is selected by the combobox. In the above figure, ALL TS set is used for indexing.

In case of existing set it is possible that not all the set’s contents are used for indexing. The table occupying the right side of the above figure shows which of the set’s keys index which parameter values. The first column contains the keys of the currently selected set whereas the other columns contain the parameter’s values, one column for each object that has the parameter. Selecting and deselecting rows in the table changes the indexing as only the keys on selected rows are used to index the parameter. Shift, ctrl and ctrl-A help in manual selection. If the selected indexes have certain pattern it might be useful to utilize the Label picking expression field which selects the set keys using a Python expression returning a boolean value. Some examples:

Expression

Effect

i == 3

Select the third row only

i % 2 == 0

Select even rows

(i + 1) % 2 == 0 and i != 9

Select odd rows except row 9

The Indexing domains list allows to shuffle the order of the parameter’s dimensions. The bold dimension is the new dimension that is added to the parameter. It can be moved around by the Move Left and Move Right buttons.

_images/gdx_export_parameter_indexing_window_using_new_domain.png

It is possible to create a new indexing set by choosing Create new index domain as shown in the figure above. Domain name is mandatory for the new domain. A Description can also be provided but it is optional. There are two options to generate the index keys: extract the time stamps or time periods from the parameter itself or generate them using a Python expression. The Extract index from parameter button can be used to extract the keys from the parameter. The Generator expression field, on the other hand, is used to generate index keys for the new set. The expression should return Python object that is convertible to string. Below are some example expressions:

Expression

Keys

i

1, 2, 3,…

f"{i - 1:04}"

0000, 0001, 0002,…

f"T{i:03}"

T001, T002, T003,…

Spine datapackage editor

Note

This section is a work in progress.

This section describes the Spine datapackage editor, used to interact with tabular data and export it into Spine format.

To open the Spine datapackage editor, select a Data Connection with CSV files in it, and press the Datapackage button in its Properties:

_images/pypsa_dc.png _images/spine_datapackage_editor_pypsa.png

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.

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

Dependencies

Spine Toolbox requires Python 3.7 or Python 3.8. Python 3.9 is not supported yet.

The dependencies have been split to required packages and development packages. The required packages must be installed for the application to start. The development packages contain tools that are recommended for developers. If you want to deploy the application yourself by using the provided cx_Freeze_setup.py file, you need to install the cx_Freeze package (v6.6 or newer recommended).

At the moment, Spine Toolbox depends on four main packages (spinetoolbox, spine-engine, spine-items, and spinedb-api) developed in Spine project. For version number limitations, please see requirements.txt and setup.py files in spinetoolbox, spine-engine, spine-items, and spinedb-api packages

Dependencies by package

spinetoolbox

Package name

License

spinedb-api

LGPL

spine_engine

LGPL

spine_items*

LGPL

pyside2

LGPL

datapackage

MIT

jupyter-client

BSD

qtconsole

BSD

sqlalchemy

MIT

numpy

BSD

matplotlib

BSD

scipy

BSD

networkx

BSD

cx_Oracle

BSD

pandas

BSD

pymysql

MIT

pyodbc

MIT

psycopg2

LGPL

jill

MIT

* spine-items is not a ‘hard’ requirement of Spine Toolbox. The app does start without spine-items but the features in that case are quite limited.

spinedb-api

Package name

License

sqlalchemy

MIT

alembic

MIT

faker

MIT

python-dateutil

PSF

numpy

BSD

openpyxl

MIT/Expat

gdx2py

MIT

ijson

BSD

spine-engine

Package name

License

spinedb-api

LGPL

dagster

Apache-2.0

sqlalchemy

MIT

numpy

BSD

datapackage

MIT

spine-items

Package name

License

spinetoolbox

LGPL

spinedb-api

LGPL

spine-engine

LGPL

Development packages

Below is a list of development packages in dev-requirements.txt. Sphinx and sphinx_rtd_theme packages are needed for building the user guide. Black is used for code formatting while pylint does linting. Pre-commit hook enables automatic code formatting at git commit.

Package name

License

black

MIT

pre-commit

MIT

pyYAML

GPL

pylint

GPL

sphinx

BSD

sphinx_rtd_theme

MIT

recommonmark

MIT

sphinx-autoapi

MIT

Contribution Guide for Spine Toolbox

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 subjet 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 (insipred 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 doesn’t 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

GdxExporter

n/a

File URLs

Gimlet

n/a

Resources from predecessor

Importer

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

GdxExporter

Database URL

n/a

Gimlet

5

File URLs, database URLs

Database URLs

Importer

6

File URLs

Database URL

Tool

7

File URLs, database URLs

Database URLs

View

Database URLs

n/a

5

Gimlet’s resources can be passed to the command as command line arguments but are otherwise ignored.

6

Importer requires a database URL from its successor for writing the mapped data. This can be provided by a Data Store.

7

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 (or any Python package) to The Python Package Index (PyPI). For a complete tutorial, see Packaging Python Projects.

First, make sure you have all the developer packages installed by calling

$ pip install --upgrade -r dev-requirements.txt

inside your Python environment.

Building

Build a source distribution archive and a wheel package with

$ python setup.py sdist bdist_wheel

This will create distribution files under the ‘dist’ directory. Please remember to clean up between subsequent builds:

$ python setup.py clean --all

Before uploading, tag the code revision with

$ git tag --message "Version x.y.z" <version number>

where the version number is a string given by spinetoolbox.__version__.

Uploading

Before making a real upload, please test using TestPyPI which is a separate instance from the real index server. Once a version has been uploaded to PyPI, it cannot be reverted or modified.

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.

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

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.

author
  1. Savolainen (VTT)

date

24.9.2019

Submodules
spinetoolbox.mvcmodels.array_model

Contains model for the Array editor widget.

author
  1. Soininen (VTT)

date

14.6.2019

Module Contents
Classes

ArrayModel

Model for the Array parameter_value type.

class spinetoolbox.mvcmodels.array_model.ArrayModel(parent)[source]

Bases: PySide2.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(self)[source]

Returns the array modeled by this model.

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

Returns 2.

_convert_to_data_type(self, 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(self, index, role=Qt.DisplayRole)[source]

Returns model’s data for given role.

flags(self, index)[source]

Returns table cell’s flags.

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

Returns header data.

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

Inserts rows to the array.

is_expanse_row(self, 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(self, row, count, parent=QModelIndex())[source]

Removes rows from the array.

reset(self, value)[source]

Resets the model to a new array.

Parameters

value (Array) – a new array to model

rowCount(self, parent=QModelIndex())[source]

Returns the length of the array.

Note: returns 1 even if the array is empty.

set_array_type(self, new_type)[source]

Changes the data type of array’s elements.

Parameters

new_type (Type) – new element type

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

Sets the value at given index.

spinetoolbox.mvcmodels.compound_table_model

Models that vertically concatenate two or more table models.

authors
  1. Marin (KTH)

date

9.10.2019

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) – the parent object

refreshed[source]
map_to_sub(self, 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(self, 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(self, row)[source]

Returns the item at given row.

Parameters

row (int) –

Returns

object

sub_model_at_row(self, row)[source]

Returns the submodel corresponding to the given row in the compound model.

Parameters

row (int) –

Returns

MinimalTableModel

refresh(self)[source]

Refreshes the layout by computing a new row map.

_do_refresh(self)[source]

Recomputes the row and inverse row maps.

_append_row_map(self, 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(self, 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(self, 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(self, parent)[source]

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

fetchMore(self, parent)[source]

Fetches the next sub model and increments the fetched counter.

flags(self, index)[source]

Return index flags.

data(self, index, role=Qt.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(self, parent=QModelIndex())[source]

Returns the sum of rows in all models.

batch_set_data(self, 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(self, 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(self, 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) – the parent object

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

Returns an empty model.

init_model(self)[source]

Initializes the compound model. Basically populates the sub_models list attribute with the result of _create_single_models and _create_empty_model.

_connect_single_model(self, model)[source]

Connects signals so changes in the submodels are acknowledge by the compound.

_recompute_empty_row_map(self)[source]

Recomputes the part of the row map corresponding to the empty model.

_handle_empty_rows_removed(self, parent, empty_first, empty_last)[source]

Runs when rows are removed from the empty model. Updates row_map, then emits rowsRemoved so the removed rows are no longer visible.

_handle_empty_rows_inserted(self, 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(self, model)[source]

Runs when given model is about to reset.

_handle_single_model_reset(self, model)[source]

Runs when given model is reset.

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

Clears the model.

spinetoolbox.mvcmodels.empty_row_model

Contains a table model with an empty last row.

authors
  1. Marin (KTH)

date

20.5.2018

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

Return True if the model hasn’t been fetched.

fetchMore(self, parent)[source]

Fetch data and use it to reset the model.

flags(self, index)[source]

Return default flags except if forcing defaults.

set_default_row(self, **kwargs)[source]

Set default row data.

clear(self)[source]

Clear all data in model.

reset_model(self, main_data=None)[source]

Reset model.

_handle_data_changed(self, 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(self, row, count, parent=QModelIndex())[source]

Don’t remove the last empty row.

_handle_rows_inserted(self, parent, first, last)[source]

Handle rowsInserted signal.

set_rows_to_default(self, first, last=None)[source]

Set default data in newly inserted rows.

spinetoolbox.mvcmodels.filter_checkbox_list_model

Provides FilterCheckboxListModel for FilterWidget.

author
  1. Vennström (VTT)

date

1.11.2018

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: PySide2.QtCore.QAbstractListModel

Init class.

Parameters

parent (QWidget) –

_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]
property _show_empty(self)[source]
property _show_add_to_selection(self)[source]
reset_selection(self)[source]
_handle_select_all_clicked(self)[source]
_check_all_selected(self)[source]
rowCount(self, parent=QModelIndex())[source]
data(self, index, role=Qt.DisplayRole)[source]
_handle_index_clicked(self, index)[source]
set_list(self, data, all_selected=True)[source]
set_selected(self, selected, select_empty=None)[source]
get_selected(self)[source]
get_not_selected(self)[source]
set_filter(self, filter_expression)[source]
search_filter_expression(self, item)[source]
set_base_filter(self, condition)[source]

Sets the base filter. The other filter, the one that works by typing in the search bar, should be applied on top of this base filter.

Parameters

condition (function) – Filter acceptance condition.

apply_filter(self)[source]
_remove_and_add_filtered(self)[source]
_remove_and_replace_filtered(self)[source]
remove_filter(self)[source]
_do_add_items(self, data)[source]
add_items(self, data, selected=None)[source]
remove_items(self, data)[source]
class spinetoolbox.mvcmodels.filter_checkbox_list_model.LazyFilterCheckboxListModel(parent, source_model, show_empty=True)[source]

Bases: SimpleFilterCheckboxListModel

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

Init class.

Parameters
canFetchMore(self, parent)[source]
fetchMore(self, parent)[source]
_do_add_items(self, 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(self, index, role=Qt.DisplayRole)[source]
search_filter_expression(self, item)[source]
spinetoolbox.mvcmodels.filter_execution_model

Contains FilterExecutionModel.

author
  1. Marin (KTH)

date

26.11.2020

Module Contents
Classes

FilterExecutionModel

class spinetoolbox.mvcmodels.filter_execution_model.FilterExecutionModel[source]

Bases: PySide2.QtCore.QAbstractItemModel

_item[source]
reset_model(self, item)[source]
index(self, row, column, parent=QModelIndex())[source]
parent(self, index)[source]
columnCount(self, parent=QModelIndex())[source]
rowCount(self, parent=QModelIndex())[source]
headerData(self, section, orientation, role=Qt.DisplayRole)[source]
data(self, index, role=Qt.DisplayRole)[source]
get_log_document(self, filter_id)[source]
get_console(self, filter_id)[source]
spinetoolbox.mvcmodels.indexed_value_table_model

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

authors
  1. Soininen (VTT)

date

18.6.2019

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: PySide2.QtCore.QAbstractTableModel

A base class for time pattern and time series models.

Parameters
  • value (IndexedValue) – a parameter_value

  • parent (QObject) – parent object

columnCount(self, parent=QModelIndex())[source]

Returns the number of columns which is two.

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

Returns the data at index for given role.

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

Returns a header.

is_expanse_row(self, 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(self, value)[source]

Resets the model.

rowCount(self, parent=QModelIndex())[source]

Returns the number of rows.

setHeaderData(self, section, orientation, value, role=Qt.EditRole)[source]
property value(self)[source]

Returns the parameter_value associated with the model.

spinetoolbox.mvcmodels.map_model

A model for maps, used by the parameter_value editors.

authors
  1. Soininen (VTT)

date

11.2.2020

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.

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: PySide2.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(self)[source]

Appends a new column to the right.

clear(self, indexes)[source]

Clears table cells.

Parameters

indexes (list of QModelIndex) – indexes to clear

columnCount(self, index=QModelIndex())[source]

Returns the number of columns in this model.

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

Returns the data associated with the given role.

flags(self, index)[source]

Returns flags at index.

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

Returns row numbers for vertical headers and column titles for horizontal ones.

insertColumns(self, 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(self, 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_in_expanse(self, 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(self, 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(self, 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(self, 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(self, 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(self, map_value)[source]

Resets the model to given map_value.

rowCount(self, parent=QModelIndex())[source]

Returns the number of rows.

set_box(self, 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(self, index, value, role=Qt.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(self, section, orientation, value, role=Qt.EditRole)[source]
trim_columns(self)[source]

Removes empty columns from the right.

value(self)[source]

Returns the Map.

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

Contains a minimal table model.

authors
  1. Marin (KTH)

date

20.5.2018

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: PySide2.QtCore.QAbstractTableModel

Table model for outlining simple tabular data.

Parameters

parent (QObject) – the parent object

clear(self)[source]

Clear all data in model.

flags(self, index)[source]

Return index flags.

canFetchMore(self, parent)[source]

Return True if the model hasn’t been fetched.

fetchMore(self, parent)[source]

Fetch data and use it to reset the model.

rowCount(self, parent=QModelIndex())[source]

Number of rows in the model.

columnCount(self, parent=QModelIndex())[source]

Number of columns in the model.

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

Returns headers.

set_horizontal_header_labels(self, labels)[source]

Set horizontal header labels.

insert_horizontal_header_labels(self, section, labels)[source]

Insert horizontal header labels at the given section.

horizontal_header_labels(self)[source]
setHeaderData(self, section, orientation, value, role=Qt.EditRole)[source]

Sets the data for the given role and section in the header with the specified orientation to the value supplied.

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

Set data in model.

batch_set_data(self, indexes, data)[source]

Batch set data for indexes.

insertRows(self, 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(self, 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(self, 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(self, 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(self, main_data=None)[source]

Reset model.

spinetoolbox.mvcmodels.minimal_tree_model

Models to represent items in a tree.

authors
  1. Vennström (VTT), M. Marin (KTH)

date

11.3.2019

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

Bases: PySide2.QtCore.QObject

A tree item that can fetch its children.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

fully_fetched[source]
has_children(self)[source]

Returns whether or not this item has or could have children.

_handle_fully_fetched(self)[source]

Handles fully_fetched.

property model(self)[source]
property child_item_class(self)[source]

Returns the type of child items. Reimplement in subclasses to return something more meaningful.

property children(self)[source]
property parent_item(self)[source]
child(self, row)[source]

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

last_child(self)[source]

Returns the last child.

child_count(self)[source]

Returns the number of children.

child_number(self)[source]

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

find_children(self, cond=lambda child: ...)[source]

Returns children that meet condition expressed as a lambda function.

find_child(self, cond=lambda child: ...)[source]

Returns first child that meet condition expressed as a lambda function or None.

next_sibling(self)[source]

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

previous_sibling(self)[source]

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

index(self)[source]
finalize(self)[source]
_do_finalize(self)[source]

Do some final initialization after setting the parent.

insert_children(self, 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

append_children(self, children)[source]

Append children at the end.

remove_children(self, 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

clear_children(self)[source]

Clear children list.

flags(self, column)[source]

Enables the item and makes it selectable.

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

Returns data for given column and role.

can_fetch_more(self)[source]

Returns whether or not this item can fetch more.

fetch_more(self)[source]

Fetches more children.

property display_data(self)[source]
property edit_data(self)[source]
abstract set_data(self, 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: PySide2.QtCore.QAbstractItemModel

Base class for all tree models.

Init class.

Parameters

parent (SpineDBEditor) –

visit_all(self, 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 from that view. So for example, if a tree item is not expanded then we don’t yield its children.

Yields

TreeItem

item_from_index(self, index)[source]

Return the item corresponding to the given index.

index_from_item(self, item)[source]

Return a model index corresponding to the given item.

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

Returns the index of the item in the model specified by the given row, column and parent index.

parent(self, index)[source]

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

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

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

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

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

flags(self, index)[source]

Returns the item flags for the given index.

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

Contains a class for storing project items.

authors
  1. Savolainen (VTT)

date

23.1.2018

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: PySide2.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(self)[source]

Returns the root item.

connect_to_project(self, project)[source]

Connects the model to a project.

Parameters

project (SpineToolboxProject) – project to connect to

_add_leaf_item(self, name)[source]

Adds a leaf item to the model

Parameters

name (str) – project item’s name

_remove_leaf_item(self, name)[source]

Removes a leaf item from the model.

Parameters

name (str) – project item’s name

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

Returns model column count which is always 1.

flags(self, index)[source]

Returns flags for the item at given index

Parameters

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

parent(self, 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(self, 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(self, 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(self, 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(self, 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(self, 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(self, 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(self, 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(self, 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(self, 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

set_leaf_item_name(self, index, name)[source]

Changes the name of the leaf item at given index.

Parameters
  • index (QModelIndex) – Tree item index

  • name (str) – New project item name

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

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

Returns

Number of items

Return type

int

item_names(self)[source]

Returns all leaf item names in a list.

Returns

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

Return type

obj

items_per_category(self)[source]

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

Returns

dict(QModelIndex,list(LeafProjectTreeItem))

leaf_indexes(self)[source]

Yields leaf indexes.

remove_leaves(self)[source]
spinetoolbox.mvcmodels.project_item_specification_models

Contains a class for storing Tool specifications.

authors
  1. Savolainen (VTT)

date

23.1.2018

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: PySide2.QtCore.QAbstractListModel

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

add_specification(self, name)[source]

Adds a specification to the model.

Parameters

name (str) – specification’s name

remove_specification(self, name)[source]

Removes a specification from the model

Parameters

name (str) – specification’s name

replace_specification(self, old_name, new_name)[source]

Replaces a specification.

Parameters
  • old_name (str) – previous name

  • new_name (str) – new name

connect_to_project(self, project)[source]

Connects the model to a project.

Parameters

project (SpineToolboxProject) – project to connect to

clear(self)[source]
rowCount(self, 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(self, 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(self, index)[source]

Returns enabled flags for the given index.

Parameters

index (QModelIndex) – Index of spec

insertRow(self, 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(self, 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(self, row)[source]

Returns spec specification on given row.

Parameters

row (int) – Row of spec specification

Returns

ProjectItemSpecification from specification list or None if given row is zero

specification_row(self, name)[source]

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

specification_index(self, 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: PySide2.QtCore.QSortFilterProxyModel

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

Yields all specs.

spinetoolbox.mvcmodels.resource_filter_model

Contains ResourceFilterModel.

author
  1. Marin (KTH)

date

26.11.2020

Module Contents
Classes

ResourceFilterModel

param link

link whose resources to model

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

Bases: PySide2.QtGui.QStandardItemModel

Parameters
  • link (Link) – link whose resources to model

  • undo_stack (QUndoStack) – an undo stack

  • logger (LoggerInterface) – a logger

tree_built[source]
_SELECT_ALL = Select all[source]
_FILTER_TYPES[source]
_FILTER_TYPE_TO_TEXT[source]
_ID_ROLE[source]
property connection(self)[source]
build_tree(self)[source]

Rebuilds model’s contents.

setData(self, index, value, role=Qt.EditRole)[source]
_change_filter_checked_state(self, 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(self, resource, filter_type, online)[source]

Sets the given filters online or offline.

Parameters
  • resource (str) – Resource label

  • filter_type (str) – Either SCENARIO_FILTER_TYPE or TOOL_FILTER_TYPE, for now.

  • online (dict) – mapping from scenario/tool id to online flag

_find_filter_type_item(self, 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(self, 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

author
  1. Marin (KTH)

date

23.3.2020

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

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

authors
  1. Soininen (VTT)

date

4.7.2019

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

Returns flags at index.

insertRows(self, 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(self, 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(self, index, value, role=Qt.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(self, 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.

authors
  1. Soininen (VTT)

date

4.7.2019

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

flags(self, index)[source]

Returns flags at index.

property indexes(self)[source]

Returns the time stamps as an array.

insertRows(self, 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(self, 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(self, value)[source]

Resets the model with new time series data.

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

Sets the ignore_year option of the time series.

set_repeat(self, repeat)[source]

Sets the repeat option of the time series.

set_resolution(self, resolution)[source]

Sets the resolution.

set_start(self, start)[source]

Sets the start datetime.

property values(self)[source]

Returns the values of the time series as an array.

spinetoolbox.mvcmodels.time_series_model_variable_resolution

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

authors
  1. Soininen (VTT)

date

5.7.2019

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

flags(self, index)[source]

Returns the flags for given model index.

property indexes(self)[source]

Returns the time stamps as an array.

insertRows(self, 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(self, 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(self, value)[source]

Resets the model with new time series data.

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

Sets the ignore_year option of the time series.

set_repeat(self, repeat)[source]

Sets the repeat option of the time series.

property values(self)[source]

Returns the values of the time series as an array.

spinetoolbox.project_item

This subpackage contains base classes for project items.

authors
  1. Marin (KTH)

date

8.10.2020

Submodules
spinetoolbox.project_item.project_item

Contains base classes for project items and item factories.

authors
  1. Savolainen (VTT)

date

4.10.2018

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

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

property logger(self)[source]
property log_document(self)[source]
property filter_log_documents(self)[source]
property filter_consoles(self)[source]
make_signal_handler_dict(self)[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(self)[source]

Restore selections and connect signals.

deactivate(self)[source]

Save selections and disconnect signals.

restore_selections(self)[source]

Restore selections into shared widgets when this project item is selected.

save_selections(self)[source]

Save selections in shared widgets for this project item into instance variables.

_connect_signals(self)[source]

Connect signals to handlers.

_disconnect_signals(self)[source]

Disconnect signals from handlers and check for errors.

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

Returns the specification for this item.

undo_specification(self)[source]
set_specification(self, specification)[source]

Pushes a new SetItemSpecificationCommand to the toolbox’ undo stack.

do_set_specification(self, 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(self, icon)[source]

Sets the icon for the item.

Parameters

icon (ProjectItemIcon) – item’s icon

get_icon(self)[source]

Returns the graphics item representing this item in the scene.

_check_notifications(self)[source]

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

clear_notifications(self)[source]

Clear all notifications from the exclamation icon.

add_notification(self, text)[source]

Add a notification to the exclamation icon.

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

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

property executable_class(self)[source]
handle_execution_successful(self, 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(self)[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(self)[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(self)[source]

Notifies direct predecessors that item’s resources have changed.

_resource_to_predecessors_replaced(self, old, new)[source]

Notifies direct predecessors that one of item’s resources has been replaced.

Parameters
  • old (ProjectItemResource) – old resource

  • new (ProjectItemResource) – new resource

upstream_resources_updated(self, resources)[source]

Notifies item that resources from direct predecessors have changed.

Parameters

resources (list of ProjectItemResource) – new resources from upstream

replace_resource_from_upstream(self, old, new)[source]

Replaces an existing resource from direct predecessor by a new one.

Parameters
  • old (ProjectItemResource) – old resource

  • new (ProjectItemResource) – new resource

_resources_to_successors_changed(self)[source]

Notifies direct successors that item’s resources have changed.

_resource_to_successors_replaced(self, old, new)[source]

Notifies direct successors that one of item’s resources has been replaced.

Parameters
  • old (ProjectItemResource) – old resource

  • new (ProjectItemResource) – new resource

downstream_resources_updated(self, resources)[source]

Notifies item that resources from direct successors have changed.

Parameters

resources (list of ProjectItemResource) – new resources from downstream

replace_resource_from_downstream(self, old, new)[source]

Replaces an existing resource from direct successor by a new one.

Parameters
  • old (ProjectItemResource) – old resource

  • new (ProjectItemResource) – new resource

invalidate_workflow(self, 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(self)[source]
item_dict(self)[source]

Returns a dictionary corresponding to this item.

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

Item specific actions.

Returns

item’s actions

Return type

list of QAction

rename(self, 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(self, checked=False)[source]

Open this item’s data directory in file explorer.

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

Sets up this item. Called when adding the item to the project. Implement in subclasses to eg recreate attributes destroyed by tear_down.

abstract update_name_label(self)[source]

Updates the name label on the properties widget when renaming an item.

Must be reimplemented by subclasses.

notify_destination(self, 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

_create_filter_log_document(self, filter_id)[source]

Creates log document for a filter execution if none yet, and returns it

Parameters

filter_id (str) – filter identifier

Returns

SignedTextDocument

_create_log_document(self)[source]

Creates log document if none yet, and returns it

Parameters

filter_id (str) – filter identifier

Returns

SignedTextDocument

add_log_message(self, filter_id, message)[source]

Adds a message to the log document.

Parameters
  • filter_id (str) – filter identifier

  • message (str) – formatted message

add_event_message(self, 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(self, 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

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.

authors
  1. Savolainen (VTT)

date

4.10.2018

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

author
  1. Marin (KTH), P. Savolainen (VTT)

date

12.4.2018

Module Contents
Classes

ChangeSpecPropertyCommand

Command to set specification properties.

SpecificationEditorWindowBase

Base class for spec editors.

_SpecNameDescriptionToolbar

A QToolBar to let users set name and description for an Spec.

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: PySide2.QtWidgets.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(self)[source]
undo(self)[source]
class spinetoolbox.project_item.specification_editor_window.SpecificationEditorWindowBase(toolbox, specification=None, item=None)[source]

Bases: PySide2.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

property settings_group(self)[source]

Returns the settings group for this spec type.

Returns

str

abstract _make_ui(self)[source]

Returns the ui object from Qt designer.

Returns

object

_restore_dock_widgets(self)[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(self, spec_name)[source]

Returns a ProjectItemSpecification from current form settings.

Parameters

spec_name (str) – Name of the spec

Returns

ProjectItemSpecification

_show_error(self, message)[source]
_show_status_bar_msg(self, msg)[source]
_populate_main_menu(self)[source]
_update_window_modified(self, clean)[source]
_save(self)[source]

Saves spec.

Returns

True if operation was successful, False otherwise

Return type

bool

property _duplicate_kwargs(self)[source]
_duplicate(self)[source]
tear_down(self)[source]
closeEvent(self, event)[source]
class spinetoolbox.project_item.specification_editor_window._SpecNameDescriptionToolbar(parent, spec, undo_stack)[source]

Bases: PySide2.QtWidgets.QToolBar

A QToolBar to let users set name and description for an Spec.

Parameters
  • parent (QMainWindow) – QMainWindow instance

  • spec (ProjectItemSpecification) – specification that is being edited

  • undo_stack (QUndoStack) – an undo stack

_make_main_menu(self)[source]
_set_name(self)[source]
_set_description(self)[source]
do_set_name(self, name)[source]
do_set_description(self, description)[source]
name(self)[source]
description(self)[source]
spinetoolbox.project_item.specification_editor_window.prompt_to_save_changes(parent, settings, save_callback)[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’.

Returns

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

Return type

bool

spinetoolbox.spine_db_editor

This subpackage contains GUI files for the Spine db editor.

authors
  1. Marin (KTH)

date

13.5.2020

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.

author
  1. Marin (KTH)

date

23.5.2020

Submodules
spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item

Classes to represent alternative and scenario items in a tree.

authors
  1. Vennström (VTT)

date

17.6.2020

Module Contents
Classes

AlternativeRootItem

An alternative root item.

ScenarioRootItem

A scenario root item.

AlternativeLeafItem

An alternative leaf item.

ScenarioLeafItem

A scenario leaf item.

ScenarioActiveItem

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

ScenarioAlternativeRootItem

A scenario alternative root item.

ScenarioAlternativeLeafItem

A scenario alternative leaf item.

Attributes

_ALTERNATIVE_ICON

_SCENARIO_ICON

spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item._ALTERNATIVE_ICON = [source]
spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item._SCENARIO_ICON = [source]
class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item.AlternativeRootItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem

An alternative root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property display_data(self)[source]
property icon_code(self)[source]
empty_child(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item.ScenarioRootItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem

A scenario root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property display_data(self)[source]
property icon_code(self)[source]
empty_child(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item.AlternativeLeafItem(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.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

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

Makes items editable.

class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item.ScenarioLeafItem(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 leaf item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
add_item_to_db(self, db_item)[source]
update_item_in_db(self, db_item)[source]
property scenario_alternative_root_item(self)[source]
_do_finalize(self)[source]

Do some final initialization after setting the parent.

handle_updated_in_db(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item.ScenarioActiveItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardTreeItem

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

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
flags(self, column)[source]

Enables the item and makes it selectable.

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

Returns data for given column and role.

set_data(self, column, value, role=Qt.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

class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item.ScenarioAlternativeRootItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem

A scenario alternative root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

empty_child(self)[source]
property item_type(self)[source]
property display_data(self)[source]
property tool_tip(self)[source]
property icon_code(self)[source]
property alternative_id_list(self)[source]
flags(self, column)[source]

Enables the item and makes it selectable.

update_alternative_id_list(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_item.ScenarioAlternativeLeafItem(identifier=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin, spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem

A scenario alternative leaf item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

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

Enables the item and makes it selectable.

set_data(self, column, value, role=Qt.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.alternative_scenario_model

Models to represent alternatives, scenarios and scenario alternatives in a tree.

authors
  1. Vennström (VTT), M. Marin (KTH)

date

17.6.2020

Module Contents
Classes

AlternativeScenarioModel

A model to display alternatives and scenarios in a tree view.

class spinetoolbox.spine_db_editor.mvcmodels.alternative_scenario_model.AlternativeScenarioModel(parent, db_mngr, *db_maps)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_model_base.TreeModelBase

A model to display alternatives and scenarios in a tree view.

Parameters
static _make_db_item(db_map)[source]
static _top_children()[source]
_scenarios_per_root(self, db_map_data)[source]
_alternatives_per_root(self, db_map_data)[source]
add_alternatives(self, db_map_data)[source]
add_scenarios(self, db_map_data)[source]
update_alternatives(self, db_map_data)[source]
update_scenarios(self, db_map_data)[source]
remove_alternatives(self, db_map_data)[source]
remove_scenarios(self, db_map_data)[source]
supportedDropActions(self)[source]
mimeData(self, indexes)[source]

Builds a dict mapping db name to item type to a list of ids.

Returns

QMimeData

canDropMimeData(self, data, drop_action, row, column, parent)[source]
dropMimeData(self, data, drop_action, row, column, parent)[source]
spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models

Compound models for object parameter definitions and values. These models concatenate several ‘single’ models and one ‘empty’ model.

authors
  1. Marin (KTH)

date

28.6.2019

Module Contents
Classes

CompoundParameterModel

A model that concatenates several single parameter models

CompoundObjectParameterMixin

Implements the interface for populating and filtering a compound object parameter model.

CompoundRelationshipParameterMixin

Implements the interface for populating and filtering a compound relationship parameter model.

CompoundParameterDefinitionMixin

Handles signals from db mngr for parameter_definition models.

CompoundParameterValueMixin

Handles signals from db mngr for parameter_value models.

CompoundObjectParameterDefinitionModel

A model that concatenates several single object parameter_definition models

CompoundRelationshipParameterDefinitionModel

A model that concatenates several single relationship parameter_definition models

CompoundObjectParameterValueModel

A model that concatenates several single object parameter_value models

CompoundRelationshipParameterValueModel

A model that concatenates several single relationship parameter_value models

class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundParameterModel(parent, db_mngr, *db_maps)[source]

Bases: spinetoolbox.mvcmodels.compound_table_model.CompoundWithEmptyTableModel

A model that concatenates several single parameter models and one empty parameter model.

Initializes model.

Parameters
  • parent (SpineDBEditor) – the parent object

  • db_mngr (SpineDBManager) – the database manager

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

canFetchMore(self, _parent)[source]

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

fetchMore(self, _parent)[source]

Fetches the next sub model and increments the fetched counter.

fetch_successful(self, db_map, item)[source]
fetch_id(self)[source]
abstract _make_header(self)[source]
property entity_class_type(self)[source]

Returns the entity_class type, either ‘object_class’ or ‘relationship_class’.

Returns

str

property item_type(self)[source]

Returns the parameter item type, either ‘parameter_definition’ or ‘parameter_value’.

Returns

str

property _single_model_type(self)[source]

Returns a constructor for the single models.

Returns

SingleParameterModel

property _empty_model_type(self)[source]

Returns a constructor for the empty model.

Returns

EmptyParameterModel

property entity_class_id_key(self)[source]

Returns the key corresponding to the entity_class id (either “object_class_id” or “relationship_class_id”)

Returns

str

property parameter_definition_id_key(self)[source]
init_model(self)[source]

Initializes the model.

_make_auto_filter_menus(self)[source]

Makes auto filter menus.

get_auto_filter_menu(self, logical_index)[source]

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

Parameters

logical_index (int) –

Returns

ParameterViewFilterMenu

_modify_data_in_filter_menus(self, action, db_map, db_items)[source]

Modifies data in filter menus.

Parameters
  • action (str) – either ‘add’, ‘remove’, or ‘update’

  • db_map (DiffDatabaseMapping) –

  • db_items (list(dict)) –

_do_add_data_to_filter_menus(self, db_map, db_items)[source]
_do_update_data_in_filter_menus(self, db_map, db_items)[source]
_do_remove_data_from_filter_menus(self, db_map, db_items)[source]
headerData(self, section, orientation=Qt.Horizontal, role=Qt.DisplayRole)[source]

Returns an italic font in case the given column has an autofilter installed.

_create_empty_model(self)[source]

Returns the empty model for this compound model.

Returns

EmptyParameterModel

filter_accepts_model(self, model)[source]

Returns a boolean indicating whether or not the given model passes the filter for compound model.

Parameters

model (SingleParameterModel, EmptyParameterModel) –

Returns

bool

_class_filter_accepts_model(self, model)[source]
_auto_filter_accepts_model(self, model)[source]
accepted_single_models(self)[source]

Returns a list of accepted single models by calling filter_accepts_model on each of them, just for convenience.

Returns

list

_invalidate_filter(self)[source]

Sets the filter invalid.

set_filter_class_ids(self, class_ids)[source]
set_auto_filter(self, field, values)[source]

Updates and applies the auto filter.

Parameters
  • field (str) – the field name

  • values (dict) – mapping db_map to entity_class id to accepted values for the field

_set_compound_auto_filter(self, field, values)[source]

Sets the auto filter for given column in the compound model.

Parameters
  • field (str) – the field name

  • values (dict) – maps tuple (database map, entity_class id) to list of accepted ids for the field

_set_single_auto_filter(self, model, field)[source]

Sets the auto filter for given column in the given single model.

Parameters
Returns

True if the auto-filtered values were updated, None otherwise

Return type

bool

_row_map_iterator_for_model(self, model)[source]

Yields row map for the given model. Reimplemented to take filter status into account.

Parameters

model (SingleParameterModel, EmptyParameterModel) –

Returns

tuples (model, row number) for each accepted row

Return type

list

_models_with_db_map(self, db_map)[source]

Returns a collection of single models with given db_map.

Parameters

db_map (DiffDatabaseMapping) –

Returns

list

receive_entity_classes_removed(self, db_map_data)[source]

Runs when entity classes are removed from the dbs. Removes sub-models for the given entity classes and dbs.

Parameters

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

_items_per_class(self, items)[source]

Returns a dict mapping entity_class ids to a set of items.

Parameters

items (list) –

Returns

dict

receive_parameter_data_added(self, 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(self, model)[source]
_create_single_model(self, db_map, entity_class_id, committed)[source]
_add_parameter_data(self, db_map, entity_class_id, ids, committed)[source]
receive_parameter_data_updated(self, 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

receive_parameter_data_removed(self, 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

_emit_data_changed_for_column(self, field)[source]

Lazily emits data changed for an entire column.

Parameters

field (str) – the column header

db_item(self, index)[source]
db_map_id(self, index)[source]
index_name(self, 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(self, index)[source]

Returns a function that ParameterValueEditor can call to set data for the given index at any later time, even if the model changes.

Parameters

index (QModelIndex) –

Returns

function

get_entity_class_id(self, index, db_map)[source]
filter_by(self, rows_per_column)[source]
filter_excluding(self, rows_per_column)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundObjectParameterMixin[source]

Implements the interface for populating and filtering a compound object parameter model.

property entity_class_type(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundRelationshipParameterMixin[source]

Implements the interface for populating and filtering a compound relationship parameter model.

property entity_class_type(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundParameterDefinitionMixin[source]

Handles signals from db mngr for parameter_definition models.

property item_type(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundParameterValueMixin[source]

Handles signals from db mngr for parameter_value models.

_filter_entity_ids[source]
_filter_alternative_ids[source]
property item_type(self)[source]
property entity_type(self)[source]

Returns the entity type, either ‘object’ or ‘relationship’ Used by update_single_main_filter.

Returns

str

set_filter_entity_ids(self, entity_ids)[source]
set_filter_alternative_ids(self, alternative_ids)[source]
_create_single_model(self, db_map, entity_class_id, committed)[source]
receive_alternatives_updated(self, db_map_data)[source]

Updated alternative column

Parameters

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

class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundObjectParameterDefinitionModel(parent, db_mngr, *db_maps)[source]

Bases: CompoundObjectParameterMixin, CompoundParameterDefinitionMixin, CompoundParameterModel

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

Initializes model.

Parameters
  • parent (SpineDBEditor) – the parent object

  • db_mngr (SpineDBManager) – the database manager

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

_make_header(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundRelationshipParameterDefinitionModel(parent, db_mngr, *db_maps)[source]

Bases: CompoundRelationshipParameterMixin, CompoundParameterDefinitionMixin, CompoundParameterModel

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

Initializes model.

Parameters
  • parent (SpineDBEditor) – the parent object

  • db_mngr (SpineDBManager) – the database manager

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

_make_header(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundObjectParameterValueModel(parent, db_mngr, *db_maps)[source]

Bases: CompoundObjectParameterMixin, CompoundParameterValueMixin, CompoundParameterModel

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

Initializes model.

Parameters
  • parent (SpineDBEditor) – the parent object

  • db_mngr (SpineDBManager) – the database manager

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

_make_header(self)[source]
property entity_type(self)[source]

Returns the entity type, either ‘object’ or ‘relationship’ Used by update_single_main_filter.

Returns

str

class spinetoolbox.spine_db_editor.mvcmodels.compound_parameter_models.CompoundRelationshipParameterValueModel(parent, db_mngr, *db_maps)[source]

Bases: CompoundRelationshipParameterMixin, CompoundParameterValueMixin, CompoundParameterModel

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

Initializes model.

Parameters
  • parent (SpineDBEditor) – the parent object

  • db_mngr (SpineDBManager) – the database manager

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

_make_header(self)[source]
property entity_type(self)[source]

Returns the entity type, either ‘object’ or ‘relationship’ Used by update_single_main_filter.

Returns

str

spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models

Empty models for parameter definitions and values.

authors
  1. Marin (KTH)

date

28.6.2019

Module Contents
Classes

EmptyParameterModel

An empty parameter model.

EmptyParameterDefinitionModel

An empty parameter_definition model.

EmptyObjectParameterDefinitionModel

An empty object parameter_definition model.

EmptyRelationshipParameterDefinitionModel

An empty relationship parameter_definition model.

EmptyParameterValueModel

An empty parameter_value model.

EmptyObjectParameterValueModel

An empty object parameter_value model.

EmptyRelationshipParameterValueModel

An empty relationship parameter_value model.

class spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models.EmptyParameterModel(parent, header, db_mngr)[source]

Bases: spinetoolbox.mvcmodels.empty_row_model.EmptyRowModel

An empty parameter model.

Initialize class.

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

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

  • db_mngr (SpineDBManager) –

property item_type(self)[source]

The item type, either ‘parameter_value’ or ‘parameter_definition’, required by the value_field property.

property entity_class_type(self)[source]

Either ‘object_class’ or ‘relationship_class’.

property entity_class_id_key(self)[source]
property entity_class_name_key(self)[source]
property can_be_filtered(self)[source]
property value_field(self)[source]
accepted_rows(self)[source]
db_item(self, _index)[source]
item_id(self, _row)[source]
data(self, index, role=Qt.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.

_make_unique_id(self, item)[source]

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

receive_parameter_data_added(self, 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(self, indexes, data)[source]

Sets data for indexes in batch. If successful, add items to db.

abstract add_items_to_db(self, db_map_data)[source]

Add items to db.

Parameters

db_map_data (dict) – mapping DiffDatabaseMapping instance to list of items

_make_db_map_data(self, 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

class spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models.EmptyParameterDefinitionModel(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInValueListIdMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInParameterNameMixin, EmptyParameterModel

An empty parameter_definition model.

Initializes lookup dicts.

property item_type(self)[source]

The item type, either ‘parameter_value’ or ‘parameter_definition’, required by the value_field property.

property entity_class_type(self)[source]

See base class.

add_items_to_db(self, db_map_data)[source]

See base class.

_check_item(self, item)[source]

Checks if a db item is ready to be inserted.

class spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models.EmptyObjectParameterDefinitionModel(*args, **kwargs)[source]

Bases: EmptyParameterDefinitionModel

An empty object parameter_definition model.

Initializes lookup dicts.

property entity_class_type(self)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models.EmptyRelationshipParameterDefinitionModel(*args, **kwargs)[source]

Bases: EmptyParameterDefinitionModel

An empty relationship parameter_definition model.

Initializes lookup dicts.

property entity_class_type(self)[source]

See base class.

flags(self, index)[source]

Additional hack to make the object_class_name_list column non-editable.

class spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models.EmptyParameterValueModel(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.InferEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInAlternativeIdMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInParameterDefinitionIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInEntityIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInEntityClassIdMixin, EmptyParameterModel

An empty parameter_value model.

Initializes lookup dicts.

property item_type(self)[source]

The item type, either ‘parameter_value’ or ‘parameter_definition’, required by the value_field property.

property entity_type(self)[source]

Either ‘object’ or “relationship’.

property entity_id_key(self)[source]
property entity_name_key(self)[source]
property entity_name_key_in_cache(self)[source]
_make_unique_id(self, item)[source]

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

add_items_to_db(self, db_map_data)[source]

See base class.

_check_item(self, db_map, item)[source]

Checks if a db item is ready to be inserted.

class spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models.EmptyObjectParameterValueModel(*args, **kwargs)[source]

Bases: EmptyParameterValueModel

An empty object parameter_value model.

Initializes lookup dicts.

property entity_class_type(self)[source]

Either ‘object_class’ or ‘relationship_class’.

property entity_type(self)[source]

Either ‘object’ or “relationship’.

class spinetoolbox.spine_db_editor.mvcmodels.empty_parameter_models.EmptyRelationshipParameterValueModel(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.MakeRelationshipOnTheFlyMixin, EmptyParameterValueModel

An empty relationship parameter_value model.

Initializes lookup dicts.

_add_entities_on_the_fly = True[source]
property entity_class_type(self)[source]

Either ‘object_class’ or ‘relationship_class’.

property entity_type(self)[source]

Either ‘object’ or “relationship’.

add_items_to_db(self, db_map_data)[source]

See base class.

spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item

Classes to represent entities in a tree.

authors
  1. Vennström (VTT), M. Marin (KTH)

date

11.3.2019

Module Contents
Classes

EntityRootItem

A tree item that may belong in multiple databases.

ObjectTreeRootItem

An object tree root item.

RelationshipTreeRootItem

A relationship tree root item.

EntityClassItem

An entity_class item.

ObjectClassItem

An object_class item.

RelationshipClassItem

A relationship_class item.

ObjectRelationshipClassItem

A relationship_class item.

MemberObjectClassItem

A member object class item.

EntityItem

An entity item.

ObjectItem

An object item.

MemberObjectItem

A member object item.

RelationshipItem

A relationship item.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityRootItem(model=None, db_map_ids=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item.MultiDBTreeItem

A tree item that may belong in multiple databases.

Init class.

Parameters
  • db_mngr (SpineDBManager) – a database manager

  • db_map_ids (dict) – maps instances of DiffDatabaseMapping to the id of the item in that db

item_type = root[source]
property display_id(self)[source]

“See super class.

property display_icon(self)[source]

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

property display_data(self)[source]

“See super class.

set_data(self, column, value, role)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.ObjectTreeRootItem(model=None, db_map_ids=None)[source]

Bases: EntityRootItem

An object tree root item.

Init class.

Parameters
  • db_mngr (SpineDBManager) – a database manager

  • db_map_ids (dict) – maps instances of DiffDatabaseMapping to the id of the item in that db

item_type = root[source]
property child_item_class(self)[source]

Returns ObjectClassItem.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.RelationshipTreeRootItem(model=None, db_map_ids=None)[source]

Bases: EntityRootItem

A relationship tree root item.

Init class.

Parameters
  • db_mngr (SpineDBManager) – a database manager

  • db_map_ids (dict) – maps instances of DiffDatabaseMapping to the id of the item in that db

item_type = root[source]
property child_item_class(self)[source]

Returns RelationshipClassItem.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityClassItem(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item.MultiDBTreeItem

An entity_class item.

Overridden method to declare group_child_count attribute.

property display_icon(self)[source]

Returns class icon.

_display_icon(self, for_group=False)[source]
data(self, column, role=Qt.DisplayRole)[source]

Returns data for given column and role.

raise_group_children_by_id(self, db_map_ids)[source]

Moves group children to the top of the list.

Parameters

db_map_ids (dict) – set of ids corresponding to newly inserted group children, keyed by DiffDatabaseMapping

_raise_group_children_by_row(self, rows)[source]

Moves group children to the top of the list.

Parameters

rows (set, list) – collection of rows corresponding to newly inserted group children

remove_children(self, position, count)[source]

Overriden method to keep the group child count up to date.

fetch_successful(self, db_map, item)[source]
set_data(self, column, value, role)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.ObjectClassItem(*args, **kwargs)[source]

Bases: EntityClassItem

An object_class item.

Overridden method to declare group_child_count attribute.

item_type = object_class[source]
property child_item_class(self)[source]

Returns ObjectItem.

default_parameter_data(self)[source]

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

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.RelationshipClassItem(*args, **kwargs)[source]

Bases: EntityClassItem

A relationship_class item.

Overridden method to declare group_child_count attribute.

visual_key = ['name', 'object_class_name_list'][source]
item_type = relationship_class[source]
property child_item_class(self)[source]

Returns RelationshipItem.

default_parameter_data(self)[source]

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

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.ObjectRelationshipClassItem(*args, **kwargs)[source]

Bases: RelationshipClassItem

A relationship_class item.

Overridden method to declare group_child_count attribute.

set_data(self, column, value, role)[source]

See base class.

fetch_successful(self, db_map, item)[source]
class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.MemberObjectClassItem(*args, **kwargs)[source]

Bases: ObjectClassItem

A member object class item.

Overridden method to declare group_child_count attribute.

item_type = members[source]
property display_id(self)[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(self)[source]

Returns the name for display.

db_map_data(self, db_map)[source]

Returns data for this item as if it was indeed an object class.

_display_icon(self, for_group=False)[source]

Returns icon for this item as if it was indeed an object class.

fetch_successful(self, db_map, item)[source]
property child_item_class(self)[source]

Returns MemberObjectItem.

default_parameter_data(self)[source]

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

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

Returns data for given column and role.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.EntityItem(model=None, db_map_ids=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item.MultiDBTreeItem

An entity item.

Init class.

Parameters
  • db_mngr (SpineDBManager) – a database manager

  • db_map_ids (dict) – maps instances of DiffDatabaseMapping to the id of the item in that db

_has_members_item = False[source]
property members_item(self)[source]
property display_icon(self)[source]

Returns corresponding class icon.

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

Returns data for given column and role.

set_data(self, column, value, role)[source]

See base class.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.ObjectItem(model=None, db_map_ids=None)[source]

Bases: EntityItem

An object item.

Init class.

Parameters
  • db_mngr (SpineDBManager) – a database manager

  • db_map_ids (dict) – maps instances of DiffDatabaseMapping to the id of the item in that db

item_type = object[source]
property child_item_class(self)[source]

Child class is always ObjectRelationshipClassItem.

default_parameter_data(self)[source]

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

fetch_successful(self, db_map, item)[source]
class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.MemberObjectItem(model=None, db_map_ids=None)[source]

Bases: ObjectItem

A member object item.

Init class.

Parameters
  • db_mngr (SpineDBManager) – a database manager

  • db_map_ids (dict) – maps instances of DiffDatabaseMapping to the id of the item in that db

item_type = entity_group[source]
visual_key = ['member_name'][source]
property display_icon(self)[source]

Returns corresponding class icon.

property display_data(self)[source]

“Returns the name for display.

has_children(self)[source]

Returns whether or not this item has or could have children.

can_fetch_more(self)[source]

Returns whether or not this item can fetch more.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_item.RelationshipItem(*args, **kwargs)[source]

Bases: EntityItem

A relationship item.

Overridden method to make sure we never try to fetch this item.

visual_key = ['name', 'object_name_list'][source]
item_type = relationship[source]
property object_name_list(self)[source]
property display_data(self)[source]

“Returns the name for display.

property edit_data(self)[source]
default_parameter_data(self)[source]

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

has_children(self)[source]

Returns whether or not this item has or could have children.

can_fetch_more(self)[source]

Returns whether or not this item can fetch more.

is_valid(self)[source]

Checks that the grand parent object is still in the relationship.

spinetoolbox.spine_db_editor.mvcmodels.entity_tree_models

Models to represent entities in a tree.

authors
  1. Vennström (VTT), M. Marin (KTH)

date

11.3.2019

Module Contents
Classes

ObjectTreeModel

An 'object-oriented' tree model.

RelationshipTreeModel

A relationship-oriented tree model.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_models.ObjectTreeModel(parent, db_mngr, *db_maps)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_model.MultiDBTreeModel

An ‘object-oriented’ tree model.

Init class.

Parameters
  • parent (SpineDBEditor) –

  • db_mngr (SpineDBManager) – A manager for the given db_maps

  • db_maps (iter) – DiffDatabaseMapping instances

property root_item_type(self)[source]

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

_parent_object_data(self, db_map_data)[source]

Takes given object data and returns the same data keyed by parent tree-item.

Parameters

db_map_data (dict) – maps DiffDatabaseMapping instances to list of items as dict

Returns

maps parent tree-items to DiffDatabaseMapping instances to list of item ids

Return type

dict

_parent_relationship_class_data(self, db_map_data)[source]

Takes given relationship_class data and returns the same data keyed by parent tree-item.

Parameters

db_map_data (dict) – maps DiffDatabaseMapping instances to list of items as dict

Returns

maps parent tree-items to DiffDatabaseMapping instances to list of item ids

Return type

dict

_parent_relationship_data(self, db_map_data)[source]

Takes given relationship data and returns the same data keyed by parent tree-item.

Parameters

db_map_data (dict) – maps DiffDatabaseMapping instances to list of items as dict

Returns

maps parent tree-items to DiffDatabaseMapping instances to list of item ids

Return type

dict

_parent_relationship_data_for_update(self, db_map_data)[source]

Takes given relationship data and returns the same data keyed by parent tree-item.

Parameters

db_map_data (dict) – maps DiffDatabaseMapping instances to list of items as dict

Returns

maps parent tree-items to DiffDatabaseMapping instances to list of item ids

Return type

dict

_parent_entity_group_data(self, db_map_data)[source]

Takes given entity group data and returns the same data keyed by parent tree-item.

Parameters

db_map_data (dict) – maps DiffDatabaseMapping instances to list of items as dict

Returns

maps parent tree-items to DiffDatabaseMapping instances to list of item ids

Return type

dict

_parent_entity_member_data(self, db_map_data)[source]

Takes given entity member data and returns the same data keyed by parent tree-item.

Parameters

db_map_data (dict) – maps DiffDatabaseMapping instances to list of items as dict

Returns

maps parent tree-items to DiffDatabaseMapping instances to list of item ids

Return type

dict

add_object_classes(self, db_map_data)[source]
add_objects(self, db_map_data)[source]
add_relationship_classes(self, db_map_data)[source]
add_relationships(self, db_map_data)[source]
add_entity_groups(self, db_map_data)[source]
remove_object_classes(self, db_map_data)[source]
remove_objects(self, db_map_data)[source]
remove_relationship_classes(self, db_map_data)[source]
remove_relationships(self, db_map_data)[source]
remove_entity_groups(self, db_map_data)[source]
update_object_classes(self, db_map_data)[source]
update_objects(self, db_map_data)[source]
update_relationship_classes(self, db_map_data)[source]
update_relationships(self, db_map_data)[source]
find_next_relationship_index(self, index)[source]

Find and return next occurrence of relationship item.

class spinetoolbox.spine_db_editor.mvcmodels.entity_tree_models.RelationshipTreeModel(parent, db_mngr, *db_maps)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_model.MultiDBTreeModel

A relationship-oriented tree model.

Init class.

Parameters
  • parent (SpineDBEditor) –

  • db_mngr (SpineDBManager) – A manager for the given db_maps

  • db_maps (iter) – DiffDatabaseMapping instances

property root_item_type(self)[source]

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

_parent_relationship_data(self, db_map_data)[source]

Takes given relationship data and returns the same data keyed by parent tree-item.

Parameters

db_map_data (dict) – maps DiffDatabaseMapping instances to list of items as dict

Returns

maps parent tree-items to DiffDatabaseMapping instances to list of item ids

Return type

dict

add_relationship_classes(self, db_map_data)[source]
add_relationships(self, db_map_data)[source]
remove_relationship_classes(self, db_map_data)[source]
remove_relationships(self, db_map_data)[source]
update_relationship_classes(self, db_map_data)[source]
update_relationships(self, db_map_data)[source]
spinetoolbox.spine_db_editor.mvcmodels.frozen_table_model

Contains FrozenTableModel class.

author
  1. Vennström (VTT)

date

24.9.2019

Module Contents
Classes

FrozenTableModel

Used by custom_qtableview.FrozenTableView

class spinetoolbox.spine_db_editor.mvcmodels.frozen_table_model.FrozenTableModel(parent, headers=None, data=None)[source]

Bases: PySide2.QtCore.QAbstractItemModel

Used by custom_qtableview.FrozenTableView

Parameters

parent (TabularViewMixin) –

parent(self, child=None)[source]
index(self, row, column, parent=QModelIndex())[source]
reset_model(self, data, headers)[source]
clear_model(self)[source]
rowCount(self, parent=QModelIndex())[source]
columnCount(self, parent=QModelIndex())[source]
row(self, index)[source]
data(self, index, role)[source]
headerData(self, section, orientation, role=Qt.DisplayRole)[source]
property headers(self)[source]
spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_item

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

authors
  1. Vennström (VTT), M. Marin (KTH)

date

17.6.2020

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=None, db_map_ids=None)[source]

Bases: spinetoolbox.mvcmodels.minimal_tree_model.TreeItem

A tree item that may belong in multiple databases.

Init class.

Parameters
  • db_mngr (SpineDBManager) – a database manager

  • db_map_ids (dict) – maps instances of DiffDatabaseMapping to the id of the item in that db

item_type[source]

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

visual_key = ['name'][source]
abstract set_data(self, 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

property db_mngr(self)[source]
property child_item_class(self)[source]

Returns the type of child items. Reimplement in subclasses to return something more meaningful.

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

Returns the name for display.

property display_database(self)[source]

Returns the database for display.

property display_icon(self)[source]

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

property first_db_map(self)[source]

Returns the first associated db_map.

property last_db_map(self)[source]

Returns the last associated db_map.

property db_maps(self)[source]

Returns a list of all associated db_maps.

property db_map_ids(self)[source]

Returns dict with db_map as key and id as value

add_db_map_id(self, db_map, id_)[source]

Adds id for this item in the given db_map.

take_db_map(self, db_map)[source]

Removes the mapping for given db_map and returns it.

_deep_refresh_children(self)[source]

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

deep_remove_db_map(self, db_map)[source]

Removes given db_map from this item and all its descendants.

deep_take_db_map(self, 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(self, other)[source]

Merges another item and all its descendants into this one.

db_map_id(self, db_map)[source]

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

db_map_data(self, db_map)[source]

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

db_map_data_field(self, 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(self, db_map, children_ids)[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

_merge_children(self, new_children)[source]

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

_insert_children_sorted(self, new_children)[source]

Inserts and sorts children.

fetch_successful(self, db_map, item)[source]
_handle_fully_fetched(self)[source]

Notifies the view that the model’s layout has changed. This triggers a repaint so this item may be painted gray if no children.

property fetch_item_type(self)[source]
can_fetch_more(self)[source]

Returns whether or not this item can fetch more.

fetch_more(self)[source]

Fetches children from all associated databases.

_get_pending_children_ids(self, db_map)[source]

Returns a list of children ids that are in the cache but not added.

fetch_more_if_possible(self)[source]
get_children_ids(self, db_map)[source]
append_children_by_id(self, db_map_ids)[source]

Appends children by id.

Parameters

db_map_ids (dict) – maps DiffDatabaseMapping instances to list of ids

remove_children_by_id(self, db_map_ids)[source]

Removes children by id.

Parameters

db_map_ids (dict) – maps DiffDatabaseMapping instances to list of ids

is_valid(self)[source]

Checks if the item is still valid after an update operation.

update_children_by_id(self, db_map_ids)[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(self, 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 (iter) – insert items from this iterable

remove_children(self, position, count)[source]

Removes count children starting from the given position.

clear_children(self)[source]

Clear children list.

_refresh_child_map(self)[source]

Recomputes the child map.

find_children_by_id(self, 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(self, db_map, *ids, reverse=True)[source]
_find_unsorted_rows_by_id(self, 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(self, column, role=Qt.DisplayRole)[source]

Returns data for given column and role.

default_parameter_data(self)[source]

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

spinetoolbox.spine_db_editor.mvcmodels.multi_db_tree_model

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

authors
  1. Vennström (VTT), M. Marin (KTH)

date

17.6.2020

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(parent, 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
  • parent (SpineDBEditor) –

  • db_mngr (SpineDBManager) – A manager for the given db_maps

  • db_maps (iter) – DiffDatabaseMapping instances

property root_item_type(self)[source]

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

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

Builds tree.

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

Returns items at given path prefix.

spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins

Miscelaneous mixins for parameter models

authors
  1. Marin (KTH)

date

4.10.2019

Module Contents
Classes

ConvertToDBMixin

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.

MakeRelationshipOnTheFlyMixin

Makes relationships on the fly.

Functions

_parse_csv_list(csv_list)

spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins._parse_csv_list(csv_list)[source]
class spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.ConvertToDBMixin[source]

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

build_lookup_dictionary(self, db_map_data)[source]

Begins an operation to convert items.

_convert_to_db(self, 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.parameter_mixins.FillInAlternativeIdMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in alternative names.

Initializes lookup dicts.

build_lookup_dictionary(self, 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(self, 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.parameter_mixins.FillInParameterNameMixin[source]

Bases: ConvertToDBMixin

Fills in parameter names.

_convert_to_db(self, 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.parameter_mixins.FillInValueListIdMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in value list ids.

Initializes lookup dicts.

build_lookup_dictionary(self, 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(self, 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(self, 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.parameter_mixins.FillInEntityClassIdMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in entity_class ids.

Initializes lookup dicts.

build_lookup_dictionary(self, 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(self, 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(self, 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.parameter_mixins.FillInEntityIdsMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in entity ids.

Initializes lookup dicts.

_add_entities_on_the_fly = False[source]
build_lookup_dictionary(self, 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(self, 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(self, 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.parameter_mixins.FillInParameterDefinitionIdsMixin(*args, **kwargs)[source]

Bases: ConvertToDBMixin

Fills in parameter_definition ids.

Initializes lookup dicts.

build_lookup_dictionary(self, 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(self, 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(self, 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.parameter_mixins.InferEntityClassIdMixin[source]

Bases: ConvertToDBMixin

Infers entity class ids.

_convert_to_db(self, 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(self, 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.parameter_mixins.ImposeEntityClassIdMixin[source]

Bases: ConvertToDBMixin

Imposes entity class ids.

_convert_to_db(self, 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(self, 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.parameter_mixins.MakeRelationshipOnTheFlyMixin(*args, **kwargs)[source]

Makes relationships on the fly.

Initializes lookup dicts.

static _make_unique_relationship_id(item)[source]

Returns a unique name-based identifier for db relationships.

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

Returns a database relationship 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 relationship item list: error log

Return type

dict

spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item

Tree items for parameter_value lists.

authors
  1. Marin (KTH)

date

28.6.2019

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(db_map)[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.

Init class.

Args

db_mngr (SpineDBManager) db_map (DiffDatabaseMapping)

property item_type(self)[source]
property fetch_item_type(self)[source]
empty_child(self)[source]
remove_wip_items(self, names)[source]
class spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item.ListItem(identifier=None, name=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.EmptyChildMixin, spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.BoldTextMixin, spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem

A list item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
_make_item_data(self)[source]
property value_list(self)[source]
_do_finalize(self)[source]

Do some final initialization after setting the parent.

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

Returns data for given column and role.

set_data(self, column, value, role=Qt.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

abstract add_item_to_db(self, db_item)[source]
update_item_in_db(self, db_item)[source]
handle_updated_in_db(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.parameter_value_list_item.ValueItem(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.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

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

Returns data for given column and role.

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

A tree model for parameter_value lists.

authors
  1. Marin (KTH)

date

28.6.2019

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(parent, 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
add_parameter_value_lists(self, db_map_data)[source]
update_parameter_value_lists(self, db_map_data)[source]
remove_parameter_value_lists(self, db_map_data)[source]
static _make_db_item(db_map)[source]
static _top_children()[source]
columnCount(self, parent=QModelIndex())[source]

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

index_name(self, index)[source]
get_set_data_delayed(self, 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.

author
  1. Vennström (VTT)

date

1.11.2018

Module Contents
Classes

PivotModel

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

Resets the model.

clear_model(self)[source]
update_model(self, data)[source]
add_to_model(self, data)[source]
remove_from_model(self, data)[source]
_check_pivot(self, 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(self, 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(self, indexes)[source]

Returns unique indexes that match the frozen condition.

Parameters

indexes (tuple) – indexes to match

Returns

unique indexes

Return type

list

set_pivot(self, rows, columns, frozen, frozen_value)[source]

Sets pivot.

set_frozen_value(self, value)[source]

Sets values for the frozen indexes.

get_pivoted_data(self, 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(self, row)[source]
column_key(self, column)[source]
property rows(self)[source]
property columns(self)[source]
spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models

Provides pivot table models for the Tabular View.

author
  1. Vennström (VTT)

date

1.11.2018

Module Contents
Classes

_FetchParent

_SimpleFetchParent

_ParameterFetchParent

_EntityFetchParent

_MemberObjectFetchParent

PivotTableModelBase

param parent

TopLeftHeaderItem

Base class for all 'top left pivot headers'.

TopLeftObjectHeaderItem

A top left header for object_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.

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.

RelationshipPivotTableModel

A model for the pivot table in relationship 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._FetchParent[source]
abstract fetch_successful(self, db_map, item)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models._SimpleFetchParent[source]

Bases: _FetchParent

fetch_successful(self, db_map, item)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models._ParameterFetchParent(parent)[source]

Bases: _FetchParent

fetch_successful(self, db_map, item)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models._EntityFetchParent(parent)[source]

Bases: _FetchParent

fetch_successful(self, db_map, item)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models._MemberObjectFetchParent(parent)[source]

Bases: _FetchParent

fetch_successful(self, db_map, item)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.PivotTableModelBase(parent)[source]

Bases: PySide2.QtCore.QAbstractTableModel

Parameters

parent (SpineDBEditor) –

_V_HEADER_WIDTH = 5[source]
_MAX_FETCH_COUNT = 1000[source]
_FETCH_DELAY = 0[source]
model_data_changed[source]
abstract _fetch_item_types(self)[source]

Yields item types to fetch for this model.

Yields

str

abstract _fetch_parent(self, item_type)[source]

Returns a parent to fetch items of given type.

Parameters

item_type (str) –

Returns

_FetchParent

_can_fetch_more_item_type(self, item_type)[source]
canFetchMore(self, _parent)[source]
_fetch_more_item_type(self, item_type)[source]
fetchMore(self, _parent)[source]
property item_type(self)[source]

Returns the item type.

reset_data_count(self)[source]
start_fetching(self)[source]
fetch_more_rows(self)[source]
fetch_more_columns(self)[source]
abstract call_reset_model(self, 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(self, data, index_ids, rows=(), columns=(), frozen=(), frozen_value=())[source]
clear_model(self)[source]
update_model(self, data)[source]

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

Parameters

data (dict) –

add_to_model(self, db_map_data)[source]
_emit_all_data_changed(self)[source]
remove_from_model(self, data)[source]
set_pivot(self, rows, columns, frozen, frozen_value)[source]
set_frozen_value(self, frozen_value)[source]
set_plot_x_column(self, column, is_x)[source]

Sets or clears the X flag on a column

property plot_x_column(self)[source]

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

headerRowCount(self)[source]

Returns number of rows occupied by header.

headerColumnCount(self)[source]

Returns number of columns occupied by header.

dataRowCount(self)[source]

Returns number of rows that contain actual data.

dataColumnCount(self)[source]

Returns number of columns that contain actual data.

emptyRowCount(self)[source]
emptyColumnCount(self)[source]
rowCount(self, parent=QModelIndex())[source]

Number of rows in table, number of header rows + datarows + 1 empty row

columnCount(self, parent=QModelIndex())[source]

Number of columns in table, number of header columns + datacolumns + 1 empty columns

flags(self, index)[source]

Roles for data

top_left_indexes(self)[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(self, index)[source]
index_in_top(self, index)[source]
index_in_left(self, index)[source]
index_in_top_left(self, index)[source]

Returns whether or not the given index is in top left corner, where pivot names are displayed

index_in_column_headers(self, index)[source]

Returns whether or not the given index is in column headers (horizontal) area

index_in_row_headers(self, index)[source]

Returns whether or not the given index is in row headers (vertical) area

index_in_headers(self, index)[source]
index_in_empty_column_headers(self, index)[source]

Returns whether or not the given index is in empty column headers (vertical) area

index_in_empty_row_headers(self, index)[source]

Returns whether or not the given index is in empty row headers (vertical) area

index_in_data(self, index)[source]

Returns whether or not the given index is in data area

column_is_index_column(self, column)[source]

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

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

Returns the id of the top left header corresponding to the given header index.

Parameters

index (QModelIndex) –

Returns

int, NoneType

_header_id(self, index)[source]

Returns the id of the given row or column header index.

Parameters

index (QModelIndex) –

Returns

int, NoneType

_header_ids(self, row, column)[source]

Returns the ids for the headers at given row and column.

Parameters
  • row (int) –

  • column (int) –

Returns

tuple(int)

header_name(self, index)[source]

Returns the name corresponding to the given header index. Used by PivotTableView.

Parameters

index (QModelIndex) –

Returns

str

_color_data(self, index)[source]
_text_alignment_data(self, index)[source]
_header_data(self, index, role=Qt.DisplayRole)[source]
_header_name(self, top_left_id, header_id)[source]
abstract _data(self, index, role)[source]
data(self, index, role=Qt.DisplayRole)[source]
setData(self, index, value, role=Qt.EditRole)[source]
batch_set_data(self, indexes, values)[source]
_batch_set_inner_data(self, inner_data)[source]
abstract _do_batch_set_inner_data(self, row_map, column_map, data, values)[source]
_batch_set_header_data(self, header_data)[source]
_batch_set_empty_header_data(self, header_data, get_top_left_id)[source]
receive_data_added_or_removed(self, db_map_data, action)[source]
receive_objects_added_or_removed(self, db_map_data, action)[source]
receive_relationships_added_or_removed(self, db_map_data, action)[source]
receive_parameter_definitions_added_or_removed(self, db_map_data, action)[source]
receive_alternatives_added_or_removed(self, db_map_data, action)[source]
receive_parameter_values_added_or_removed(self, db_map_data, action)[source]
receive_scenarios_added_or_removed(self, db_map_data, action)[source]
receive_scenarios_updated(self, db_map_data)[source]
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(self)[source]
property db_mngr(self)[source]
_get_header_data_from_db(self, item_type, header_id, field_name, role)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.TopLeftObjectHeaderItem(model, class_name, class_id)[source]

Bases: TopLeftHeaderItem

A top left header for object_class.

Parameters

model (PivotTableModelBase) –

property header_type(self)[source]
property name(self)[source]
header_data(self, header_id, role=Qt.DisplayRole)[source]
update_data(self, db_map_data)[source]
add_data(self, names)[source]
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(self)[source]
property name(self)[source]
header_data(self, header_id, role=Qt.DisplayRole)[source]
update_data(self, db_map_data)[source]
add_data(self, names)[source]
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(self)[source]
property name(self)[source]
header_data(self, header_id, role=Qt.DisplayRole)[source]
update_data(self, db_map_data)[source]
add_data(self, _names)[source]
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(self)[source]
property name(self)[source]
header_data(self, header_id, role=Qt.DisplayRole)[source]
update_data(self, db_map_data)[source]
add_data(self, names)[source]
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(self)[source]
property name(self)[source]
header_data(self, header_id, role=Qt.DisplayRole)[source]
update_data(self, db_map_data)[source]
add_data(self, names)[source]
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(self)[source]
property name(self)[source]
header_data(self, header_id, role=Qt.DisplayRole)[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(self)[source]

Returns the item type.

_fetch_item_types(self)[source]

Yields item types to fetch for this model.

Yields

str

_fetch_parent(self, item_type)[source]

Returns a parent to fetch items of given type.

Parameters

item_type (str) –

Returns

_FetchParent

db_map_object_ids(self, index)[source]

Returns db_map and object ids for given index. Used by PivotTableView.

Returns

DatabaseMapping, list

_db_map_object_ids(self, header_ids)[source]
_all_header_names(self, index)[source]

Returns the object, 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(self, 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(self, 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(self, pivot=None)[source]

See base class.

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

Sets parameter values in batch.

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

receive_objects_added_or_removed(self, db_map_data, action)[source]
receive_relationships_added_or_removed(self, db_map_data, action)[source]
receive_parameter_definitions_added_or_removed(self, db_map_data, action)[source]
receive_alternatives_added_or_removed(self, db_map_data, action)[source]
receive_parameter_values_added_or_removed(self, db_map_data, action)[source]
_load_empty_parameter_value_data(self, *args, **kwargs)[source]
_load_full_parameter_value_data(self, *args, **kwargs)[source]
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(self, pivot=None)[source]

See base class.

flags(self, index)[source]

Roles for data

column_is_index_column(self, column)[source]

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

_load_empty_parameter_value_data(self, *args, **kwargs)[source]
_load_full_parameter_value_data(self, *args, **kwargs)[source]
_data(self, index, role)[source]
static _parameter_value_to_update(id_, header_ids, value_and_type)[source]
_update_parameter_values(self, db_map_data)[source]
class spinetoolbox.spine_db_editor.mvcmodels.pivot_table_models.RelationshipPivotTableModel(parent)[source]

Bases: PivotTableModelBase

A model for the pivot table in relationship input type.

Parameters

parent (SpineDBEditor) –

property item_type(self)[source]

Returns the item type.

_fetch_item_types(self)[source]

Yields item types to fetch for this model.

Yields

str

_fetch_parent(self, item_type)[source]

Returns a parent to fetch items of given type.

Parameters

item_type (str) –

Returns

_FetchParent

call_reset_model(self, pivot=None)[source]

See base class.

static make_delegate(parent)[source]
_default_pivot(self, data)[source]
_data(self, index, role)[source]
_do_batch_set_inner_data(self, row_map, column_map, data, values)[source]
_batch_set_relationship_data(self, row_map, column_map, data, values)[source]
receive_objects_added_or_removed(self, db_map_data, action)[source]
receive_relationships_added_or_removed(self, db_map_data, action)[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(self)[source]

Returns the item type.

_fetch_item_types(self)[source]

Yields item types to fetch for this model.

Yields

str

_fetch_parent(self, item_type)[source]

Returns a parent to fetch items of given type.

Parameters

item_type (str) –

Returns

_FetchParent

call_reset_model(self, pivot=None)[source]

See base class.

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

Bases: PySide2.QtCore.QSortFilterProxyModel

Initialize class.

model_data_changed[source]
setSourceModel(self, model)[source]
set_filter(self, 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(self)[source]
accept_index(self, index, index_ids)[source]
filterAcceptsRow(self, 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(self, 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(self, indexes, values)[source]
spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models

Single models for parameter definitions and values (as ‘for a single entity’).

authors
  1. Marin (KTH)

date

28.6.2019

Module Contents
Classes

HalfSortedTableModel

Table model for outlining simple tabular data.

SingleParameterModel

A parameter model for a single entity_class to go in a CompoundParameterModel.

SingleObjectParameterMixin

Associates a parameter model with a single object_class.

SingleRelationshipParameterMixin

Associates a parameter model with a single relationship_class.

SingleParameterDefinitionMixin

A parameter_definition model for a single entity_class.

SingleParameterValueMixin

A parameter_value model for a single entity_class.

SingleObjectParameterDefinitionModel

An object parameter_definition model for a single object_class.

SingleRelationshipParameterDefinitionModel

A relationship parameter_definition model for a single relationship_class.

SingleObjectParameterValueModel

An object parameter_value model for a single object_class.

SingleRelationshipParameterValueModel

A relationship parameter_value model for a single relationship_class.

class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_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) – the parent object

reset_model(self, main_data=None)[source]

Reset model.

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

Bases: HalfSortedTableModel

A parameter model for a single entity_class to go in a CompoundParameterModel. Provides methods to associate the model to an entity_class as well as to filter entities within the class.

Init class.

Parameters

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

__lt__(self, other)[source]
property item_type(self)[source]

The item type, either ‘parameter_value’ or ‘parameter_definition’, required by the data method.

property entity_class_type(self)[source]

The entity_class type, either ‘object_class’ or ‘relationship_class’.

property entity_class_name_field(self)[source]
property entity_class_name(self)[source]
property entity_class_id_key(self)[source]
property value_field(self)[source]
property fixed_fields(self)[source]
property group_fields(self)[source]
property parameter_definition_id_key(self)[source]
property can_be_filtered(self)[source]
item_id(self, row)[source]
db_item(self, index)[source]
_db_item(self, row)[source]
db_item_from_id(self, id_)[source]
db_items(self)[source]
flags(self, index)[source]

Make fixed indexes non-editable.

get_field_item_data(self, field)[source]

Returns item data for given field.

Parameters

field (str) – A field from the header

Returns

str, str

get_id_key(self, field)[source]
get_field_item(self, field, db_item)[source]

Returns a db item corresponding to the given field from the table header, or an empty dict if the field doesn’t contain db items.

data(self, index, role=Qt.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.

batch_set_data(self, 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.

abstract update_items_in_db(self, items)[source]

Update items in db. Required by batch_set_data

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

Returns the result of the auto filter.

accepted_rows(self)[source]

Yields accepted rows, for convenience.

_get_field_item(self, field, id_)[source]

Returns a item from the db_mngr.get_item depending on the field. If a field doesn’t correspond to a item in the database then an empty dict is returned.

class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleObjectParameterMixin[source]

Associates a parameter model with a single object_class.

property entity_class_type(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleRelationshipParameterMixin[source]

Associates a parameter model with a single relationship_class.

property entity_class_type(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleParameterDefinitionMixin(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInParameterNameMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInValueListIdMixin

A parameter_definition model for a single entity_class.

Initializes lookup dicts.

property item_type(self)[source]
_sort_key(self, element)[source]
update_items_in_db(self, items)[source]

Update items in db.

Parameters

item (list) – dictionary-items

class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleParameterValueMixin(*args, **kwargs)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInAlternativeIdMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.ImposeEntityClassIdMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInParameterDefinitionIdsMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.FillInEntityIdsMixin

A parameter_value model for a single entity_class.

Initializes lookup dicts.

_filter_db_map_class_entity_ids[source]
_filter_alternative_ids[source]
_filter_entity_ids[source]
property item_type(self)[source]
property entity_type(self)[source]

Either ‘object’ or “relationship’.

property entity_id_key(self)[source]
property entity_name_key(self)[source]
property entity_name_key_in_cache(self)[source]
_sort_key(self, element)[source]
set_filter_entity_ids(self, db_map_class_entity_ids)[source]
set_filter_alternative_ids(self, db_map_alternative_ids)[source]
filter_accepts_item(self, item)[source]

Reimplemented to also account for the entity and alternative filter.

_entity_filter_accepts_item(self, item)[source]

Returns the result of the entity filter.

_alternative_filter_accepts_item(self, item)[source]

Returns the result of the alternative filter.

update_items_in_db(self, items)[source]

Update items in db.

Parameters

item (list) – dictionary-items

class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleObjectParameterDefinitionModel(*args, **kwargs)[source]

Bases: SingleObjectParameterMixin, SingleParameterDefinitionMixin, SingleParameterModel

An object parameter_definition model for a single object_class.

Initializes lookup dicts.

class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleRelationshipParameterDefinitionModel(*args, **kwargs)[source]

Bases: SingleRelationshipParameterMixin, SingleParameterDefinitionMixin, SingleParameterModel

A relationship parameter_definition model for a single relationship_class.

Initializes lookup dicts.

class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleObjectParameterValueModel(*args, **kwargs)[source]

Bases: SingleObjectParameterMixin, SingleParameterValueMixin, SingleParameterModel

An object parameter_value model for a single object_class.

Initializes lookup dicts.

property entity_type(self)[source]

Either ‘object’ or “relationship’.

class spinetoolbox.spine_db_editor.mvcmodels.single_parameter_models.SingleRelationshipParameterValueModel(*args, **kwargs)[source]

Bases: SingleRelationshipParameterMixin, spinetoolbox.spine_db_editor.mvcmodels.parameter_mixins.MakeRelationshipOnTheFlyMixin, SingleParameterValueMixin, SingleParameterModel

A relationship parameter_value model for a single relationship_class.

Initializes lookup dicts.

property entity_type(self)[source]

Either ‘object’ or “relationship’.

update_items_in_db(self, items)[source]

Update items in db.

Parameters

item (list) – dictionary-items

spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item

Classes to represent tool and feature items in a tree.

authors
  1. Marin (KTH)

date

1.9.2020

Module Contents
Classes

FeatureRootItem

A feature root item.

ToolRootItem

A tool root item.

FeatureLeafItem

A feature leaf item.

ToolLeafItem

A tool leaf item.

ToolFeatureRootItem

A tool_feature root item.

ToolFeatureLeafItem

A tool feature leaf item.

ToolFeatureRequiredItem

A tool feature required item.

ToolFeatureMethodRootItem

A tool_feature_method root item.

ToolFeatureMethodLeafItem

A tool_feature_method leaf item.

Attributes

_FEATURE_ICON

_TOOL_ICON

_METHOD_ICON

spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item._FEATURE_ICON = [source]
spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item._TOOL_ICON = [source]
spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item._METHOD_ICON = [source]
class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.FeatureRootItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem

A feature root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property display_data(self)[source]
property icon_code(self)[source]
empty_child(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.ToolRootItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem

A tool root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property display_data(self)[source]
property icon_code(self)[source]
empty_child(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.FeatureLeafItem(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 feature leaf item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
_make_item_data(self)[source]
property item_data(self)[source]
property tool_tip(self)[source]
add_item_to_db(self, db_item)[source]
update_item_in_db(self, db_item)[source]
flags(self, column)[source]

Makes items editable.

_make_item_to_add(self, value)[source]
_make_item_to_update(self, column, value)[source]
_get_ids_from_feat_name(self, feature_name)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.ToolLeafItem(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 tool leaf item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
add_item_to_db(self, db_item)[source]
update_item_in_db(self, db_item)[source]
_do_finalize(self)[source]

Do some final initialization after setting the parent.

class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.ToolFeatureRootItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem

A tool_feature root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property display_data(self)[source]
property tool_tip(self)[source]
property icon_code(self)[source]
property feature_id_list(self)[source]
flags(self, column)[source]

Enables the item and makes it selectable.

empty_child(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.ToolFeatureLeafItem(identifier=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin, spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem

A tool feature leaf item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property item_data(self)[source]
_do_finalize(self)[source]

Do some final initialization after setting the parent.

_make_item_to_add(self, value)[source]
add_item_to_db(self, db_item)[source]
update_item_in_db(self, db_item)[source]
flags(self, column)[source]

Enables the item and makes it selectable.

class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.ToolFeatureRequiredItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardTreeItem

A tool feature required item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
flags(self, column)[source]

Enables the item and makes it selectable.

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

Returns data for given column and role.

set_data(self, column, value, role=Qt.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

has_children(self)[source]

Returns whether or not this item has or could have children.

class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.ToolFeatureMethodRootItem(model=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem

A tool_feature_method root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property display_data(self)[source]
property icon_code(self)[source]
empty_child(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_item.ToolFeatureMethodLeafItem(identifier=None)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.GrayIfLastMixin, spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem

A tool_feature_method leaf item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property tool_feature_item(self)[source]
property item_data(self)[source]
_make_item_data(self)[source]
flags(self, column)[source]

Enables the item and makes it selectable.

_make_item_to_add(self, value)[source]
_make_item_to_update(self, column, value)[source]
_get_method_index(self, parameter_value_list_id, method)[source]
add_item_to_db(self, db_item)[source]
update_item_in_db(self, db_item)[source]
spinetoolbox.spine_db_editor.mvcmodels.tool_feature_model

Models to represent tools and features in a tree.

authors
  1. Marin (KTH)

date

1.0.2020

Module Contents
Classes

ToolFeatureModel

A model to display tools and features in a tree view.

class spinetoolbox.spine_db_editor.mvcmodels.tool_feature_model.ToolFeatureModel(parent, db_mngr, *db_maps)[source]

Bases: spinetoolbox.spine_db_editor.mvcmodels.tree_model_base.TreeModelBase

A model to display tools and features in a tree view.

Parameters

Initialize class

static _make_db_item(db_map)[source]
static _top_children()[source]
static make_feature_name(entity_class_name, parameter_definition_name)[source]
_begin_set_features(self, db_map)[source]
get_all_feature_names(self, db_map)[source]
get_feature_data(self, db_map, feature_name)[source]
_begin_set_feature_method(self, db_map, parameter_value_list_id)[source]
get_all_feature_methods(self, db_map, parameter_value_list_id)[source]
get_method_index(self, db_map, parameter_value_list_id, method)[source]
_tools_per_root(self, db_map_data)[source]
_features_per_root(self, db_map_data)[source]
_tool_features_per_root(self, db_map_data)[source]
_tool_feature_methods_per_root(self, db_map_data)[source]
add_features(self, db_map_data)[source]
add_tools(self, db_map_data)[source]
add_tool_features(self, db_map_data)[source]
add_tool_feature_methods(self, db_map_data)[source]
update_features(self, db_map_data)[source]
update_tools(self, db_map_data)[source]
update_tool_features(self, db_map_data)[source]
update_tool_feature_methods(self, db_map_data)[source]
remove_features(self, db_map_data)[source]
remove_tools(self, db_map_data)[source]
remove_tool_features(self, db_map_data)[source]
remove_tool_feature_methods(self, db_map_data)[source]
supportedDropActions(self)[source]
mimeData(self, indexes)[source]

Builds a dict mapping db name to item type to a list of ids.

Returns

QMimeData

canDropMimeData(self, data, drop_action, row, column, parent)[source]
dropMimeData(self, data, drop_action, row, column, parent)[source]
spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility

A tree model for parameter_value lists.

authors
  1. Marin (KTH)

date

28.6.2019

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

Guarantess there's always an empty child.

SortsChildrenMixin

FetchMoreMixin

StandardDBItem

An item representing a db.

RootItem

A root item.

EmptyChildRootItem

Guarantess there's always an empty child.

LeafItem

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

class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardTreeItem(model=None)[source]

Bases: spinetoolbox.mvcmodels.minimal_tree_model.TreeItem

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

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

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

Returns data for given column and role.

set_data(self, column, value, role=Qt.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

property non_empty_children(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EditableMixin[source]
flags(self, 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(self, column, role=Qt.DisplayRole)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.BoldTextMixin[source]

Bolds text.

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

Guarantess there’s always an empty child.

property non_empty_children(self)[source]
abstract empty_child(self)[source]
_do_finalize(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.SortsChildrenMixin[source]
insert_children_sorted(self, children)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.FetchMoreMixin[source]
property fetch_item_type(self)[source]
can_fetch_more(self)[source]
fetch_more(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.StandardDBItem(db_map)[source]

Bases: SortsChildrenMixin, StandardTreeItem

An item representing a db.

Init class.

Args

db_mngr (SpineDBManager) db_map (DiffDatabaseMapping)

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

Shows Spine icon for fun.

class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.RootItem(model=None)[source]

Bases: SortsChildrenMixin, BoldTextMixin, FetchMoreMixin, StandardTreeItem

A root item.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

property item_type(self)[source]
property db_map(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.EmptyChildRootItem(model=None)[source]

Bases: EmptyChildMixin, RootItem

Guarantess there’s always an empty child.

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

abstract empty_child(self)[source]
class spinetoolbox.spine_db_editor.mvcmodels.tree_item_utility.LeafItem(identifier=None)[source]

Bases: StandardTreeItem

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

Initializes item.

Parameters

model (MinimalTreeModel, NoneType) – The model where the item belongs.

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

Returns data for given column and role.

set_data(self, column, value, role=Qt.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(self, value)[source]
_make_item_to_update(self, column, value)[source]
handle_updated_in_db(self)[source]
can_fetch_more(self)[source]

Returns whether or not this item can fetch more.

spinetoolbox.spine_db_editor.mvcmodels.tree_model_base

Models to represent things in a tree.

authors
  1. Marin (KTH)

date

1.0.2020

Module Contents
Classes

TreeModelBase

A base model to display items in a tree view.

class spinetoolbox.spine_db_editor.mvcmodels.tree_model_base.TreeModelBase(parent, db_mngr, *db_maps)[source]

Bases: spinetoolbox.mvcmodels.minimal_tree_model.MinimalTreeModel

A base model to display items in a tree view.

Parameters
columnCount(self, parent=QModelIndex())[source]

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

Returns

column count

Return type

int

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

Builds tree.

abstract static _make_db_item(db_map)[source]
abstract static _top_children()[source]
_items_per_db_item(self, db_map_data)[source]
_items_per_root(self, db_map_data, root_number=0)[source]
static _db_map_data_per_id(db_map_data, id_key)[source]
_update_leaf_items(self, root_item, ids)[source]
static _remove_leaf_items(root_item, ids)[source]
static _insert_items(parent_item, db_items, make_child)[source]

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

Parameters
  • parent_item (TreeItem) –

  • db_items (list of dict) – database items

  • make_child (function) – A function that receives an integer id and returns a TreeItem

static db_item(item)[source]
db_row(self, item)[source]
spinetoolbox.spine_db_editor.ui

Automatically generated UI modules for Spine db editor.

authors
  1. Marin (KTH)

date

13.5.2020

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(self, Form)[source]
retranslateUi(self, 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(self, MainWindow)[source]
retranslateUi(self, MainWindow)[source]
spinetoolbox.spine_db_editor.widgets

Interface logic for Spine db editor.

authors
  1. Marin (KTH)

date

13.5.2020

Submodules
spinetoolbox.spine_db_editor.widgets.add_items_dialogs

Classes for custom QDialogs to add items to databases.

author
  1. Marin (KTH)

date

13.5.2018

Module Contents
Classes

AddReadyRelationshipsDialog

A dialog to let the user add new 'ready' relationships.

AddItemsDialog

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

AddObjectClassesDialog

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

AddObjectsDialog

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

AddRelationshipClassesDialog

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

AddOrManageRelationshipsDialog

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

AddRelationshipsDialog

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

ManageRelationshipsDialog

A dialog to query user's preferences for managing relationships.

ObjectGroupDialogBase

param parent

data store widget

AddObjectGroupDialog

param parent

data store widget

ManageMembersDialog

param parent

data store widget

class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddReadyRelationshipsDialog(parent, relationships_class, relationships, db_mngr, *db_maps)[source]

Bases: spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialogBase

A dialog to let the user add new ‘ready’ relationships.

Parameters
  • parent (SpineDBEditor) –

  • relationships_class (dict) –

  • relationships (list(list(str)) –

  • db_mngr (SpineDBManager) –

  • *db_maps – DiffDatabaseMapping instances

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

Connect signals to slots.

_handle_table_view_cell_clicked(self, row, column)[source]
_handle_table_view_current_changed(self, current, _previous)[source]
accept(self)[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(self)[source]

Connect signals to slots.

remove_selected_rows(self, checked=True)[source]
all_databases(self, 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.AddObjectClassesDialog(parent, db_mngr, *db_maps)[source]

Bases: spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ShowIconColorEditorMixin, AddItemsDialog

A dialog to query user’s preferences for new object classes.

Parameters
connect_signals(self)[source]

Connect signals to slots.

all_db_maps(self, row)[source]

Returns a list of db maps available for a given row. Used by ShowIconColorEditorMixin.

accept(self)[source]

Collect info from dialog and try to add items.

class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddObjectsDialog(parent, parent_item, db_mngr, *db_maps, force_default=False)[source]

Bases: spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetObjectClassesMixin, AddItemsDialog

A dialog to query user’s preferences for new objects.

Parameters
accept(self)[source]

Collect info from dialog and try to add items.

class spinetoolbox.spine_db_editor.widgets.add_items_dialogs.AddRelationshipClassesDialog(parent, 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.GetObjectClassesMixin, AddItemsDialog

A dialog to query user’s preferences for new relationship classes.

Parameters
connect_signals(self)[source]

Connect signals to slots.

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

Reimplement in subclasses to handle changes in model data.

accept(self)[source]

Collect info from dialog and try to add items.

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

Bases: spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetRelationshipClassesMixin, spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetObjectsMixin, AddItemsDialog

A dialog to query user’s preferences for new relationships.

Parameters
abstract make_model(self)[source]
connect_signals(self)[source]

Connect signals to slots.

abstract reset_model(self, 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.AddRelationshipsDialog(parent, parent_item, db_mngr, *db_maps, force_default=False)[source]

Bases: AddOrManageRelationshipsDialog

A dialog to query user’s preferences for new relationships.

Parameters
make_model(self)[source]
reset_model(self, index)[source]

Setup model according to current relationship_class selected in combobox.

_handle_model_data_changed(self, top_left, bottom_right, roles)[source]

Reimplement in subclasses to handle changes in model data.

accept(self)[source]

Collect info from dialog and try to add items.

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

Bases: AddOrManageRelationshipsDialog

A dialog to query user’s preferences for managing relationships.

Parameters
  • parent (SpineDBEditor) – data store widget

  • parent_item (MultiDBTreeItem) –

  • db_mngr (SpineDBManager) – the manager to do the removal

  • *db_maps – DiffDatabaseMapping instances

  • relationship_class_key (str, optional) – relationships class name, object_class name list string.

make_model(self)[source]
splitter_widgets(self)[source]
connect_signals(self)[source]

Connect signals to slots.

reset_relationship_class_combo_box(self, database, relationship_class_key=None)[source]
add_relationships(self, checked=True)[source]
reset_model(self, index)[source]

Setup model according to current relationship_class selected in combobox.

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

Collect info from dialog and try to add items.

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

Bases: PySide2.QtWidgets.QDialog

Parameters
connect_signals(self)[source]

Connect signals to slots.

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

Bases: ObjectGroupDialogBase

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

Bases: ObjectGroupDialogBase

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

Contains the CommitViewer class.

author
  1. Marin (KTH)

date

26.11.2018

Module Contents
Classes

_DBCommitViewer

_CommitItem

_CommitContents

CommitViewer

param qsettings

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

Bases: PySide2.QtWidgets.QWidget

_select_commit(self, current, previous)[source]
class spinetoolbox.spine_db_editor.widgets.commit_viewer._CommitItem(commit, parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

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

Bases: PySide2.QtWidgets.QTreeWidget

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

Bases: PySide2.QtWidgets.QMainWindow

Parameters
  • qsettings (QSettings) –

  • db_mngr (SpineDBManager) –

  • db_maps (DiffDatabaseMapping) –

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

Custom item delegates.

author
  1. Marin (KTH)

date

1.9.2018

Module Contents
Classes

RelationshipPivotTableDelegate

A delegate that places a fully functioning QCheckBox.

ScenarioAlternativeTableDelegate

A delegate that places a QCheckBox but draws a number instead of the check.

ParameterPivotTableDelegate

param parent

ParameterValueElementDelegate

Delegate for Array and Map editors' table cells.

ParameterDelegate

Base class for all custom parameter delegates.

DatabaseNameDelegate

A delegate for the database name.

ParameterValueOrDefaultValueDelegate

A delegate for the 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.

ObjectClassNameDelegate

A delegate for the object_class name.

RelationshipClassNameDelegate

A delegate for the relationship_class name.

ParameterNameDelegate

A delegate for the object parameter name.

ObjectNameDelegate

A delegate for the object name.

AlternativeNameDelegate

A delegate for the object name.

ObjectNameListDelegate

A delegate for the object name list.

ToolFeatureDelegate

A delegate for the tool feature tree.

AlternativeScenarioDelegate

A delegate for the alternative scenario tree.

ParameterValueListDelegate

A delegate for the parameter value list tree.

ManageItemsDelegate

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

ManageEntityClassesDelegate

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

ManageObjectClassesDelegate

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

ManageObjectsDelegate

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

ManageRelationshipClassesDelegate

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

ManageRelationshipsDelegate

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

RemoveEntitiesDelegate

A delegate for the model and view in RemoveEntitiesDialog.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.RelationshipPivotTableDelegate(parent)[source]

Bases: spinetoolbox.widgets.custom_delegates.CheckBoxDelegate

A delegate that places a fully functioning QCheckBox.

Parameters

parent (SpineDBEditor) –

data_committed[source]
static _is_relationship_index(index)[source]

Checks whether or not the given index corresponds to a relationship, in which case we need to use the check box delegate.

Returns

bool

setModelData(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

paint(self, painter, option, index)[source]

Paint a checkbox without the label.

editorEvent(self, 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(self, 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: spinetoolbox.widgets.custom_delegates.RankDelegate

A delegate that places a QCheckBox but draws a number instead of the check.

Parameters

parent (SpineDBEditor) –

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(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

paint(self, painter, option, index)[source]

Paint a checkbox without the label.

editorEvent(self, 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(self, 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: PySide2.QtWidgets.QStyledItemDelegate

Parameters

parent (SpineDBEditor) –

parameter_value_editor_requested[source]
data_committed[source]
setModelData(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

createEditor(self, parent, option, index)[source]
class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueElementDelegate[source]

Bases: PySide2.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(self, editor, model, index)[source]

Sets data in the model.

editor (CustomLineEditor): editor widget model (QAbstractItemModel): model index (QModelIndex): target index

createEditor(self, 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.ParameterDelegate(parent, db_mngr)[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

Base class for all custom parameter delegates.

db_mngr

database manager

Type

SpineDBManager

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

data_committed[source]
setModelData(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

updateEditorGeometry(self, editor, option, index)[source]
_close_editor(self, editor, index)[source]

Closes editor. Needed by SearchBarEditor.

_get_db_map(self, 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: ParameterDelegate

A delegate for the database name.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueOrDefaultValueDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the either the value or the default value.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

parameter_value_editor_requested[source]
setModelData(self, editor, model, index)[source]

Send signal.

_create_or_request_parameter_value_editor(self, parent, option, index, db_map)[source]

Emits the signal to request a standalone ParameterValueEditor from parent widget.

createEditor(self, 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 (SpineDBManager) – database manager

_get_value_list_id(self, index, db_map)[source]

Returns a value list item for the given index and db_map.

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 (SpineDBManager) – database manager

_get_value_list_id(self, index, db_map)[source]

Returns a value list item for the given index and db_map.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ValueListDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the parameter value list.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ObjectClassNameDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the object_class name.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.RelationshipClassNameDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the relationship_class name.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterNameDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the object parameter name.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ObjectNameDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the object name.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.AlternativeNameDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the object name.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ObjectNameListDelegate(parent, db_mngr)[source]

Bases: ParameterDelegate

A delegate for the object name list.

Parameters
  • parent (QWidget) – parent widget

  • db_mngr (SpineDBManager) – database manager

object_name_list_editor_requested[source]
createEditor(self, parent, option, index)[source]

Returns editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ToolFeatureDelegate(*args, **kwargs)[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

A delegate for the tool feature tree.

data_committed[source]
_get_names(self, item, model)[source]
static _get_index_data(item, index)[source]
setModelData(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

createEditor(self, parent, option, index)[source]

Returns editor.

updateEditorGeometry(self, editor, option, index)[source]
_close_editor(self, editor, index)[source]

Closes editor. Needed by SearchBarEditor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.AlternativeScenarioDelegate(*args, **kwargs)[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

A delegate for the alternative scenario tree.

data_committed[source]
setModelData(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

_get_names(self, item, model)[source]
static _get_index_data(item, index)[source]
createEditor(self, parent, option, index)[source]

Returns editor.

updateEditorGeometry(self, editor, option, index)[source]
_close_editor(self, editor, index)[source]

Closes editor. Needed by SearchBarEditor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ParameterValueListDelegate[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

A delegate for the parameter value list tree.

data_committed[source]
parameter_value_editor_requested[source]
setModelData(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

createEditor(self, parent, option, index)[source]

Returns editor.

_close_editor(self, editor, index)[source]

Closes editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageItemsDelegate[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

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

data_committed[source]
setModelData(self, editor, model, index)[source]

Send signal.

close_editor(self, editor, index, model)[source]
updateEditorGeometry(self, editor, option, index)[source]
connect_editor_signals(self, editor, index)[source]

Connect editor signals if necessary.

_create_database_editor(self, parent, option, index)[source]
createEditor(self, parent, option, index)[source]

Returns an editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageEntityClassesDelegate[source]

Bases: ManageItemsDelegate

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

paint(self, painter, option, index)[source]

Get a pixmap from the index data and paint it in the middle of the cell.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageObjectClassesDelegate[source]

Bases: ManageEntityClassesDelegate

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

icon_color_editor_requested[source]
createEditor(self, parent, option, index)[source]

Return editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageObjectsDelegate[source]

Bases: ManageItemsDelegate

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

createEditor(self, parent, option, index)[source]

Return editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageRelationshipClassesDelegate[source]

Bases: ManageEntityClassesDelegate

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

icon_color_editor_requested[source]
createEditor(self, parent, option, index)[source]

Return editor.

class spinetoolbox.spine_db_editor.widgets.custom_delegates.ManageRelationshipsDelegate[source]

Bases: ManageItemsDelegate

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

createEditor(self, 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(self, parent, option, index)[source]

Return editor.

spinetoolbox.spine_db_editor.widgets.custom_menus

Classes for custom context menus and pop-up menus.

author
  1. Marin (KTH)

date

13.5.2020

Module Contents
Classes

MainMenu

ParameterViewFilterMenu

Filter menu.

TabularViewFilterMenu

Filter menu to use together with FilterWidget in TabularViewMixin.

class spinetoolbox.spine_db_editor.widgets.custom_menus.MainMenu[source]

Bases: PySide2.QtWidgets.QMenu

event(self, ev)[source]

Intercepts shortcurts 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 underligned on windows.

class spinetoolbox.spine_db_editor.widgets.custom_menus.ParameterViewFilterMenu(parent, source_model, field, show_empty=True)[source]

Bases: spinetoolbox.widgets.custom_menus.FilterMenuBase

Filter menu.

Parameters
filterChanged[source]
_handle_source_model_refreshed(self)[source]

Updates the menu to only present values that are actually shown in the source model.

set_filter_accepted_values(self, accepted_values)[source]
set_filter_rejected_values(self, rejected_values)[source]
_get_value_to_remove(self, action, db_map, db_item)[source]
_get_value_to_add(self, action, db_map, db_item)[source]
modify_menu_data(self, action, db_map, db_items)[source]

Modifies data in the menu.

Parameters
  • action (str) – either ‘add’, ‘remove’, or ‘update’

  • db_map (DiffDatabaseMapping) –

  • db_items (list(dict)) –

_build_auto_filter(self, valid_values)[source]

Builds the auto filter given valid values.

Parameters

valid_values (Sequence) – Values accepted by the filter.

Returns

mapping db_map, to entity_class_id, to set of accepted parameter_value/definition ids

Return type

dict

emit_filter_changed(self, 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, identifier, data_to_value, show_empty=True)[source]

Bases: spinetoolbox.widgets.custom_menus.FilterMenuBase

Filter menu to use together with FilterWidget in TabularViewMixin.

Parameters
  • parent (SpineDBEditor) –

  • identifier (int) – index identifier

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

filterChanged[source]
emit_filter_changed(self, valid_values)[source]
event(self, event)[source]
spinetoolbox.spine_db_editor.widgets.custom_qgraphicsviews

Classes for custom QGraphicsViews for the Entity graph view.

authors
  1. Savolainen (VTT), M. Marin (KTH)

date

6.2.2018

Module Contents
Classes

EntityQGraphicsView

QGraphicsView for the Entity Graph View.

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)

graph_selection_changed[source]
property _qsettings(self)[source]
property db_mngr(self)[source]
property entity_items(self)[source]
handle_scene_selection_changed(self)[source]

Filters parameters by selected objects in the graph.

connect_spine_db_editor(self, spine_db_editor)[source]
populate_context_menu(self)[source]
increase_arc_length(self)[source]
decrease_arc_length(self)[source]
_update_actions_visibility(self)[source]

Enables or disables actions according to current selection in the graph.

make_items_menu(self)[source]
set_auto_expand_objects(self, checked=False)[source]
add_objects_at_position(self, checked=False)[source]
edit_selected(self, _=False)[source]

Edits selected items.

remove_selected(self, _=False)[source]

Removes selected items.

_get_selected_entity_names(self)[source]
hide_selected_items(self, checked=False)[source]

Hides selected items.

_hide_class(self, action)[source]

Hides some class.

show_all_hidden_items(self, checked=False)[source]

Shows all hidden items.

show_hidden_items(self, action)[source]

Shows some hidden items.

prune_selected_items(self, checked=False)[source]

Prunes selected items.

_prune_class(self, action)[source]

Prunnes some class.

restore_all_pruned_items(self, checked=False)[source]

Reinstates all pruned items.

restore_pruned_items(self, action)[source]

Reinstates some pruned items.

select_position_parameters(self, checked=False)[source]
_set_position_parameters(self, parameter_pos_x, parameter_pos_y)[source]
save_positions(self, checked=False)[source]
clear_saved_positions(self, checked=False)[source]
export_as_pdf(self, checked=False)[source]
_populate_add_heat_map_menu(self)[source]

Populates the menu ‘Add heat map’ with parameters for currently shown items in the graph.

add_heat_map(self, action)[source]

Adds heat map for the parameter in the action text.

_clean_up_heat_map_items(self)[source]
set_cross_hairs_items(self, relationship_class, cross_hairs_items)[source]

Sets ‘cross_hairs’ items for relationship creation.

Parameters
  • relationship_class (dict) –

  • cross_hairs_items (list(QGraphicsItems)) –

clear_cross_hairs_items(self)[source]
_cross_hairs_has_valid_target(self)[source]
mousePressEvent(self, event)[source]

Handles relationship creation if one it’s in process.

mouseMoveEvent(self, event)[source]

Updates the hovered object item if we’re in relationship creation mode.

_update_cross_hairs_pos(self, pos)[source]

Updates the hovered object item and sets the ‘cross_hairs’ icon accordingly.

Parameters

pos (QPoint) – the desired position in view coordinates

mouseReleaseEvent(self, event)[source]

Reestablish scroll hand drag mode.

_scroll_scene_by(self, dx, dy)[source]
keyPressEvent(self, event)[source]

Aborts relationship creation if user presses ESC.

contextMenuEvent(self, e)[source]

Shows context menu.

Parameters

e (QContextMenuEvent) – Context menu event

_compute_max_zoom(self)[source]
_use_smooth_zoom(self)[source]
_zoom(self, factor)[source]
apply_zoom(self)[source]
wheelEvent(self, 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(self, pos)[source]

Performs rotation whenever the smooth rotation time line advances.

_rotate(self, angle)[source]
rotate_clockwise(self)[source]

Performs a rotate clockwise with fixed angle.

rotate_anticlockwise(self)[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.

author
  1. Marin (KTH)

date

18.5.2018

Module Contents
Classes

ParameterTableView

Custom QTableView class with autofilter functionality.

ObjectParameterTableMixin

RelationshipParameterTableMixin

ParameterDefinitionTableView

Custom QTableView class with autofilter functionality.

ParameterValueTableView

Custom QTableView class with autofilter functionality.

ObjectParameterDefinitionTableView

A custom QTableView for the object parameter_definition pane in Spine db editor.

RelationshipParameterDefinitionTableView

A custom QTableView for the relationship parameter_definition pane in Spine db editor.

ObjectParameterValueTableView

A custom QTableView for the object parameter_value pane in Spine db editor.

RelationshipParameterValueTableView

A custom QTableView for the relationship parameter_value pane in Spine db editor.

PivotTableView

Custom QTableView class with pivot capabilities.

FrozenTableView

Functions

_set_parameter_data(index, new_value)

Updates (object or relationship) parameter_definition or value with newly edited data.

spinetoolbox.spine_db_editor.widgets.custom_qtableview._set_parameter_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.ParameterTableView(parent)[source]

Bases: spinetoolbox.widgets.custom_qtableview.AutoFilterCopyPasteTableView

Custom QTableView class with autofilter functionality.

Initialize the view.

property value_column_header(self)[source]

Either “default value” or “value”. Used to identifiy the value column for advanced editting and plotting.

connect_spine_db_editor(self, spine_db_editor)[source]

Connects a Spine db editor to work with this view.

Parameters

spine_db_editor (SpineDBEditor) –

_make_delegate(self, column_name, delegate_class)[source]

Creates a delegate for the given column and returns it.

Parameters
Returns

ParameterDelegate

create_delegates(self)[source]

Creates delegates for this view

open_in_editor(self)[source]

Opens the current index in a parameter_value editor using the connected Spine db editor.

plot(self, checked=False)[source]

Plots current index.

plot_in_window(self, action)[source]

Plots current index in the window given by action’s name.

populate_context_menu(self)[source]

Creates a context menu for this view.

contextMenuEvent(self, event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

_selected_rows_per_column(self)[source]

Computes selected rows per column.

Returns

Mapping columns to selected rows in that column.

Return type

dict

filter_by_selection(self, checked=False)[source]
filter_excluding_selection(self, checked=False)[source]
remove_selected(self)[source]

Removes selected indexes.

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ObjectParameterTableMixin[source]
create_delegates(self)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtableview.RelationshipParameterTableMixin[source]
create_delegates(self)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterDefinitionTableView(parent)[source]

Bases: ParameterTableView

Custom QTableView class with autofilter functionality.

Initialize the view.

property value_column_header(self)[source]

Either “default value” or “value”. Used to identifiy the value column for advanced editting and plotting.

create_delegates(self)[source]

Creates delegates for this view

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ParameterValueTableView(parent)[source]

Bases: ParameterTableView

Custom QTableView class with autofilter functionality.

Initialize the view.

property value_column_header(self)[source]

Either “default value” or “value”. Used to identifiy the value column for advanced editting and plotting.

create_delegates(self)[source]

Creates delegates for this view

populate_context_menu(self)[source]

Creates a context menu for this view.

show_value_metadata(self)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ObjectParameterDefinitionTableView(parent)[source]

Bases: ObjectParameterTableMixin, ParameterDefinitionTableView

A custom QTableView for the object parameter_definition pane in Spine db editor.

Initialize the view.

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.RelationshipParameterDefinitionTableView(parent)[source]

Bases: RelationshipParameterTableMixin, ParameterDefinitionTableView

A custom QTableView for the relationship parameter_definition pane in Spine db editor.

Initialize the view.

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.ObjectParameterValueTableView(parent)[source]

Bases: ObjectParameterTableMixin, ParameterValueTableView

A custom QTableView for the object parameter_value pane in Spine db editor.

Initialize the view.

create_delegates(self)[source]

Creates delegates for this view

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.RelationshipParameterValueTableView(parent)[source]

Bases: RelationshipParameterTableMixin, ParameterValueTableView

A custom QTableView for the relationship parameter_value pane in Spine db editor.

Initialize the view.

create_delegates(self)[source]

Creates delegates for this view

class spinetoolbox.spine_db_editor.widgets.custom_qtableview.PivotTableView(parent=None)[source]

Bases: spinetoolbox.widgets.custom_qtableview.CopyPasteTableView

Custom QTableView class with pivot capabilities.

Uses ‘contexts’ to provide different UI elements (table headers, context menus,…) depending on what data the pivot table currently contains.

Parameters

parent (QWidget, optional) – parent widget

class _ContextBase(view, db_editor, horizontal_header, vertical_header)[source]

Base class for pivot table view’s contexts.

Parameters
  • view (PivotTableView) – parent view

  • db_editor (SpineDBEditor) – database editor

  • horizontal_header (QHeaderView) – horizontal header

  • vertical_header (QHeaderView) – vertical header

_REMOVE_OBJECT = Remove objects[source]
_REMOVE_RELATIONSHIP = Remove relationships[source]
_REMOVE_PARAMETER = Remove parameter definitions[source]
_REMOVE_ALTERNATIVE = Remove alternatives[source]
_REMOVE_SCENARIO = Remove scenarios[source]
_clear_selection_lists(self)[source]

Clears cached selected index lists.

abstract populate_context_menu(self)[source]

Generates context menu.

_refresh_selected_indexes(self)[source]

Caches selected index lists.

remove_alternatives(self)[source]

Removes selected alternatives from the database.

show_context_menu(self, position)[source]

Shows the context menu.

_to_selection_lists(self, index, source_model)[source]

Caches given index to corresponding selected index list.

Parameters
  • index (QModelIndex) – index to cache

  • source_model (PivotTableModelBase) – underlying model

abstract _update_actions_availability(self)[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

_can_remove_relationships(self)[source]

Checks if it makes sense to remove selected relationships from the database.

Returns

True if relationships can be removed, False otherwise

Return type

bool

_clear_selection_lists(self)[source]

See base class.

abstract populate_context_menu(self)[source]

See base class.

remove_objects(self)[source]

Removes selected objects from the database.

remove_relationships(self)[source]

Removes selected relationships from the database.

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

See base class.

populate_context_menu(self)[source]

See base class.

open_in_editor(self)[source]

Opens the parameter value editor for the first selected cell.

plot(self)[source]

Plots the selected cells.

_plot_in_window(self, action)[source]

Plots the selected cells in an existing window.

remove_parameters(self)[source]

Removes selected parameter definitions from the database.

remove_values(self)[source]

Removes selected parameter values from the database.

_show_context_menu(self, position)[source]

See base class.

_to_selection_lists(self, index, source_model)[source]

See base class.

_update_actions_availability(self)[source]

See base class.

class _IndexExpansionContext(view, db_editor)[source]

Bases: PivotTableView._ParameterValueContext

Context for expanded parameter values

Parameters
class _RelationshipContext(view, db_editor)[source]

Bases: PivotTableView._EntityContextBase

Context for presenting relationships in the pivot table.

Parameters
populate_context_menu(self)[source]

See base class.

_update_actions_availability(self)[source]

See base class.

class _ScenarioAlternativeContext(view, db_editor)[source]

Bases: PivotTableView._ContextBase

Context for presenting scenarios and alternatives

Parameters
_clear_selection_lists(self)[source]

See base class.

populate_context_menu(self)[source]

See base class.

remove_scenarios(self)[source]

Removes selected scenarios from the database.

_to_selection_lists(self, index, source_model)[source]

See base class.

_update_actions_availability(self)[source]

See base class.

_open_scenario_generator(self)[source]

Opens the scenario generator dialog.

_toggle_checked_state(self)[source]

Toggles the checked state of selected alternatives.

header_changed[source]
property source_model(self)[source]
property db_mngr(self)[source]
connect_spine_db_editor(self, spine_db_editor)[source]
_change_context(self)[source]

Changes the UI engine according to pivot model type.

contextMenuEvent(self, event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

setModel(self, model)[source]
_fetch_more_visible(self)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtableview.FrozenTableView[source]

Bases: PySide2.QtWidgets.QTableView

header_dropped[source]
property area(self)[source]
dragEnterEvent(self, event)[source]
dragMoveEvent(self, event)[source]
dropEvent(self, event)[source]
spinetoolbox.spine_db_editor.widgets.custom_qtreeview

Classes for custom QTreeView.

author
  1. Marin (KTH)

date

25.4.2018

Module Contents
Classes

EntityTreeView

Tree view base class for object and relationship tree views.

ObjectTreeView

Custom QTreeView class for the object tree in SpineDBEditor.

RelationshipTreeView

Custom QTreeView class for the relationship tree in SpineDBEditor.

ItemTreeView

Base class for all non-entity tree views.

ToolFeatureTreeView

Custom QTreeView class for tools and features in SpineDBEditor.

AlternativeScenarioTreeView

Custom QTreeView class for the alternative scenario tree in SpineDBEditor.

ParameterValueListTreeView

Custom QTreeView class for parameter_value_list in SpineDBEditor.

class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.EntityTreeView(parent)[source]

Bases: spinetoolbox.widgets.custom_qtreeview.CopyTreeView

Tree view base class for object and relationship tree views.

Initialize the view.

tree_selection_changed[source]
connect_spine_db_editor(self, spine_db_editor)[source]

Connects a Spine db editor to work with this view.

Parameters

spine_db_editor (SpineDBEditor) –

_add_middle_actions(self)[source]

Adds action at the middle of the context menu. Subclasses can reimplement at will.

_create_context_menu(self)[source]

Creates a context menu for this view.

edit(self, index, trigger, event)[source]

Edit all selected items.

connect_signals(self)[source]

Connects signals.

rowsInserted(self, parent, start, end)[source]
rowsRemoved(self, parent, start, end)[source]
setModel(self, model)[source]
_fetch_more_visible(self)[source]
verticalScrollbarValueChanged(self, value)[source]
_handle_selection_changed(self, selected, deselected)[source]

Classifies selection by item type and emits signal.

_refresh_selected_indexes(self)[source]
clear_any_selections(self)[source]

Clears the selection if any.

fully_expand(self)[source]

Expands selected indexes and all their children.

fully_collapse(self)[source]

Collapses selected indexes and all their children.

export_selected(self)[source]

Exports data from selected indexes using the connected Spine db editor.

remove_selected(self)[source]

Removes selected indexes using the connected Spine db editor.

manage_relationships(self)[source]
show_entity_metadata(self)[source]

Shows entity’s metadata.

contextMenuEvent(self, event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

mousePressEvent(self, 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) –

_add_relationship_actions(self)[source]
update_actions_availability(self)[source]

Updates the visible property of actions according to whether or not they apply to given item.

edit_selected(self)[source]

Edits all selected indexes using the connected Spine db editor.

class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ObjectTreeView(parent)[source]

Bases: EntityTreeView

Custom QTreeView class for the object tree in SpineDBEditor.

Initialize the view.

update_actions_availability(self)[source]

Updates the visible property of actions according to whether or not they apply to given item.

_add_middle_actions(self)[source]

Adds action at the middle of the context menu. Subclasses can reimplement at will.

connect_signals(self)[source]

Connects signals.

rowsInserted(self, parent, start, end)[source]
add_object_classes(self)[source]
add_objects(self)[source]
add_relationship_classes(self)[source]
add_relationships(self)[source]
find_next_relationship(self)[source]

Finds the next occurrence of the relationship at the current index and expands it.

_do_find_next_relationship(self)[source]
duplicate_object(self)[source]

Duplicates the object at the current index using the connected Spine db editor.

add_object_group(self)[source]
manage_members(self)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.RelationshipTreeView(parent)[source]

Bases: EntityTreeView

Custom QTreeView class for the relationship tree in SpineDBEditor.

Initialize the view.

_add_middle_actions(self)[source]

Adds action at the middle of the context menu. Subclasses can reimplement at will.

update_actions_availability(self)[source]

Updates the visible property of actions according to whether or not they apply to given item.

add_relationship_classes(self)[source]
add_relationships(self)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ItemTreeView(parent)[source]

Bases: spinetoolbox.widgets.custom_qtreeview.CopyTreeView

Base class for all non-entity tree views.

Initialize the view.

connect_signals(self)[source]

Connects signals.

abstract remove_selected(self)[source]

Removes items selected in the view.

abstract update_actions_availability(self, item)[source]

Updates the visible property of actions according to whether or not they apply to given item.

connect_spine_db_editor(self, spine_db_editor)[source]
populate_context_menu(self)[source]

Creates a context menu for this view.

contextMenuEvent(self, event)[source]

Shows context menu.

Parameters

event (QContextMenuEvent) –

class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ToolFeatureTreeView(parent)[source]

Bases: ItemTreeView

Custom QTreeView class for tools and features in SpineDBEditor.

Initialize the view.

connect_spine_db_editor(self, spine_db_editor)[source]

see base class

remove_selected(self)[source]

See base class.

update_actions_availability(self, item)[source]

See base class.

dragMoveEvent(self, event)[source]
dragEnterEvent(self, event)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.AlternativeScenarioTreeView(parent)[source]

Bases: ItemTreeView

Custom QTreeView class for the alternative scenario tree in SpineDBEditor.

Initialize the view.

alternative_selection_changed[source]
connect_signals(self)[source]

Connects signals.

connect_spine_db_editor(self, spine_db_editor)[source]

see base class

populate_context_menu(self)[source]

See base class.

_db_map_alt_ids_from_selection(self, selection)[source]
_db_map_scen_alt_ids_from_selection(self, selection)[source]
_handle_selection_changed(self, selected, deselected)[source]

Emits alternative_selection_changed with the current selection.

remove_selected(self)[source]

See base class.

update_actions_availability(self, item)[source]

See base class.

dragMoveEvent(self, event)[source]
dragEnterEvent(self, event)[source]
_open_scenario_generator(self)[source]

Opens the scenario generator dialog.

class spinetoolbox.spine_db_editor.widgets.custom_qtreeview.ParameterValueListTreeView(parent)[source]

Bases: ItemTreeView

Custom QTreeView class for parameter_value_list in SpineDBEditor.

Initialize the view.

connect_spine_db_editor(self, spine_db_editor)[source]

see base class

populate_context_menu(self)[source]

Creates a context menu for this view.

update_actions_availability(self, item)[source]

See base class.

open_in_editor(self)[source]

Opens the parameter_value editor for the first selected cell.

remove_selected(self)[source]

See base class.

spinetoolbox.spine_db_editor.widgets.custom_qwidgets

Custom QWidgets.

author
  1. Marin (KTH)

date

13.5.2018

Module Contents
Classes

DataToValueFilterWidget

Filter widget class.

LazyFilterWidget

Filter widget class.

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

class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.DataToValueFilterWidget(parent, data_to_value, show_empty=True)[source]

Bases: spinetoolbox.widgets.custom_qwidgets.FilterWidgetBase

Filter widget class.

Init class.

Parameters
  • parent (QWidget) –

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

class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.LazyFilterWidget(parent, source_model, show_empty=True)[source]

Bases: spinetoolbox.widgets.custom_qwidgets.FilterWidgetBase

Filter widget class.

Init class.

Parameters
set_model(self)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.OpenFileButton(file_path, db_editor)[source]

Bases: PySide2.QtWidgets.QToolButton

A button to open files or show them in the folder.

open_file(self, checked=False)[source]
open_containing_folder(self, checked=False)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.OpenSQLiteFileButton(file_path, db_editor)[source]

Bases: OpenFileButton

A button to open sqlite files, show them in the folder, or add them to the project.

open_file(self, checked=False)[source]
class spinetoolbox.spine_db_editor.widgets.custom_qwidgets.ShootingLabel(origin, destination, parent=None, duration=1200)[source]

Bases: PySide2.QtWidgets.QLabel

_handle_value_changed(self, value)[source]
show(self)[source]
spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs

Classes for custom QDialogs to edit items in databases.

author
  1. Marin (KTH)

date

13.5.2018

Module Contents
Classes

EditOrRemoveItemsDialog

A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all

EditObjectClassesDialog

A dialog to query user's preferences for updating object classes.

EditObjectsDialog

A dialog to query user's preferences for updating objects.

EditRelationshipClassesDialog

A dialog to query user's preferences for updating relationship classes.

EditRelationshipsDialog

A dialog to query user's preferences for updating relationships.

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(self, 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.EditObjectClassesDialog(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 object classes.

Init class.

Parameters
  • parent (SpineDBEditor) – data store widget

  • db_mngr (SpineDBManager) – the manager to do the update

  • selected (set) – set of ObjectClassItem instances to edit

connect_signals(self)[source]

Connect signals to slots.

all_db_maps(self, row)[source]

Returns a list of db maps available for a given row. Used by ShowIconColorEditorMixin.

accept(self)[source]

Collect info from dialog and try to update items.

class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.EditObjectsDialog(parent, db_mngr, selected)[source]

Bases: EditOrRemoveItemsDialog

A dialog to query user’s preferences for updating objects.

Init class.

Parameters
  • parent (SpineDBEditor) – data store widget

  • db_mngr (SpineDBManager) – the manager to do the update

  • selected (set) – set of ObjectItem instances to edit

accept(self)[source]

Collect info from dialog and try to update items.

class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.EditRelationshipClassesDialog(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 relationship classes.

Init class.

Parameters
  • parent (SpineDBEditor) – data store widget

  • db_mngr (SpineDBManager) – the manager to do the update

  • selected (set) – set of RelationshipClassItem instances to edit

connect_signals(self)[source]

Connect signals to slots.

accept(self)[source]

Collect info from dialog and try to update items.

class spinetoolbox.spine_db_editor.widgets.edit_or_remove_items_dialogs.EditRelationshipsDialog(parent, db_mngr, selected, class_key)[source]

Bases: spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetRelationshipClassesMixin, spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetObjectsMixin, EditOrRemoveItemsDialog

A dialog to query user’s preferences for updating relationships.

Init class.

Parameters
  • parent (SpineDBEditor) – data store widget

  • db_mngr (SpineDBManager) – the manager to do the update

  • selected (set) – set of RelationshipItem instances to edit

  • class_key (tuple) – (class_name, object_class_name_list) for identifying the relationship_class

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

Collect info from dialog and try to remove items.

spinetoolbox.spine_db_editor.widgets.graph_layout_generator

Contains the GraphViewMixin class.

author
  1. Marin (KTH)

date

26.11.2018

Module Contents
Classes

ProgressBarWidget

GraphLayoutGenerator

Computes the layout for the Entity Graph View.

Functions

make_heat_map(x, y, values)

spinetoolbox.spine_db_editor.widgets.graph_layout_generator.make_heat_map(x, y, values)[source]
class spinetoolbox.spine_db_editor.widgets.graph_layout_generator.ProgressBarWidget[source]

Bases: PySide2.QtWidgets.QWidget

set_layout_generator(self, layout_generator)[source]
paintEvent(self, event)[source]
class spinetoolbox.spine_db_editor.widgets.graph_layout_generator.GraphLayoutGenerator(identifier, vertex_count, src_inds=(), dst_inds=(), spread=0, heavy_positions=None, iterations=12, weight_exp=- 2)[source]

Bases: PySide2.QtCore.QRunnable

Computes the layout for the Entity Graph View.

class Signals[source]

Bases: PySide2.QtCore.QObject

finished[source]
layout_available[source]
progressed[source]
msg[source]
stop(self, _checked=False)[source]
set_show_previews(self, checked)[source]
emit_layout_available(self, x, y)[source]
emit_finished(self)[source]
shortest_path_matrix(self)[source]

Returns the shortest-path matrix.

sets(self)[source]

Returns sets of vertex pairs indices.

run(self)[source]

Computes and returns x and y coordinates for each vertex in the graph, using VSGD-MS.

spinetoolbox.spine_db_editor.widgets.graph_view_mixin

Contains the GraphViewMixin class.

author
  1. Marin (KTH)

date

26.11.2018

Module Contents
Classes

GraphViewMixin

Provides the graph view for the DS form.

class spinetoolbox.spine_db_editor.widgets.graph_view_mixin.GraphViewMixin(*args, **kwargs)[source]

Provides the graph view for the DS form.

VERTEX_EXTENT = 64[source]
_ARC_WIDTH[source]
_ARC_LENGTH_HINT[source]
_stop_extending_graph(self, _=False)[source]
init_models(self)[source]
connect_signals(self)[source]

Connects signals.

receive_objects_added(self, db_map_data)[source]

Runs when objects are added to the db. Adds the new objects to the graph if needed.

Parameters

db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.

receive_relationships_added(self, db_map_data)[source]

Runs when relationships are added to the db. Adds the new relationships to the graph if needed.

Parameters

db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.

receive_object_classes_updated(self, db_map_data)[source]
receive_relationship_classes_updated(self, db_map_data)[source]
receive_objects_updated(self, db_map_data)[source]

Runs when objects are updated in the db. Refreshes names of objects in graph.

Parameters

db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.

receive_objects_removed(self, db_map_data)[source]

Runs when objects are removed from the db. Rebuilds graph if needed.

Parameters

db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.

receive_relationships_updated(self, db_map_data)[source]

Runs when relationships are updated in the db.

Parameters

db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.

receive_relationships_removed(self, db_map_data)[source]

Runs when relationships are removed from the db. Rebuilds graph if needed.

Parameters

db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.

restore_removed_entities(self, added_ids)[source]

Restores any entities that have been previously removed and returns their ids. This happens in the context of undo/redo.

Parameters

added_ids (set(int)) – Set of newly added ids.

Returns

set(int)

hide_removed_entities(self, db_map_data)[source]

Hides removed entities while saving them into a list attribute. This allows entities to be restored in case the user undoes the operation.

refresh_icons(self, db_map_data)[source]

Runs when entity classes are updated in the db. Refreshes icons of entities in graph.

Parameters

db_map_data (dict) – list of dictionary-items keyed by DiffDatabaseMapping instance.

_handle_entity_graph_visibility_changed(self, visible)[source]
rebuild_graph(self, selected=None)[source]

Stores the given selection of entity tree indexes and builds graph.

build_graph(self, persistent=False)[source]

Builds the graph.

Parameters

persistent (bool, optional) – If True, elements in the current graph (if any) retain their position in the new one.

_stop_layout_generators(self)[source]
_complete_graph(self, layout_gen_id, x, y)[source]
Parameters
  • layout_gen_id (object) –

  • x (list) – Horizontal coordinates

  • y (list) – Vertical coordinates

_get_selected_entity_ids(self)[source]

Returns a set of ids corresponding to selected entities in the trees.

Returns

selected object ids set: selected relationship ids

Return type

set

_get_all_relationships_for_graph(self, object_ids, relationship_ids)[source]
_update_graph_data(self)[source]

Updates data for graph according to selection in trees.

_update_src_dst_inds(self, object_id_lists)[source]
_get_parameter_positions(self, parameter_name)[source]
_make_layout_generator(self)[source]

Returns a layout generator for the current graph.

Returns

GraphLayoutGenerator

_make_new_items(self, x, y)[source]

Returns new items for the graph.

Parameters
  • x (list) –

  • y (list) –

_add_new_items(self)[source]
start_relationship(self, relationship_class, obj_item)[source]

Starts a relationship from the given object item.

Parameters
  • relationship_class (dict) –

  • obj_item (.graphics_items.ObjectItem) –

finalize_relationship(self, relationship_class, *object_items)[source]

Tries to add relationships between the given object items.

Parameters
  • relationship_class (dict) –

  • object_items (.graphics_items.ObjectItem) –

_begin_add_relationships(self)[source]
_end_add_relationships(self)[source]
add_objects_at_position(self, pos)[source]
get_pdf_file_path(self)[source]
closeEvent(self, event)[source]

Handle close window.

Parameters

event (QCloseEvent) – Closing event

spinetoolbox.spine_db_editor.widgets.manage_items_dialogs

Classes for custom QDialogs to add edit and remove database items.

author
  1. Marin (KTH)

date

13.5.2018

Module Contents
Classes

ManageItemsDialogBase

Init class.

ManageItemsDialog

A dialog with a CopyPasteTableView and a QDialogButtonBox. Base class for all

GetObjectClassesMixin

Provides a method to retrieve object classes for AddObjectsDialog and AddRelationshipClassesDialog.

GetObjectsMixin

Provides a method to retrieve objects for AddRelationshipsDialog and EditRelationshipsDialog.

GetRelationshipClassesMixin

Provides a method to retrieve relationship classes for AddRelationshipsDialog and EditRelationshipsDialog.

ShowIconColorEditorMixin

Provides methods to show an IconColorEditor upon request.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialogBase(parent, db_mngr)[source]

Bases: PySide2.QtWidgets.QDialog

Init class.

Parameters
make_table_view(self)[source]
connect_signals(self)[source]

Connect signals to slots.

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

Connect signals to slots.

_handle_model_data_changed(self, top_left, bottom_right, roles)[source]

Reimplement in subclasses to handle changes in model data.

set_model_data(self, index, data)[source]

Update model data.

_handle_model_reset(self)[source]

Resize columns and form.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetObjectClassesMixin[source]

Provides a method to retrieve object classes for AddObjectsDialog and AddRelationshipClassesDialog.

make_db_map_obj_cls_lookup(self)[source]
object_class_name_list(self, row)[source]

Return a list of object_class names present in all databases selected for given row. Used by ManageObjectsDelegate.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetObjectsMixin[source]

Provides a method to retrieve objects for AddRelationshipsDialog and EditRelationshipsDialog.

make_db_map_obj_lookup(self)[source]
object_name_list(self, row, column)[source]

Return a list of object names present in all databases selected for given row. Used by ManageRelationshipsDelegate.

class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.GetRelationshipClassesMixin[source]

Provides a method to retrieve relationship classes for AddRelationshipsDialog and EditRelationshipsDialog.

make_db_map_rel_cls_lookup(self)[source]
class spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ShowIconColorEditorMixin[source]

Provides methods to show an IconColorEditor upon request.

show_icon_color_editor(self, index)[source]
spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs

Classes for custom QDialogs to add edit and remove database items.

author
  1. Marin (KTH)

date

13.5.2018

Module Contents
Classes

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.

Functions

_batch_set_check_state(check_boxes, checked)

class spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs.MassSelectItemsDialog(parent, db_mngr, *db_maps)[source]

Bases: PySide2.QtWidgets.QDialog

A dialog to query a selection of dbs and items from the user.

Initialize class.

Parameters
_MARGIN = 3[source]
_ITEM_TYPES = ['object_class', 'relationship_class', 'parameter_value_list', 'parameter_definition', 'object',...[source]
_COLUMN_COUNT = 3[source]
_add_check_boxes(self, group_box, check_boxes)[source]
_handle_check_box_state_changed(self, _checked)[source]
spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs._batch_set_check_state(check_boxes, checked)[source]
class spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs.MassRemoveItemsDialog(parent, db_mngr, *db_maps)[source]

Bases: MassSelectItemsDialog

A dialog to query user’s preferences for mass removing db items.

Initialize class.

Parameters
accept(self)[source]
class spinetoolbox.spine_db_editor.widgets.mass_select_items_dialogs.MassExportItemsDialog(parent, db_mngr, *db_maps)[source]

Bases: MassSelectItemsDialog

A dialog to let users chose items for JSON export.

Initialize class.

Parameters
data_submitted[source]
accept(self)[source]
spinetoolbox.spine_db_editor.widgets.multi_spine_db_editor

Contains the MultiSpineDBEditor class.

author
  1. Marin (KTH)

date

12.12.2020

Module Contents
Classes

MultiSpineDBEditor

Database editor's tabbed main window.

_FileOpenToolBar

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

Creates a new MultiTabWindow of this type.

Returns

new MultiTabWindow

Return type

MultiTabWindow

others(self)[source]

List of other MultiTabWindows of the same type.

Returns

other MutliTabWindows windows

Return type

list of MultiTabWindow

_connect_tab_signals(self, 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(self, index)[source]

Disconnects signals from given tab.

Parameters

index (int) – tab index

Returns

True if signals were disconnected successfully, False otherwise

Return type

bool

_make_new_tab(self, 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(self, global_pos)[source]

Opens a context menu for the tool bar.

Parameters

global_pos (QPoint) – menu position on screen

make_context_menu(self, 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(self, button)[source]

Inserts given button to the ‘beginning’ of the status bar and decorates it with a shooting label.

Parameters

button (OpenFileButton) –

insert_sqlite_file_open_button(self, file_path)[source]
insert_file_open_button(self, file_path)[source]
_open_sqlite_url(self, url, codename)[source]

Opens sqlite url.

show_user_guide(self, checked=False)[source]

Opens Spine db editor documentation page in browser.

class spinetoolbox.spine_db_editor.widgets.multi_spine_db_editor._FileOpenToolBar(parent=None)[source]

Bases: PySide2.QtWidgets.QToolBar

preppend_widget(self, widget)[source]
remove_widget(self, widget)[source]
spinetoolbox.spine_db_editor.widgets.object_name_list_editor

Contains the ObjectNameListEditor class.

author
  1. Marin (KTH)

date

27.11.2019

Module Contents
Classes

SearchBarDelegate

A custom delegate to use with ObjectNameListEditor.

ObjectNameListEditor

A dialog to select the object name list for a relationship using Google-like search bars.

class spinetoolbox.spine_db_editor.widgets.object_name_list_editor.SearchBarDelegate[source]

Bases: PySide2.QtWidgets.QItemDelegate

A custom delegate to use with ObjectNameListEditor.

data_committed[source]
setModelData(self, editor, model, index)[source]
createEditor(self, parent, option, index)[source]
updateEditorGeometry(self, editor, option, index)[source]
close_editor(self, editor, index, model)[source]
eventFilter(self, editor, event)[source]
class spinetoolbox.spine_db_editor.widgets.object_name_list_editor.ObjectNameListEditor(parent, index, object_class_names, object_names_lists, current_object_names)[source]

Bases: spinetoolbox.spine_db_editor.widgets.manage_items_dialogs.ManageItemsDialog

A dialog to select the object name list for a relationship using Google-like search bars.

Initializes widget.

Parameters
  • parent (SpineDBEditor) –

  • index (QModelIndex) –

  • object_class_names (list) – string object_class names

  • object_names_lists (list) – lists of string object names

  • current_object_names (list) –

init_model(self, object_class_names, object_names_lists, current_object_names)[source]
accept(self)[source]
spinetoolbox.spine_db_editor.widgets.parameter_view_mixin

Contains the ParameterViewMixin class.

author
  1. Marin (KTH)

date

26.11.2018

Module Contents
Classes

ParameterViewMixin

Provides stacked parameter tables for the Spine db editor.

class spinetoolbox.spine_db_editor.widgets.parameter_view_mixin.ParameterViewMixin(*args, **kwargs)[source]

Provides stacked parameter tables for the Spine db editor.

connect_signals(self)[source]

Connects signals to slots.

init_models(self)[source]

Initializes models.

show_object_name_list_editor(self, index, rel_cls_id, db_map)[source]

Shows the object names list editor.

Parameters
  • index (QModelIndex) –

  • rel_cls_id (int) –

  • db_map (DiffDatabaseMapping) –

_set_default_parameter_data(self, 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(self, default_data)[source]
reset_filters(self)[source]

Resets filters.

_handle_graph_selection_changed(self, selected_items)[source]

Resets filter according to graph selection.

_handle_object_tree_selection_changed(self, selected_indexes)[source]

Resets filter according to object tree selection.

_handle_relationship_tree_selection_changed(self, selected_indexes)[source]

Resets filter according to relationship tree selection.

_handle_alternative_selection_changed(self, selected_db_map_alt_ids)[source]

Resets filter according to selection in alternative tree view.

restore_ui(self)[source]

Restores UI state from previous session.

save_window_state(self)[source]

Saves window state parameters (size, position, state) via QSettings.

receive_alternatives_updated(self, db_map_data)[source]
receive_parameter_definitions_added(self, db_map_data)[source]
receive_parameter_values_added(self, db_map_data)[source]
receive_parameter_definitions_updated(self, db_map_data)[source]
receive_parameter_values_updated(self, db_map_data)[source]
receive_object_classes_removed(self, db_map_data)[source]
receive_relationship_classes_removed(self, db_map_data)[source]
receive_parameter_definitions_removed(self, db_map_data)[source]
receive_parameter_values_removed(self, db_map_data)[source]
spinetoolbox.spine_db_editor.widgets.pivot_table_header_view

Contains custom QHeaderView for the pivot table.

author
  1. Marin (KTH)

date

2.12.2019

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: PySide2.QtWidgets.QHeaderView

Header view for the pivot table.

Parameters
  • orientation (int) – Qt.Horizontal or Qt.Vertical

  • area (str) – which pivot area the header represents: “columns”, “rows” or “frozen”

  • pivot_table_view (PivotTableView) – parent view

header_dropped[source]
property area(self)[source]
dragEnterEvent(self, event)[source]
dragMoveEvent(self, event)[source]
dropEvent(self, 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 (int) – Qt.Horizontal or Qt.Vertical

  • area (str) – which pivot area the header represents: “columns”, “rows” or “frozen”

  • pivot_table_view (PivotTableView) – parent view

_add_column_to_plot(self, action)[source]

Adds a single column to existing plot window.

_plot_column(self)[source]

Plots a single column not the selection.

_set_x_flag(self)[source]

Sets the X flag for a column.

contextMenuEvent(self, 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 (int) – Qt.Horizontal or Qt.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(self, event)[source]
spinetoolbox.spine_db_editor.widgets.scenario_generator

Contains a dialog for generating scenarios from selected alternatives.

authors

A.Soininen (VTT)

date

7.9.2021

Module Contents
Classes

_ScenarioNameResolution

Generic enumeration.

ScenarioGenerator

A dialog where users can generate scenarios from given alternatives.

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: PySide2.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(self)[source]

Generates scenarios and closes the dialog.

The operation may get cancelled by user if there are conflicts in scenario names.

_generate_scenarios(self, 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(self, 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

spinetoolbox.spine_db_editor.widgets.select_position_parameters_dialog

Classes for custom QDialogs to add items to databases.

author
  1. Marin (KTH)

date

13.5.2018

Module Contents
Classes

SelectPositionParametersDialog

ParameterNameDelegate

A delegate for the database name.

class spinetoolbox.spine_db_editor.widgets.select_position_parameters_dialog.SelectPositionParametersDialog(parent, pos_x_parameter, pos_y_parameter)[source]

Bases: PySide2.QtWidgets.QDialog

selection_made[source]
accept(self)[source]
_parameter_position_x(self)[source]
_parameter_position_y(self)[source]
class spinetoolbox.spine_db_editor.widgets.select_position_parameters_dialog.ParameterNameDelegate(parent, db_mngr, *db_maps)[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

A delegate for the database name.

setModelData(self, editor, model, index)[source]

Send signal.

setEditorData(self, editor, index)[source]

Do nothing. We’re setting editor data right away in createEditor.

updateEditorGeometry(self, editor, option, index)[source]
_close_editor(self, editor, index)[source]

Closes editor. Needed by SearchBarEditor.

createEditor(self, parent, option, index)[source]

Returns editor.

spinetoolbox.spine_db_editor.widgets.spine_db_editor

Contains the SpineDBEditor class.

author
  1. Marin (KTH)

date

26.11.2018

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: PySide2.QtWidgets.QMainWindow

Base class for SpineDBEditor (i.e. Spine database editor).

Initializes form.

Parameters

db_mngr (SpineDBManager) – The manager to use

msg[source]
msg_error[source]
file_exported[source]
sqlite_file_exported[source]
property toolbox(self)[source]
property settings_subgroup(self)[source]
property db_names(self)[source]
property first_db_map(self)[source]
property db_url_codenames(self)[source]
load_db_urls(self, db_url_codenames, create=False, update_history=True)[source]
init_add_undo_redo_actions(self)[source]
load_previous_urls(self, _=False)[source]
load_next_urls(self, _=False)[source]
open_db_file(self, _=False)[source]
add_db_file(self, _=False)[source]
create_db_file(self, _=False)[source]
_make_docks_menu(self)[source]

Returns a menu with all dock toggle/view actions. Called by self.add_main_menu().

Returns

QMenu

add_main_menu(self)[source]

Adds a menu with main actions to toolbar.

_browse_commits(self)[source]
connect_signals(self)[source]

Connects signals to slots.

update_undo_redo_actions(self, index)[source]
_replace_undo_redo_actions(self, new_undo_action, new_redo_action)[source]
_refresh_undo_redo_actions(self)[source]
update_commit_enabled(self, _clean=False)[source]
init_models(self)[source]

Initializes models.

add_message(self, msg)[source]

Pushes message to notification stack.

Parameters

msg (str) – String to show in the notification

Pushes link message to notification stack.

Parameters
  • msg (str) – String to show in notification

  • open_link (Callable, optional) – callback to invoke when notification’s link is opened

refresh_copy_paste_actions(self)[source]

Runs when menus are about to show. Enables or disables actions according to selection status.

copy(self, checked=False)[source]

Copies data to clipboard.

paste(self, checked=False)[source]

Pastes data from clipboard.

import_data(self, data)[source]
import_file(self, checked=False)[source]

Import file. It supports SQLite, JSON, and Excel.

import_from_json(self, file_path)[source]
import_from_sqlite(self, file_path)[source]
import_from_excel(self, file_path)[source]
show_mass_export_items_dialog(self, checked=False)[source]

Shows dialog for user to select dbs and items for export.

export_session(self, checked=False)[source]

Exports changes made in the current session as reported by DiffDatabaseMapping.

mass_export_items(self, db_map_item_types)[source]
duplicate_object(self, object_item)[source]

Duplicates the object at the given object tree model index.

Parameters

index (QModelIndex) –

export_data(self, 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

static _parse_db_map_metadata(db_map_metadata)[source]
show_db_map_entity_metadata(self, db_map_ids)[source]
show_db_map_parameter_value_metadata(self, db_map_ids)[source]
refresh_session(self, checked=False)[source]
commit_session(self, checked=False)[source]

Commits dirty database maps.

rollback_session(self, checked=False)[source]

Rolls back dirty datbase maps.

receive_session_committed(self, db_maps, cookie)[source]
receive_session_rolled_back(self, db_maps)[source]
receive_session_refreshed(self, db_maps)[source]
show_mass_remove_items_form(self, checked=False)[source]
show_parameter_value_editor(self, index, plain=False)[source]

Shows the parameter_value editor for the given index of given table view.

receive_error_msg(self, db_map_error_log)[source]
log_changes(self, action, item_type, db_map_data)[source]

Enables or disables actions and informs the user about what just happened.

receive_scenarios_added(self, db_map_data)[source]
receive_alternatives_added(self, db_map_data)[source]
receive_object_classes_added(self, db_map_data)[source]
receive_objects_added(self, db_map_data)[source]
receive_relationship_classes_added(self, db_map_data)[source]
receive_relationships_added(self, db_map_data)[source]
receive_entity_groups_added(self, db_map_data)[source]
receive_parameter_definitions_added(self, db_map_data)[source]
receive_parameter_values_added(self, db_map_data)[source]
receive_parameter_value_lists_added(self, db_map_data)[source]
receive_features_added(self, db_map_data)[source]
receive_tools_added(self, db_map_data)[source]
receive_tool_features_added(self, db_map_data)[source]
receive_tool_feature_methods_added(self, db_map_data)[source]
receive_scenarios_updated(self, db_map_data)[source]
receive_alternatives_updated(self, db_map_data)[source]
receive_object_classes_updated(self, db_map_data)[source]
receive_objects_updated(self, db_map_data)[source]
receive_relationship_classes_updated(self, db_map_data)[source]
receive_relationships_updated(self, db_map_data)[source]
receive_parameter_definitions_updated(self, db_map_data)[source]
receive_parameter_values_updated(self, db_map_data)[source]
receive_parameter_value_lists_updated(self, db_map_data)[source]
receive_features_updated(self, db_map_data)[source]
receive_tools_updated(self, db_map_data)[source]
receive_tool_features_updated(self, db_map_data)[source]
receive_tool_feature_methods_updated(self, db_map_data)[source]
receive_scenarios_removed(self, db_map_data)[source]
receive_alternatives_removed(self, db_map_data)[source]
receive_object_classes_removed(self, db_map_data)[source]
receive_objects_removed(self, db_map_data)[source]
receive_relationship_classes_removed(self, db_map_data)[source]
receive_relationships_removed(self, db_map_data)[source]
receive_entity_groups_removed(self, db_map_data)[source]
receive_parameter_definitions_removed(self, db_map_data)[source]
receive_parameter_values_removed(self, db_map_data)[source]
receive_parameter_value_lists_removed(self, db_map_data)[source]
receive_features_removed(self, db_map_data)[source]
receive_tools_removed(self, db_map_data)[source]
receive_tool_features_removed(self, db_map_data)[source]
receive_tool_feature_methods_removed(self, db_map_data)[source]
restore_ui(self)[source]

Restore UI state from previous session.

save_window_state(self)[source]

Save window state parameters (size, position, state) via QSettings.

tear_down(self)[source]

Performs clean up duties.

Returns

True if editor is ready to close, False otherwise

Return type

bool

_prompt_to_commit_changes(self)[source]

Prompts the user to commit or rollback changes to ‘dirty’ db maps.

Returns

QMessageBox status code

Return type

int

_get_commit_msg(self, 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(self, 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

closeEvent(self, event)[source]

Handle close window.

Parameters

event (QCloseEvent) – Closing event

scenario_items(self, db_map)[source]

Gathers scenario items from alternative scenario tree for given database.

Parameters

db_map (DiffDatabaseMapping) – database map

Returns

scenario items

Return type

list of CachedItem

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.parameter_view_mixin.ParameterViewMixin, 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

connect_signals(self)[source]

Connects signals to slots.

_restart_timer_refresh_tab_order(self, _visible=False)[source]
_refresh_tab_order(self)[source]
tabify_and_raise(self, docks)[source]

Tabifies docks in given list, then raises the first.

Parameters

docks (list) –

restore_dock_widgets(self)[source]

Docks all floating and or hidden QDockWidgets back to the window.

begin_style_change(self)[source]

Begins a style change operation.

end_style_change(self)[source]

Ends a style change operation.

apply_stacked_style(self, checked=False)[source]

Applies the stacked style, inspired in the former tree view.

apply_pivot_style(self, _action)[source]

Applies the pivot style, inspired in the former tabular view.

apply_graph_style(self, checked=False)[source]

Applies the graph style, inspired in the former graph view.

static _get_base_dir()[source]
spinetoolbox.spine_db_editor.widgets.tabular_view_header_widget

Contains TabularViewHeaderWidget class.

authors
  1. Vennström (VTT), M. Marin (KTH)

date

2.12.2019

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: PySide2.QtWidgets.QFrame

A draggable QWidget.

Parameters
  • identifier (str) –

  • area (str) – either “rows”, “columns”, or “frozen”

  • menu (FilterMenu, optional) –

  • parent (QWidget, optional) – Parent widget

header_dropped[source]
_H_MARGIN = 3[source]
_SPACING = 16[source]
property identifier(self)[source]
property area(self)[source]
mousePressEvent(self, event)[source]

Register drag start position

mouseMoveEvent(self, event)[source]

Start dragging action if needed

mouseReleaseEvent(self, event)[source]

Forget drag start position

dragEnterEvent(self, event)[source]
dropEvent(self, event)[source]
spinetoolbox.spine_db_editor.widgets.tabular_view_mixin

Contains TabularViewMixin class.

author
  1. Vennström (VTT)

date

1.11.2018

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.

_PARAMETER_VALUE = &Value[source]
_INDEX_EXPANSION = &Index[source]
_RELATIONSHIP = Re&lationship[source]
_SCENARIO_ALTERNATIVE = &Scenario[source]
_PARAMETER = parameter[source]
_ALTERNATIVE = alternative[source]
_INDEX = index[source]
populate_pivot_action_group(self)[source]
connect_signals(self)[source]

Connects signals to slots.

_connect_pivot_table_header_signals(self)[source]

Connects signals of pivot table’s header views.

init_models(self)[source]

Initializes models.

_set_model_data(self, index, value)[source]
property current_object_class_id_list(self)[source]
property current_object_class_name_list(self)[source]
property current_object_class_ids(self)[source]
static _is_class_index(index)[source]

Returns whether or not the given tree index is a class index.

Parameters

index (QModelIndex) – index from object or relationship tree

Returns

bool

_handle_pivot_action_triggered(self, action)[source]
_handle_pivot_table_visibility_changed(self, visible)[source]
_handle_frozen_table_visibility_changed(self, visible)[source]
_handle_object_tree_selection_changed(self, selected_indexes)[source]
_handle_relationship_tree_selection_changed(self, selected_indexes)[source]
_handle_entity_tree_current_changed(self, current_index)[source]
_update_class_attributes(self, 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(self)[source]

Returns a dict mapping db maps to a list of dict entity items in the current class.

Returns

dict

load_empty_relationship_data(self, db_map_class_objects=None)[source]

Returns a dict containing all possible relationships in the current class.

Parameters

db_map_class_objects (dict) –

Returns

Key is db_map-object_id tuple, value is None.

Return type

dict

load_full_relationship_data(self, db_map_relationships=None, action='add')[source]

Returns a dict of relationships 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(self)[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(self, 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(self, 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(self, 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(self, 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(self, 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(self, value)[source]
load_empty_expanded_parameter_value_data(self, 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(self, 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(self)[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(self)[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(self)[source]

Returns saved pivot preferences.

Returns

pivot tuple, or None if no preference stored

Return type

tuple, NoneType

do_reload_pivot_table(self)[source]

Reloads pivot table.

_can_build_pivot_table(self)[source]
clear_pivot_table(self)[source]
wipe_out_filter_menus(self)[source]
make_pivot_headers(self)[source]

Turns top left indexes in the pivot table into TabularViewHeaderWidget.

_resize_pivot_header_columns(self)[source]
make_frozen_headers(self)[source]

Turns indexes in the first row of the frozen table into TabularViewHeaderWidget.

create_filter_menu(self, identifier)[source]

Returns a filter menu for given given object_class identifier.

Parameters

identifier (int) –

Returns

TabularViewFilterMenu

create_header_widget(self, 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(self, dropped, catcher, position='')[source]

Updates pivots when a header is dropped.

Parameters
get_frozen_value(self, index)[source]

Returns the value in the frozen table corresponding to the given index.

Parameters

index (QModelIndex) –

Returns

tuple

change_frozen_value(self, current, previous)[source]

Sets the frozen value from selection in frozen table.

change_filter(self, identifier, valid_values, has_filter)[source]
reload_frozen_table(self)[source]

Resets the frozen model according to new selection in entity trees.

find_frozen_values(self, frozen)[source]

Returns a list of tuples containing unique values (object ids) for the frozen indexes (object_class ids).

Parameters

frozen (tuple(int)) – A tuple of currently frozen indexes

Returns

list(tuple(list(int)))

static refresh_table_view(table_view)[source]
update_filter_menus(self, action)[source]
receive_objects_added_or_removed(self, db_map_data, action)[source]
receive_relationships_added_or_removed(self, db_map_data, action)[source]
receive_parameter_definitions_added_or_removed(self, db_map_data, action)[source]
receive_alternatives_added_or_removed(self, db_map_data, action)[source]
receive_parameter_values_added_or_removed(self, db_map_data, action)[source]
receive_scenarios_added_or_removed(self, db_map_data, action)[source]
receive_db_map_data_updated(self, db_map_data, get_class_id)[source]
receive_classes_updated(self, db_map_data)[source]
receive_classes_removed(self, db_map_data)[source]
receive_alternatives_added(self, db_map_data)[source]

Reacts to alternatives added event.

receive_scenarios_added(self, db_map_data)[source]

Reacts to scenarios added event.

receive_objects_added(self, db_map_data)[source]

Reacts to objects added event.

receive_relationships_added(self, db_map_data)[source]

Reacts to relationships added event.

receive_parameter_definitions_added(self, db_map_data)[source]

Reacts to parameter definitions added event.

receive_parameter_values_added(self, db_map_data)[source]

Reacts to parameter values added event.

receive_alternatives_updated(self, db_map_data)[source]

Reacts to alternatives updated event.

receive_object_classes_updated(self, db_map_data)[source]

Reacts to object classes updated event.

receive_relationship_classes_updated(self, db_map_data)[source]

Reacts to relationship classes updated event.

receive_objects_updated(self, db_map_data)[source]

Reacts to objects updated event.

receive_relationships_updated(self, db_map_data)[source]

Reacts to relationships updated event.

receive_parameter_values_updated(self, db_map_data)[source]

Reacts to parameter values added event.

receive_parameter_definitions_updated(self, db_map_data)[source]

Reacts to parameter definitions updated event.

receive_scenarios_updated(self, db_map_data)[source]
receive_alternatives_removed(self, db_map_data)[source]

Reacts to alternatives removed event.

receive_scenarios_removed(self, db_map_data)[source]

Reacts to scenarios removed event.

receive_object_classes_removed(self, db_map_data)[source]

Reacts to object classes removed event.

receive_relationship_classes_removed(self, db_map_data)[source]

Reacts to relationship classes remove event.

receive_objects_removed(self, db_map_data)[source]

Reacts to objects removed event.

receive_relationships_removed(self, db_map_data)[source]

Reacts to relationships removed event.

receive_parameter_definitions_removed(self, db_map_data)[source]

Reacts to parameter definitions removed event.

receive_parameter_values_removed(self, db_map_data)[source]

Reacts to parameter values removed event.

receive_session_rolled_back(self, db_maps)[source]

Reacts to session rolled back event.

spinetoolbox.spine_db_editor.widgets.tree_view_mixin

Contains the TreeViewMixin class.

author
  1. Marin (KTH)

date

26.11.2018

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.

_object_classes_added[source]
_relationship_classes_added[source]
_object_classes_fetched[source]
_relationship_classes_fetched[source]

Emitted from fetcher thread, connected to Slots in GUI thread.

connect_signals(self)[source]

Connects signals to slots.

init_models(self)[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(self, indexes)[source]
_db_map_class_ids(self, indexes)[source]
export_selected(self, selected_indexes)[source]

Exports data from given indexes in the entity tree.

show_add_object_classes_form(self)[source]

Shows dialog to add new object classes.

show_add_objects_form(self, parent_item)[source]

Shows dialog to add new objects.

show_add_object_group_form(self, object_class_item)[source]

Shows dialog to add new object group.

show_manage_members_form(self, object_item)[source]

Shows dialog to manage an object group.

show_add_relationship_classes_form(self, parent_item)[source]

Shows dialog to add new relationship_class.

show_add_relationships_form(self, parent_item)[source]

Shows dialog to add new relationships.

show_manage_relationships_form(self, parent_item)[source]
edit_entity_tree_items(self, selected_indexes)[source]

Starts editing given indexes.

show_edit_object_classes_form(self, items)[source]
show_edit_objects_form(self, items)[source]
show_edit_relationship_classes_form(self, items)[source]
show_remove_alternative_tree_items_form(self)[source]

Shows form to remove items from object treeview.

show_edit_relationships_form(self, items)[source]
show_remove_entity_tree_items_form(self, selected_indexes)[source]

Shows form to remove items from object treeview.

update_export_enabled(self)[source]
log_changes(self, action, item_type, db_map_data)[source]

Enables or disables actions and informs the user about what just happened.

receive_alternatives_added(self, db_map_data)[source]
receive_scenarios_added(self, db_map_data)[source]
receive_object_classes_added(self, db_map_data)[source]
receive_objects_added(self, db_map_data)[source]
receive_relationship_classes_added(self, db_map_data)[source]
receive_relationships_added(self, db_map_data)[source]
receive_entity_groups_added(self, db_map_data)[source]
receive_parameter_value_lists_added(self, db_map_data)[source]
receive_features_added(self, db_map_data)[source]
receive_tools_added(self, db_map_data)[source]
receive_tool_features_added(self, db_map_data)[source]
receive_tool_feature_methods_added(self, db_map_data)[source]
receive_alternatives_updated(self, db_map_data)[source]
receive_scenarios_updated(self, db_map_data)[source]
receive_object_classes_updated(self, db_map_data)[source]
receive_objects_updated(self, db_map_data)[source]
receive_relationship_classes_updated(self, db_map_data)[source]
receive_relationships_updated(self, db_map_data)[source]
receive_parameter_value_lists_updated(self, db_map_data)[source]
receive_features_updated(self, db_map_data)[source]
receive_tools_updated(self, db_map_data)[source]
receive_tool_features_updated(self, db_map_data)[source]
receive_tool_feature_methods_updated(self, db_map_data)[source]
receive_alternatives_removed(self, db_map_data)[source]
receive_scenarios_removed(self, db_map_data)[source]
receive_object_classes_removed(self, db_map_data)[source]
receive_objects_removed(self, db_map_data)[source]
receive_relationship_classes_removed(self, db_map_data)[source]
receive_relationships_removed(self, db_map_data)[source]
receive_entity_groups_removed(self, db_map_data)[source]
receive_parameter_value_lists_removed(self, db_map_data)[source]
receive_features_removed(self, db_map_data)[source]
receive_tools_removed(self, db_map_data)[source]
receive_tool_features_removed(self, db_map_data)[source]
receive_tool_feature_methods_removed(self, db_map_data)[source]
restore_ui(self)[source]

Restores UI state from previous session.

save_window_state(self)[source]

Saves window state parameters (size, position, state) via QSettings.

spinetoolbox.spine_db_editor.widgets.url_toolbar

Contains the UrlToolBar class and helpers.

author
  1. Marin (KTH)

date

13.5.2020

Module Contents
Classes

UrlToolBar

class spinetoolbox.spine_db_editor.widgets.url_toolbar.UrlToolBar(db_editor)[source]

Bases: PySide2.QtWidgets.QToolBar

property line_edit(self)[source]
_add_open_project_url_menu(self)[source]
_update_ds_url_menu_enabled(self)[source]
_connect_project_item_model_signals(self, slot)[source]
_disconnect_project_item_model_signals(self, slot)[source]
_update_open_project_url_menu(self)[source]
_open_ds_url(self, action)[source]
add_main_menu(self, menu)[source]
_update_history_actions_availability(self)[source]
add_urls_to_history(self, db_urls)[source]

Adds url to history.

Parameters

db_urls (list of str) –

get_previous_urls(self)[source]

Returns previous urls in history.

Returns

list of str

get_next_urls(self)[source]

Returns next urls in history.

Returns

list of str

_handle_line_edit_return_pressed(self)[source]
set_current_urls(self, urls)[source]
Submodules
spinetoolbox.spine_db_editor.graphics_items

Classes for drawing graphics items on graph view’s QGraphicsScene.

authors
  1. Marin (KTH), P. Savolainen (VTT)

date

4.4.2018

Module Contents
Classes

EntityItem

Base class for ObjectItem and RelationshipItem.

RelationshipItem

Represents a relationship in the Entity graph.

ObjectItem

Represents an object in the Entity graph.

ArcItem

Connects a RelationshipItem to an ObjectItem.

CrossHairsItem

Creates new relationships directly in the graph.

CrossHairsRelationshipItem

Represents the relationship that's being created using the CrossHairsItem.

CrossHairsArcItem

Connects a CrossHairsRelationshipItem with the CrossHairsItem,

ObjectLabelItem

Provides a label for ObjectItem's.

Functions

make_figure_graphics_item(scene, z=0, static=True)

Creates a FigureCanvas and adds it to the given scene.

spinetoolbox.spine_db_editor.graphics_items.make_figure_graphics_item(scene, z=0, static=True)[source]

Creates a FigureCanvas and adds it to the given scene. Used for creating heatmaps and associated colorbars.

Parameters
  • scene (QGraphicsScene) –

  • z (int, optional) – z value. Defaults to 0.

  • static (bool, optional) – if True (the default) the figure canvas is not movable

Returns

the graphics item that represents the canvas Figure: the figure in the canvas

Return type

QGraphicsProxyWidget

class spinetoolbox.spine_db_editor.graphics_items.EntityItem(spine_db_editor, x, y, extent, db_map_entity_id)[source]

Bases: PySide2.QtWidgets.QGraphicsRectItem

Base class for ObjectItem and RelationshipItem.

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_entity_id (tuple) – db_map, entity id

abstract _make_tool_tip(self)[source]
abstract default_parameter_data(self)[source]
property entity_type(self)[source]
property entity_name(self)[source]
property entity_class_type(self)[source]
property entity_class_id(self)[source]
property entity_class_name(self)[source]
property db_map(self)[source]
property entity_id(self)[source]
property first_db_map(self)[source]
property display_data(self)[source]
property display_database(self)[source]
property db_maps(self)[source]
db_map_data(self, _db_map)[source]
db_map_id(self, _db_map)[source]
boundingRect(self)[source]
moveBy(self, dx, dy)[source]
_init_bg(self)[source]
refresh_icon(self)[source]

Refreshes the icon.

_set_renderer(self, renderer)[source]
shape(self)[source]

Returns a shape containing the entire bounding rect, to work better with icon transparency.

paint(self, painter, option, widget=None)[source]

Shows or hides the selection halo.

_paint_as_selected(self)[source]
_paint_as_deselected(self)[source]
add_arc_item(self, arc_item)[source]

Adds an item to the list of arcs.

Parameters

arc_item (ArcItem) –

apply_zoom(self, factor)[source]

Applies zoom.

Parameters

factor (float) – The zoom factor.

apply_rotation(self, angle, center)[source]

Applies rotation.

Parameters
  • angle (float) – The angle in degrees.

  • center (QPointF) – Rotates around this point.

block_move_by(self, dx, dy)[source]
mouseMoveEvent(self, event)[source]

Moves the item and all connected arcs.

Parameters

event (QGraphicsSceneMouseEvent) –

update_arcs_line(self)[source]

Moves arc items.

itemChange(self, change, value)[source]

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

the same value given as input

setVisible(self, on)[source]

Sets visibility status for this item and all arc items.

Parameters

on (bool) –

_make_menu(self)[source]
contextMenuEvent(self, e)[source]

Shows context menu.

Parameters

e (QGraphicsSceneMouseEvent) – Mouse event

class spinetoolbox.spine_db_editor.graphics_items.RelationshipItem(spine_db_editor, x, y, extent, db_map_entity_id)[source]

Bases: EntityItem

Represents a relationship in the Entity graph.

Initializes the item.

Parameters
  • spine_db_editor (GraphViewForm) – ‘owner’

  • x (float) – x-coordinate of central point

  • y (float) – y-coordinate of central point

  • extent (int) – preferred extent

  • db_map_entity_id (tuple) – db_map, relationship id

default_parameter_data(self)[source]

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

property entity_type(self)[source]
property object_class_id_list(self)[source]
property object_name_list(self)[source]
property object_id_list(self)[source]
property entity_class_name(self)[source]
property db_representation(self)[source]
_make_tool_tip(self)[source]
_init_bg(self)[source]
follow_object_by(self, dx, dy)[source]
add_arc_item(self, arc_item)[source]

Adds an item to the list of arcs.

Parameters

arc_item (ArcItem) –

itemChange(self, change, value)[source]

Rotates svg item if the relationship is 2D. This makes it possible to define e.g. an arow icon for relationships that express direction.

_rotate_svg_item(self)[source]
class spinetoolbox.spine_db_editor.graphics_items.ObjectItem(spine_db_editor, x, y, extent, db_map_entity_id)[source]

Bases: EntityItem

Represents an object in the Entity graph.

Initializes the item.

Parameters
  • spine_db_editor (GraphViewForm) – ‘owner’

  • x (float) – x-coordinate of central point

  • y (float) – y-coordinate of central point

  • extent (int) – preferred extent

  • db_map_entity_id (tuple) – db_map, object id

default_parameter_data(self)[source]

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

property entity_type(self)[source]
property db_representation(self)[source]
shape(self)[source]

Returns a shape containing the entire bounding rect, to work better with icon transparency.

update_name(self, name)[source]

Refreshes the name.

_make_tool_tip(self)[source]
block_move_by(self, dx, dy)[source]
mouseDoubleClickEvent(self, e)[source]
_make_menu(self)[source]
_duplicate(self)[source]
_refresh_relationship_classes(self)[source]
_populate_expand_collapse_menu(self, menu)[source]

Populates the ‘Expand’ or ‘Collapse’ menu.

Parameters

menu (QMenu) –

_populate_add_relationships_menu(self, menu)[source]

Populates the ‘Add relationships’ menu.

Parameters

menu (QMenu) –

_get_relationship_ids_to_expand_or_collapse(self, action)[source]
_expand(self, action)[source]
_collapse(self, action)[source]
_start_relationship(self, action)[source]
class spinetoolbox.spine_db_editor.graphics_items.ArcItem(rel_item, obj_item, width)[source]

Bases: PySide2.QtWidgets.QGraphicsPathItem

Connects a RelationshipItem to an ObjectItem.

Initializes item.

Parameters
  • rel_item (spinetoolbox.widgets.graph_view_graphics_items.RelationshipItem) – relationship item

  • obj_item (spinetoolbox.widgets.graph_view_graphics_items.ObjectItem) – object item

  • width (float) – Preferred line width

_make_pen(self)[source]
moveBy(self, dx, dy)[source]

Does nothing. This item is not moved the regular way, but follows the EntityItems it connects.

update_line(self)[source]
mousePressEvent(self, event)[source]

Accepts the event so it’s not propagated.

other_item(self, item)[source]
apply_zoom(self, factor)[source]

Applies zoom.

Parameters

factor (float) – The zoom factor.

class spinetoolbox.spine_db_editor.graphics_items.CrossHairsItem(*args, **kwargs)[source]

Bases: RelationshipItem

Creates new relationships directly in the graph.

Initializes the item.

Parameters
  • spine_db_editor (GraphViewForm) – ‘owner’

  • x (float) – x-coordinate of central point

  • y (float) – y-coordinate of central point

  • extent (int) – preferred extent

  • db_map_entity_id (tuple) – db_map, relationship id

property entity_class_name(self)[source]
property entity_name(self)[source]
_make_tool_tip(self)[source]
refresh_icon(self)[source]

Refreshes the icon.

set_plus_icon(self)[source]
set_check_icon(self)[source]
set_normal_icon(self)[source]
set_ban_icon(self)[source]
set_icon(self, unicode, color=0)[source]

Refreshes the icon.

mouseMoveEvent(self, event)[source]

Moves the item and all connected arcs.

Parameters

event (QGraphicsSceneMouseEvent) –

block_move_by(self, dx, dy)[source]
contextMenuEvent(self, e)[source]

Shows context menu.

Parameters

e (QGraphicsSceneMouseEvent) – Mouse event

class spinetoolbox.spine_db_editor.graphics_items.CrossHairsRelationshipItem(*args, **kwargs)[source]

Bases: RelationshipItem

Represents the relationship that’s being created using the CrossHairsItem.

Initializes the item.

Parameters
  • spine_db_editor (GraphViewForm) – ‘owner’

  • x (float) – x-coordinate of central point

  • y (float) – y-coordinate of central point

  • extent (int) – preferred extent

  • db_map_entity_id (tuple) – db_map, relationship id

_make_tool_tip(self)[source]
refresh_icon(self)[source]

Refreshes the icon.

contextMenuEvent(self, e)[source]

Shows context menu.

Parameters

e (QGraphicsSceneMouseEvent) – Mouse event

class spinetoolbox.spine_db_editor.graphics_items.CrossHairsArcItem(rel_item, obj_item, width)[source]

Bases: ArcItem

Connects a CrossHairsRelationshipItem with the CrossHairsItem, and with all the ObjectItem’s in the relationship so far.

Initializes item.

Parameters
  • rel_item (spinetoolbox.widgets.graph_view_graphics_items.RelationshipItem) – relationship item

  • obj_item (spinetoolbox.widgets.graph_view_graphics_items.ObjectItem) – object item

  • width (float) – Preferred line width

_make_pen(self)[source]
class spinetoolbox.spine_db_editor.graphics_items.ObjectLabelItem(entity_item)[source]

Bases: PySide2.QtWidgets.QGraphicsTextItem

Provides a label for ObjectItem’s.

Initializes item.

Parameters

entity_item (spinetoolbox.widgets.graph_view_graphics_items.EntityItem) – The parent item.

entity_name_edited[source]
setPlainText(self, text)[source]

Set texts and resets position.

Parameters

text (str) –

reset_position(self)[source]

Adapts item geometry so text is always centered.

spinetoolbox.spine_db_editor.main
Module Contents
Functions

main()

Launches Spine Db Editor as it's own application.

spinetoolbox.spine_db_editor.main.main()[source]

Launches Spine Db Editor as it’s own application.

Parameters

argv (list) – Command line arguments

spinetoolbox.spine_db_editor.scenario_generation

Contains functions for automatically generating scenarios from a set of alternatives.

authors

A.Soininen (VTT)

date

7.9.2021

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

tuples containing alternatives for each scenario

Return type

list of tuple

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 tuple

spinetoolbox.widgets

Init file for widgets package. Intentionally empty.

author
  1. Savolainen (VTT)

date

3.1.2018

Submodules
spinetoolbox.widgets.about_widget

A widget for presenting basic information about the application.

author
  1. Savolainen (VTT)

date

14.12.2017

Module Contents
Classes

AboutWidget

About widget class.

class spinetoolbox.widgets.about_widget.AboutWidget(toolbox)[source]

Bases: PySide2.QtWidgets.QWidget

About widget class.

Parameters

toolbox (ToolboxUI) – QMainWindow instance

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

Add license to QTextBrowser.

keyPressEvent(self, e)[source]

Close form when Escape, Enter, Return, or Space bar keys are pressed.

Parameters

e (QKeyEvent) – Received key press event.

closeEvent(self, event=None)[source]

Handle close window.

Parameters

event (QEvent) – Closing event if ‘X’ is clicked.

mousePressEvent(self, e)[source]

Save mouse position at the start of dragging.

Parameters

e (QMouseEvent) – Mouse event

mouseReleaseEvent(self, e)[source]

Save mouse position at the end of dragging.

Parameters

e (QMouseEvent) – Mouse event

mouseMoveEvent(self, 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.

author
  1. Savolainen (VTT)

date

19.1.2017

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: PySide2.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(self)[source]

Connect signals to slots.

handle_name_changed(self)[source]

Update label to show upcoming folder name.

handle_ok_clicked(self)[source]

Check that given item name is valid and add it to project.

abstract call_add_item(self)[source]

Creates new Item according to user’s selections.

Must be reimplemented by subclasses.

keyPressEvent(self, e)[source]

Close Setup form when escape key is pressed.

Parameters

e (QKeyEvent) – Received key press event.

closeEvent(self, 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.

author
  1. Marin (KTH)

date

13.5.2018

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: PySide2.QtWidgets.QWizard

A wizard to install & upgrade SpineOpt.

Initialize class.

Parameters

parent (QWidget) – the parent widget (SettingsWidget)

class spinetoolbox.widgets.add_up_spine_opt_wizard.IntroPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

nextId(self)[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.SelectJuliaPage(parent, julia_exe, julia_project)[source]

Bases: PySide2.QtWidgets.QWizardPage

initializePage(self)[source]
_select_julia_exe(self)[source]
_select_julia_project(self)[source]
nextId(self)[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.CheckPreviousInstallPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

isComplete(self)[source]
cleanupPage(self)[source]
initializePage(self)[source]
_handle_check_install_finished(self, ret)[source]
nextId(self)[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(self)[source]
_handle_spine_opt_add_up_finished(self, ret)[source]
nextId(self)[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.SuccessPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

initializePage(self)[source]
nextId(self)[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.FailurePage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

_handle_check_box_clicked(self, checked=False)[source]
initializePage(self)[source]
nextId(self)[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.TroubleshootProblemsPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

isComplete(self)[source]
_show_log(self, _=False)[source]
nextId(self)[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.TroubleshootSolutionPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

cleanupPage(self)[source]
initializePage(self)[source]
_initialize_page_solution1(self)[source]
_initialize_page_solution2(self)[source]
nextId(self)[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(self)[source]
_handle_registry_reset_finished(self, ret)[source]
nextId(self)[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(self)[source]
class spinetoolbox.widgets.add_up_spine_opt_wizard.TotalFailurePage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

nextId(self)[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.

author
  1. Soininen (VTT)

date

25.3.2020

Module Contents
Classes

ArrayEditor

Editor widget for Arrays.

class spinetoolbox.widgets.array_editor.ArrayEditor(parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

Editor widget for Arrays.

Parameters

parent (QWidget, optional) – parent widget

set_value(self, value)[source]

Sets the parameter_value for editing in this widget.

Parameters

value (Array) – value for editing

value(self)[source]

Returns the array currently being edited.

Returns

array

Return type

Array

_check_if_plotting_enabled(self, 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(self, type_name)[source]
open_value_editor(self, index)[source]

Opens an editor widget for array element.

Parameters

index (QModelIndex) – element’s index

_show_table_context_menu(self, position)[source]

Shows the table’s context menu.

Parameters

position (QPoint) – menu’s position on the table

_update_plot(self, topLeft=None, bottomRight=None, roles=None)[source]

Updates the plot widget.

_open_header_editor(self, column)[source]
spinetoolbox.widgets.array_value_editor

An editor dialog for Array elements.

author
  1. Soininen (VTT)

date

10.11.2020

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

See base class.

spinetoolbox.widgets.code_text_edit

Provides simple text editor for programming purposes.

author
  1. Marin (KTH)

date

28.1.2020

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: PySide2.QtWidgets.QPlainTextEdit

A plain text edit with syntax highlighting and line numbers.

insertFromMimeData(self, source)[source]
set_lexer_name(self, lexer_name)[source]
setDocument(self, doc)[source]
line_number_area_width(self)[source]
_update_line_number_area_width(self, _new_block_count=0)[source]
_update_line_number_area(self, rect, dy)[source]
resizeEvent(self, event)[source]
line_number_area_paint_event(self, ev)[source]
class spinetoolbox.widgets.code_text_edit.LineNumberArea(editor)[source]

Bases: PySide2.QtWidgets.QWidget

sizeHint(self)[source]
paintEvent(self, ev)[source]
spinetoolbox.widgets.commit_dialog

Classes for custom QDialogs to add edit and remove database items.

author
  1. Marin (KTH)

date

13.5.2018

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: PySide2.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(self)[source]

Called when text changes in the commit msg text edit. Enable/disable commit button accordingly.

spinetoolbox.widgets.console_window

Window for the ‘base’ Julia Console and Python Console.

author
  1. Savolainen (VTT)

date

5.2.2021

Module Contents
Classes

ConsoleWindow

Class for a separate window for the Python or Julia Console.

class spinetoolbox.widgets.console_window.ConsoleWindow(toolbox, spine_console, language)[source]

Bases: PySide2.QtWidgets.QMainWindow

Class for a separate window for the Python or Julia Console.

Parameters
  • toolbox (ToolboxUI) – QMainWindow instance

  • spine_console (JupyterConsoleWidget) – Qt Console

  • language (str) – ‘python’ or ‘julia’

start(self)[source]

Starts the kernel.

closeEvent(self, e)[source]

Shuts down the running kernel and calls ToolboxUI method to destroy this window.

Parameters

e (QCloseEvent) – Event

spinetoolbox.widgets.custom_combobox

A widget for presenting basic information about the application.

author
  1. Savolainen (VTT)

date

14.12.2017

Module Contents
Classes

ElidedCombobox

Combobox with elided text.

OpenProjectDialogComboBox

class spinetoolbox.widgets.custom_combobox.ElidedCombobox[source]

Bases: PySide2.QtWidgets.QComboBox

Combobox with elided text.

paintEvent(self, event)[source]
class spinetoolbox.widgets.custom_combobox.OpenProjectDialogComboBox[source]

Bases: PySide2.QtWidgets.QComboBox

keyPressEvent(self, 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.

author
  1. Marin (KTH)

date

1.9.2018

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: PySide2.QtWidgets.QStyledItemDelegate

createEditor(self, parent, option, index)[source]
paint(self, painter, option, index)[source]
setEditorData(self, editor, index)[source]
setModelData(self, editor, model, index)[source]
updateEditorGeometry(self, editor, option, index)[source]
_finalize_editing(self, editor)[source]
class spinetoolbox.widgets.custom_delegates.CheckBoxDelegate(parent, centered=True)[source]

Bases: PySide2.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(self, 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(self, painter, option, index)[source]

Paint a checkbox without the label.

static _do_paint(painter, checkbox_style_option, index)[source]
editorEvent(self, 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(self, editor, model, index)[source]

Do nothing. Model data is updated by handling the data_committed signal.

get_checkbox_rect(self, 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.

author
  1. Marin (KTH)

date

2.9.2018

Module Contents
Classes

CustomLineEditor

A custom QLineEdit to handle data from models.

ParameterValueLineEditor

A custom QLineEdit to handle data from models.

_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: PySide2.QtWidgets.QLineEdit

A custom QLineEdit to handle data from models.

set_data(self, data)[source]

Sets editor’s text.

Parameters

data (Any) – anything convertible to string

data(self)[source]

Returns editor’s text.

Returns

editor’s text

Return type

str

keyPressEvent(self, 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(self, data)[source]

Sets editor’s text.

Parameters

data (Any) – anything convertible to string

data(self)[source]

Returns editor’s text.

Returns

editor’s text

Return type

str

class spinetoolbox.widgets.custom_editors._CustomLineEditDelegate[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

A delegate for placing a CustomLineEditor on the first row of SearchBarEditor.

text_edited[source]
setModelData(self, editor, model, index)[source]
createEditor(self, parent, option, index)[source]

Create editor and ‘forward’ textEdited signal.

eventFilter(self, editor, event)[source]

Handle all sort of special cases.

class spinetoolbox.widgets.custom_editors.SearchBarEditor(parent, tutor=None)[source]

Bases: PySide2.QtWidgets.QTableView

A Google-like search bar, implemented as a QTableView with a _CustomLineEditDelegate in the first row.

Initializes instance.

Parameters
  • parent (QWidget) – parent widget

  • tutor (QWidget, optional) – another widget used for positioning.

data_committed[source]
set_data(self, current, items)[source]

Populates model.

Parameters
  • current (str) – item that is currently selected from given items

  • items (Sequence(str)) – items to show in the list

set_base_size(self, size)[source]
set_base_offset(self, offset)[source]
update_geometry(self)[source]

Updates geometry.

refit(self)[source]
data(self)[source]
_handle_delegate_text_edited(self, text)[source]

Filters model as the first row is being edited.

_proxy_model_filter_accepts_row(self, source_row, source_parent)[source]

Always accept first row.

keyPressEvent(self, event)[source]

Sets data from current index into first index as the user navigates through the table using the up and down keys.

currentChanged(self, current, previous)[source]
edit_first_index(self)[source]

Edits first index if valid and not already being edited.

mouseMoveEvent(self, event)[source]

Sets the current index to the one hovered by the mouse.

mousePressEvent(self, event)[source]

Commits data.

class spinetoolbox.widgets.custom_editors.CheckListEditor(parent, tutor=None, ranked=False)[source]

Bases: PySide2.QtWidgets.QTableView

A check list editor.

Initialize class.

_make_icon(self, i=None)[source]
keyPressEvent(self, event)[source]

Toggles checked state if the user presses space.

toggle_selected(self, index)[source]

Adds or removes given index from selected items.

Parameters

index (QModelIndex) – index to toggle

_select_item(self, qitem, rank)[source]
_deselect_item(self, qitem, update_ranks=False)[source]
mouseMoveEvent(self, event)[source]

Sets the current index to the one under mouse.

mousePressEvent(self, event)[source]

Toggles checked state of pressed index.

set_data(self, items, checked_items)[source]

Sets data and updates geometry.

Parameters
  • items (Sequence(str)) – All items.

  • checked_items (Sequence(str)) – Initially checked items.

data(self)[source]

Returns a comma separated list of checked items.

Returns

str

set_base_size(self, size)[source]
update_geometry(self)[source]

Updates geometry.

class spinetoolbox.widgets.custom_editors._IconPainterDelegate[source]

Bases: PySide2.QtWidgets.QStyledItemDelegate

A delegate to highlight decorations in a QListWidget.

paint(self, painter, option, index)[source]

Paints selected items using the highlight brush.

class spinetoolbox.widgets.custom_editors.IconColorEditor(parent)[source]

Bases: PySide2.QtWidgets.QDialog

An editor to let the user select an icon and a color for an object_class.

Init class.

_proxy_model_filter_accepts_row(self, source_row, source_parent)[source]

Filters icons according to search terms.

connect_signals(self)[source]

Connects signals to slots.

set_data(self, data)[source]
data(self)[source]
spinetoolbox.widgets.custom_menus

Classes for custom context menus and pop-up menus.

author
  1. Savolainen (VTT)

date

9.1.2018

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.

FilterMenuBase

Filter menu.

SimpleFilterMenu

Filter menu.

class spinetoolbox.widgets.custom_menus.CustomContextMenu(parent, position)[source]

Bases: PySide2.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(self, 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(self, option)[source]

Sets the action which was clicked.

Parameters

option (str) – string with the text description of the action

get_action(self)[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: PySide2.QtWidgets.QMenu

Popup menu master class for several popup menus.

Parameters

parent (QWidget) – Parent widget of this pop-up menu

add_action(self, text, slot, enabled=True, tooltip=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

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)

add_recent_projects(self)[source]

Reads the previous project names and paths from QSettings. Adds them to the QMenu as QActions.

call_open_project(self, 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.FilterMenuBase(parent)[source]

Bases: PySide2.QtWidgets.QMenu

Filter menu.

Parameters

parent (QWidget) – a parent widget

connect_signals(self)[source]
set_filter_list(self, data)[source]
add_items_to_filter_list(self, items)[source]
remove_items_from_filter_list(self, items)[source]
_clear_filter(self)[source]
_check_filter(self)[source]
_change_filter(self)[source]
abstract emit_filter_changed(self, valid_values)[source]
wipe_out(self)[source]
class spinetoolbox.widgets.custom_menus.SimpleFilterMenu(parent, show_empty=True)[source]

Bases: FilterMenuBase

Filter menu.

Parameters

parent (SpineDBEditor) –

filterChanged[source]
emit_filter_changed(self, valid_values)[source]
spinetoolbox.widgets.custom_qcombobox

Class for a custom QComboBox.

author
  1. Savolainen (VTT)

date

16.10.2020

Module Contents
Classes

CustomQComboBox

A custom QComboBox for showing kernels in Settings->Tools.

class spinetoolbox.widgets.custom_qcombobox.CustomQComboBox[source]

Bases: PySide2.QtWidgets.QComboBox

A custom QComboBox for showing kernels in Settings->Tools.

mouseMoveEvent(self, 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.

author
  1. Savolainen (VTT)

date

13.2.2019

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

item_removed[source]

Emitted when an item has been removed.

center_items(self)[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

mouseMoveEvent(self, event)[source]

Moves link drawer.

mousePressEvent(self, event)[source]

Puts link drawer to sleep and log message if it looks like the user doesn’t know what they’re doing.

mouseReleaseEvent(self, event)[source]

Makes link if drawer is released over a valid connector button.

emit_connection_failed(self)[source]
keyPressEvent(self, event)[source]

Puts link drawer to sleep if user presses ESC.

connect_signals(self)[source]

Connect scene signals.

project_item_icons(self)[source]
handle_selection_changed(self)[source]

Synchronizes selection with the project tree.

set_bg_color(self, color)[source]

Change background color when this is changed in Settings.

Parameters

color (QColor) – Background color

set_bg_choice(self, bg_choice)[source]

Set background choice when this is changed in Settings.

Parameters

bg (str) – “grid”, “tree”, or “solid”

dragLeaveEvent(self, event)[source]

Accept event.

dragEnterEvent(self, event)[source]

Accept event. Then call the super class method only if drag source is not a ProjectItemDragMixin.

dragMoveEvent(self, event)[source]

Accept event. Then call the super class method only if drag source is not a ProjectItemDragMixin.

dropEvent(self, 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(self, event)[source]

Accepts GraphicsSceneHelp events without doing anything, to not interfere with our usage of QToolTip.showText in graphics_items.ExclamationIcon.

drawBackground(self, 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(self, painter, rect)[source]

Draws solid bg.

_draw_grid_bg(self, painter, rect)[source]

Draws grid bg.

_draw_tree_bg(self, 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.

authors
  1. Savolainen (VTT), M. Marin (KTH)

date

6.2.2018

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: PySide2.QtWidgets.QGraphicsView

Super class for Design and Entity QGraphicsViews.

parent

Parent widget

Type

QWidget

Init CustomQGraphicsView.

property _qsettings(self)[source]
property zoom_factor(self)[source]
reset_zoom(self)[source]

Resets zoom to the default factor.

keyPressEvent(self, 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(self, event)[source]

Set rubber band selection mode if Control pressed. Enable resetting the zoom factor from the middle mouse button.

mouseReleaseEvent(self, event)[source]

Reestablish scroll hand drag mode.

_use_smooth_zoom(self)[source]
wheelEvent(self, event)[source]

Zooms in/out.

Parameters

event (QWheelEvent) – Mouse wheel event

resizeEvent(self, event)[source]

Updates zoom if needed when the view is resized.

Parameters

event (QResizeEvent) – a resize event

setScene(self, scene)[source]

Sets a new scene to this view.

Parameters

scene (ShrinkingScene) – a new scene

_handle_item_move_finished(self, item)[source]
_update_zoom_limits(self)[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(self)[source]
_handle_zoom_time_line_advanced(self, pos)[source]

Performs zoom whenever the smooth zoom time line advances.

_handle_transformation_time_line_finished(self)[source]

Cleans up after the smooth transformation time line finishes.

_handle_resize_time_line_finished(self)[source]

Cleans up after resizing time line finishes.

zoom_in(self)[source]

Perform a zoom in with a fixed scaling.

zoom_out(self)[source]

Perform a zoom out with a fixed scaling.

gentle_zoom(self, 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(self, factor)[source]
_get_viewport_scene_rect(self)[source]

Returns the viewport rect mapped to the scene.

Returns

QRectF

_ensure_item_visible(self, item)[source]

Resets zoom if item is not visible.

_set_preferred_scene_rect(self)[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(self)[source]
set_ui(self, toolbox)[source]

Set a new scene into the Design View when app is started.

reset_zoom(self)[source]

Resets zoom to the default factor.

_compute_max_zoom(self)[source]
add_icon(self, item_name)[source]

Adds project item’s icon to the scene.

Parameters

item_name (str) – project item’s name

remove_icon(self, 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
  • original_connection (Connection) – connection that was replaced

  • new_connection (Connection) – replacing connection

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(self, src_connector, dst_connector)[source]

Pushes an AddJumpCommand to the Toolbox undo stack.

Parameters
do_add_jump(self, jump)[source]

Adds given jump to the Design view.

Parameters

jump (Jump) – jump to add

do_replace_jump(self, original_jump, new_jump)[source]

Replaces a jump link on the Design view.

Parameters
  • original_jump (Jump) – jump that was replaced

  • new_jump (Jump) – replacing jump

do_remove_jump(self, jump)[source]

Removes a jump from the scene.

Parameters

jump (Jump) – link’s jump

contextMenuEvent(self, event)[source]

Shows context menu for the blank view

Parameters

event (QContextMenuEvent) – Event

spinetoolbox.widgets.custom_qlineedits

Classes for custom line edits.

authors
  1. Marin (KTH), P. Savolainen (VTT)

date

11.10.2018

Module Contents
Classes

PropertyQLineEdit

A custom QLineEdit for Project Item Properties.

CustomQLineEdit

A custom QLineEdit that accepts file drops and displays the path.

class spinetoolbox.widgets.custom_qlineedits.PropertyQLineEdit[source]

Bases: PySide2.QtWidgets.QLineEdit

A custom QLineEdit for Project Item Properties.

keyPressEvent(self, e)[source]

Overridden to catch and pass on the Undo and Redo commands when this line edit has the focus.

Parameters

e (QKeyEvent) – Event

setText(self, 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.

class spinetoolbox.widgets.custom_qlineedits.CustomQLineEdit[source]

Bases: PropertyQLineEdit

A custom QLineEdit that accepts file drops and displays the path.

parent

Parent for line edit widget

Type

QMainWindow

file_dropped[source]
dragEnterEvent(self, event)[source]

Accept a single file drop from the filesystem.

dragMoveEvent(self, event)[source]

Accept event.

dropEvent(self, event)[source]

Emit file_dropped signal with the file for the dropped url.

spinetoolbox.widgets.custom_qtableview

Custom QTableView classes that support copy-paste and the like.

author
  1. Marin (KTH)

date

18.5.2018

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

Bases: PySide2.QtWidgets.QTableView

Custom QTableView class with copy and paste methods.

keyPressEvent(self, event)[source]

Copies and pastes to and from clipboard in Excel-like format.

delete_content(self)[source]

Deletes content from editable indexes in current selection.

can_copy(self)[source]
copy(self)[source]

Copies current selection to clipboard in excel format.

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

Pastes clipboard data on selection, but not beyond. If data is smaller than selection, repeat data to fit selection.

paste_normal(self)[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) –

keyPressEvent(self, event)[source]

Shows the autofilter menu if the user presses Alt + Down.

Parameters

event (QEvent) –

setModel(self, 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) –

show_auto_filter_menu(self, logical_index)[source]

Called when user clicks on a horizontal section header. Shows/hides the auto filter widget.

Parameters

logical_index (int) –

class spinetoolbox.widgets.custom_qtableview.IndexedParameterValueTableViewBase[source]

Bases: CopyPasteTableView

Custom QTableView base class with copy and paste methods for indexed parameter values.

copy(self)[source]

Copies current selection to clipboard in CSV format.

abstract static _read_pasted_text(text)[source]

Reads CSV formatted table.

abstract paste(self)[source]

Pastes data from clipboard to selection.

class spinetoolbox.widgets.custom_qtableview.TimeSeriesFixedResolutionTableView[source]

Bases: IndexedParameterValueTableViewBase

A QTableView for fixed resolution time series table.

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

Bases: IndexedParameterValueTableViewBase

A QTableView class with for variable resolution time series and time patterns.

paste(self)[source]

Pastes data from clipboard.

_paste_two_columns(self, 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(self, 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[source]

Bases: IndexedParameterValueTableViewBase

Custom QTableView with copy and paste methods for single column tables.

copy(self)[source]

Copies current selection to clipboard in CSV format.

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

Bases: CopyPasteTableView

Custom QTableView with copy and paste methods for map tables.

copy(self)[source]

Copies current selection to clipboard in Excel compatible CSV format.

delete_content(self)[source]

Deletes content in current selection.

paste(self)[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.

author
  1. Savolainen (VTT)

date

6.2.2018

Module Contents
Classes

SignedTextDocument

param owner

The item that owns the document.

CustomQTextBrowser

Custom QTextBrowser class.

MonoSpaceFontTextBrowser

Custom QTextBrowser class.

class spinetoolbox.widgets.custom_qtextbrowser.SignedTextDocument(owner=None)[source]

Bases: PySide2.QtGui.QTextDocument

Parameters

owner (ProjectItem, optional) – The item that owns the document.

class spinetoolbox.widgets.custom_qtextbrowser.CustomQTextBrowser(parent)[source]

Bases: PySide2.QtWidgets.QTextBrowser

Custom QTextBrowser class.

Parameters

parent (QWidget) – Parent widget

set_override_document(self, document)[source]

Sets the given document as the current document.

Parameters

document (QTextDocument) –

restore_original_document(self)[source]

Restores the original document

scroll_to_bottom(self)[source]
append(self, 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(self, event)[source]

Reimplemented method to add a clear action into the default context menu.

Parameters

event (QContextMenuEvent) – Received event

property max_blocks(self)[source]

int: the upper limit of text blocks that can be appended to the widget.

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.

author
  1. Marin (KTH)

date

25.4.2018

Module Contents
Classes

CopyTreeView

Custom QTreeView class with copy 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.CopyTreeView(parent)[source]

Bases: PySide2.QtWidgets.QTreeView

Custom QTreeView class with copy support.

Initialize the view.

can_copy(self)[source]
copy(self)[source]

Copy current selection to clipboard in excel format.

class spinetoolbox.widgets.custom_qtreeview.SourcesTreeView(parent)[source]

Bases: PySide2.QtWidgets.QTreeView

Custom QTreeView class for ‘Sources’ in Tool specification editor widget.

parent

The parent of this view

Type

QWidget

Initialize the view.

files_dropped[source]
del_key_pressed[source]
dragEnterEvent(self, event)[source]

Accept file and folder drops from the filesystem.

dragMoveEvent(self, event)[source]

Accept event.

dropEvent(self, event)[source]

Emit files_dropped signal with a list of files for each dropped url.

keyPressEvent(self, event)[source]

Overridden method to make the view support deleting items with a delete key.

class spinetoolbox.widgets.custom_qtreeview.CustomTreeView(parent)[source]

Bases: PySide2.QtWidgets.QTreeView

Custom QTreeView class for Tool specification editor form to enable keyPressEvent.

parent

The parent of this view

Type

QWidget

Initialize the view.

del_key_pressed[source]
keyPressEvent(self, 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.

author
  1. Vennström (VTT)

date

4.12.2018

Module Contents
Classes

FilterWidgetBase

Filter widget class.

SimpleFilterWidget

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.

class spinetoolbox.widgets.custom_qwidgets.FilterWidgetBase(parent)[source]

Bases: PySide2.QtWidgets.QWidget

Filter widget class.

Init class.

Parameters

parent (QWidget) –

okPressed[source]
cancelPressed[source]
connect_signals(self)[source]
save_state(self)[source]

Saves the state of the FilterCheckboxListModel.

reset_state(self)[source]

Sets the state of the FilterCheckboxListModel to saved state.

clear_filter(self)[source]

Selects all items in FilterCheckBoxListModel.

has_filter(self)[source]

Returns true if any item is filtered in FilterCheckboxListModel false otherwise.

set_filter_list(self, data)[source]

Sets the list of items to filter.

_apply_filter(self)[source]

Apply current filter and save state.

_cancel_filter(self)[source]

Cancel current edit of filter and set the state to the stored state.

_filter_list(self)[source]

Filter list with current text.

_text_edited(self, 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.SimpleFilterWidget(parent, show_empty=True)[source]

Bases: FilterWidgetBase

Filter widget class.

Init class.

Parameters

parent (QWidget) –

class spinetoolbox.widgets.custom_qwidgets.CustomWidgetAction(parent=None)[source]

Bases: PySide2.QtWidgets.QWidgetAction

A QWidgetAction with custom hovering.

Class constructor.

Parameters

parent (QMenu) – the widget’s parent

_handle_hovered(self)[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(self, obj, ev)[source]
_handle_hovered(self)[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)[source]

Bases: PySide2.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)[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.

tool_bar
Type

QToolBar

Class constructor.

Parameters
  • text (str) –

  • parent (QWidget) – the widget’s parent

  • compact (bool) – if True, the widget uses the minimal space

paintEvent(self, 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: PySide2.QtWidgets.QToolBar

A custom tool bar for MenuItemToolBarWidget.

enabled_changed[source]
_align_buttons(self)[source]

Align all buttons to bottom so frames look good.

add_frame(self, left, right, title)[source]

Add frame around given actions, with given title.

Parameters
  • left (QAction) –

  • right (QAction) –

  • title (str) –

is_enabled(self)[source]
addActions(self, actions)[source]

Overriden method to customize tool buttons.

addAction(self, *args, **kwargs)[source]

Overriden method to customize the tool button.

sizeHint(self)[source]

Make room for frames if needed.

paintEvent(self, ev)[source]

Paint the frames.

_setup_action_button(self, 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

QAction

actionEvent(self, ev)[source]

Updates self._enabled: True if at least one non-separator action is enabled, False otherwise. Emits self.enabled_changed accordingly.

eventFilter(self, 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(self, ev)[source]

Navigates over the tool bar buttons.

hideEvent(self, 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(self)[source]
class spinetoolbox.widgets.custom_qwidgets.WrapLabel(text='', parent=None)[source]

Bases: PySide2.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: PySide2.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__(self, owner, name)[source]
__get__(self, obj, objtype=None)[source]
__set__(self, 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(self)[source]
_handle_copy_clicked(self, _=False)[source]
_add_msg(self, msg)[source]
_add_msg_warning(self, msg)[source]
_add_msg_error(self, msg)[source]
_add_msg_succes(self, msg)[source]
isComplete(self)[source]
cleanupPage(self)[source]
class spinetoolbox.widgets.custom_qwidgets.LabelWithCopyButton(text='', parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

A read only QLabel with a QToolButton that copies the text to clipboard.

spinetoolbox.widgets.datetime_editor

An editor widget for editing datetime database (relationship) parameter values.

author
  1. Soininen (VTT)

date

28.6.2019

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: PySide2.QtWidgets.QWidget

An editor widget for DateTime type parameter values.

parent

a parent widget

Type

QWidget

_change_datetime(self, new_datetime)[source]

Updates the internal DateTime value

set_value(self, value)[source]

Sets the value to be edited.

value(self)[source]

Returns the editor’s current value.

spinetoolbox.widgets.duration_editor

An editor widget for editing duration database (relationship) parameter values.

author
  1. Soininen (VTT)

date

28.6.2019

Module Contents
Classes

DurationEditor

An editor widget for Duration type parameter values.

class spinetoolbox.widgets.duration_editor.DurationEditor(parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

An editor widget for Duration type parameter values.

parent

a parent widget

Type

QWidget

_change_duration(self)[source]

Updates the value being edited.

set_value(self, value)[source]

Sets the value for editing.

value(self)[source]

Returns the current Duration.

spinetoolbox.widgets.indexed_value_table_context_menu

Context menus for parameter value editor widgets.

author
  1. Soininen (VTT)

date

5.7.2019

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

_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 = Open value editor...[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: PySide2.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(self)[source]

Adds default actions to the menu.

_first_row(self)[source]

Returns the first selected row.

Returns

index to the first row

Return type

int

_insert_multiple_rows_after(self)[source]

Prompts for row count, then inserts new rows below the current selection.

_insert_multiple_rows_before(self)[source]

Prompts for row count, then inserts new rows above the current selection.

_insert_single_row_after(self)[source]

Inserts a single row below the current selection.

_insert_single_row_before(self)[source]

Inserts a single row above the current selection.

_last_row(self)[source]

Returns the last selected row.

Returns

index to the last row

Return type

int

_prompt_row_count(self)[source]

Prompts for number of rows to insert.

Returns

number of rows

Return type

int

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

Returns the first selected column.

Returns

index to the first column

Return type

int

_insert_multiple_columns_after(self)[source]

Prompts for column count, then inserts new columns right from the current selection.

_insert_multiple_columns_before(self)[source]

Prompts for column count, then inserts new columns left from the current selection.

_insert_single_column_before(self)[source]

Inserts a single column left from the current selection.

_insert_single_column_after(self)[source]

Inserts a single column right from the current selection.

_last_column(self)[source]

Returns the last selected column.

Returns

index to the last column

Return type

int

_prompt_column_count(self)[source]

Prompts for number of column to insert.

Returns

number of columns

Return type

int

_remove_columns(self)[source]

Removes selected columns

_show_value_editor(self)[source]

Opens the value element editor.

_trim_columns(self)[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.

author
  1. Marin (KTH)

date

13.5.2018

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: PySide2.QtWidgets.QWizard

A wizard to install julia

Initialize class.

Parameters

parent (QWidget) – the parent widget (SettingsWidget)

julia_exe_selected[source]
set_julia_exe(self)[source]
accept(self)[source]
class spinetoolbox.widgets.install_julia_wizard.JillNotFoundPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

class spinetoolbox.widgets.install_julia_wizard.IntroPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

nextId(self)[source]
class spinetoolbox.widgets.install_julia_wizard.SelectDirsPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

initializePage(self)[source]
_select_install_dir(self)[source]
nextId(self)[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(self)[source]
initializePage(self)[source]
_handle_julia_install_finished(self, ret)[source]
nextId(self)[source]
class spinetoolbox.widgets.install_julia_wizard.SuccessPage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

initializePage(self)[source]
nextId(self)[source]
class spinetoolbox.widgets.install_julia_wizard.FailurePage(parent)[source]

Bases: PySide2.QtWidgets.QWizardPage

initializePage(self)[source]
nextId(self)[source]
spinetoolbox.widgets.jump_properties_widget

Contains jump properties widget’s business logic.

author
  1. Soininen (VTT)

date

23.6.2021

Module Contents
Classes

JumpPropertiesWidget

Widget for jump link properties.

class spinetoolbox.widgets.jump_properties_widget.JumpPropertiesWidget(toolbox)[source]

Bases: PySide2.QtWidgets.QWidget

Widget for jump link properties.

Parameters

toolbox (ToolboxUI) – The toolbox instance where this widget should be embedded

Hooks the widget to given link, so that user actions are reflected in the link’s configuration.

Parameters

link (JumpLink) – link to hook into

Releases the widget from any links.

set_condition(self, jump, condition)[source]
_change_condition(self)[source]

Stores jump condition to link.

spinetoolbox.widgets.jupyter_console_widget

Class for a custom RichJupyterWidget that can run Tool instances.

authors
  1. Marin (KTH), P. Savolainen (VTT)

date

22.10.2019

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

  • target_kernel_name (str) – Kernel name, e.g. ‘julia-1.6’

  • owner (ProjectItem, NoneType) – Item that owns the console.

name(self)[source]

Returns console name for display purposes.

property owner_names(self)[source]
start_console(self, checked=False)[source]

Starts chosen Python/Julia kernel if available and not already running. Context menu start action handler.

restart_console(self, checked=False)[source]

Restarts current Python/Julia kernel. Starts a new kernel if it is not running or if chosen kernel has been changed in Settings. Context menu restart action handler.

call_start_kernel(self)[source]

Finds a valid kernel and calls start_kernel() with it.

start_kernel(self, k_path)[source]

Starts a kernel manager and kernel client and attaches the client to this Console.

Parameters

k_path (str) – Directory where the the kernel specs are located

shutdown_kernel(self)[source]

Shut down Julia/Python kernel.

dragEnterEvent(self, e)[source]

Don’t accept project item drops.

_handle_status(self, msg)[source]

Handles status message.

enterEvent(self, event)[source]

Sets busy cursor during console (re)starts.

abstract _is_complete(self, source, interactive)[source]

See base class.

_context_menu_make(self, pos)[source]

Reimplemented to add actions to console context-menus.

copy_input(self)[source]

Copies only input.

_replace_client(self)[source]
connect_to_kernel(self, kernel_name, connection_file)[source]

Connects to an existing kernel. Used when Spine Engine is managing the kernel for project execution.

Parameters
  • kernel_name (str) –

  • connection_file (str) – Path to the connection file of the kernel

interrupt(self)[source]

[TODO: Remove?] Sends interrupt signal to kernel.

spinetoolbox.widgets.kernel_editor

Dialog for selecting a kernel or creating a new Julia or Python kernel.

author
  1. Savolainen (VTT)

date

7.10.2020

Module Contents
Classes

KernelEditorBase

Base class for kernel editors.

KernelEditor

Class for a Python and Julia kernel editor.

MiniKernelEditorBase

Base class for kernel editors.

MiniPythonKernelEditor

A reduced version of KernelEditor that basically just takes care of installing one Python kernel.

MiniJuliaKernelEditor

A reduced version of KernelEditor that basically just takes care of installing one Julia kernel.

Functions

find_kernels()

Returns a dictionary mapping kernel names to kernel paths.

find_python_kernels()

Returns a dictionary of Python kernels. Keys are kernel_names, values are kernel paths.

find_julia_kernels()

Returns a dictionary of Julia kernels. Keys are kernel_names, values are kernel paths.

find_unknown_kernels()

Returns a dictionary of kernels that are neither Python nor Julia kernels.

format_event_message(msg_type, message, show_datetime=True)

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: PySide2.QtWidgets.QDialog

Base class for kernel editors.

Parameters
  • parent (QSettingsWidget) – Toolbox settings widget

  • python_or_julia (str) – kernel type; valid values: “julia”, “python”

setup_dialog_style(self)[source]

Sets windows icon and stylesheet. This can be removed when SettingsWidget inherits stylesheet from ToolboxUI.

connect_signals(self)[source]

Connects signals to slots.

check_options(self, 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(self)[source]
abstract _python_kernel_display_name(self)[source]
abstract _python_interpreter_name(self)[source]
make_python_kernel(self, 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(self, 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(self, retval)[source]

Handles installing package finished.

Parameters

retval (int) – Process return value. 0: success, !0: failure

start_kernelspec_install_process(self, 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(self, 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(self)[source]
abstract _julia_executable(self)[source]
abstract _julia_project(self)[source]
make_julia_kernel(self, 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(self)[source]
is_ijulia_installed(self, 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(self, 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(self, ret)[source]

Runs when IJulia install process finishes.

Parameters

ret (int) – Process return value. 0: success, !0: failure

start_ijulia_rebuild_process(self, program, project)[source]

Starts rebuilding IJulia.

handle_ijulia_rebuild_finished(self, ret)[source]

Runs when IJulia rebuild process finishes.

Parameters

ret (int) – Process return value. 0: success, !0: failure

start_ijulia_installkernel_process(self, program, project, kernel_name)[source]

Installs the kernel using IJulia.installkernel function. Given kernel_name is actually the new kernel DISPLAY name. IJulia strips the whitespace and uncapitalizes this to make the kernel name automatically. Julia version is concatenated to both names automatically (This cannot be changed).

handle_installkernel_process_finished(self, retval)[source]

Checks whether or not the IJulia.installkernel process finished successfully.

Parameters

retval (int) – Process return value. 0: success, !0: failure

restore_dialog_dimensions(self)[source]

Restore widget location, dimensions, and state from previous session.

add_message(self, msg)[source]

Append regular message to kernel editor text browser.

Parameters

msg (str) – String written to QTextBrowser

add_success_message(self, msg)[source]

Append message with green text color to kernel editor text browser.

Parameters

msg (str) – String written to QTextBrowser

add_error_message(self, msg)[source]

Append message with red color to kernel editor text browser.

Parameters

msg (str) – String written to QTextBrowser

add_warning_message(self, msg)[source]

Append message with yellow (golden) color to kernel editor text browser.

Parameters

msg (str) – String written to QTextBrowser

add_process_message(self, msg)[source]

Writes message from stdout to kernel editor text browser.

Parameters

msg (str) – String written to QTextBrowser

add_process_error_message(self, msg)[source]

Writes message from stderr to kernel editor text browser.

Parameters

msg (str) – String written to QTextBrowser

_save_ui(self)[source]
class spinetoolbox.widgets.kernel_editor.KernelEditor(parent, python, julia, python_or_julia, current_kernel)[source]

Bases: KernelEditorBase

Class for a Python and Julia kernel editor.

Parameters
  • parent (QWidget) – Parent widget (Settings widget)

  • python (str) – Python interpreter, may be empty string

  • julia (str) – Julia executable, may be empty string

  • python_or_julia (str) – Setup KernelEditor according to selected mode

  • current_kernel (str) – Current selected Python or Julia kernel name

connect_signals(self)[source]

Connects signals to slots.

_julia_kernel_name(self)[source]
_julia_executable(self)[source]
_julia_project(self)[source]
_python_kernel_name(self)[source]
_python_kernel_display_name(self)[source]
_python_interpreter_name(self)[source]
_handle_kernel_selection_changed(self, _selected, _deselected)[source]
_update_ok_button_enabled(self)[source]
python_kernel_name_edited(self, txt)[source]

Updates the display name place holder text and the command QCustomLabel tool tip.

select_julia_clicked(self, checked=False)[source]

Opens file browser where user can select a Julia executable for the new kernel.

select_julia_project_clicked(self, checked=False)[source]

Opens file browser where user can select a Julia project path for the new kernel.

select_python_clicked(self, checked=False)[source]

Opens file browser where user can select the python interpreter for the new kernel.

update_python_cmd_tooltip(self)[source]

Updates Python command (CustomQLabel) tooltip according to selections.

update_julia_cmd_tooltip(self)[source]

Updates Julia command (CustomQLabel) tooltip according to selections.

set_kernel_selected(self, k_name)[source]

Finds row index of given kernel name from the model, sets it selected and scrolls the view so that it’s visible.

Parameters

k_name (str) – Kernel name to find and select

_check_kernel_is_ok(self, current, previous)[source]

Shows a notification if there are any known problems with selected kernel.

Parameters
  • current (QModelIndex) – Currently selected index

  • previous (QModelIndex) – Previously selected index

find_column(self, label)[source]

Returns the column number from the kernel model with the given label.

Parameters

label (str) – Header column label

Returns

Column number or -1 if label not found

Return type

int

check_options(self, 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

_is_rebuild_ijulia_needed(self)[source]
handle_kernelspec_install_process_finished(self, retval)[source]

Handles case when the process for installing the kernel has finished.

Parameters

retval (int) – Process return value. 0: success, !0: failure

handle_installkernel_process_finished(self, retval)[source]

Checks whether or not the IJulia.installkernel process finished successfully.

Parameters

retval (int) – Process return value. 0: success, !0: failure

populate_kernel_model(self)[source]

Populates the kernel model with kernels found in user’s system either with Python or Julia kernels. Unknows, invalid, and unsupported kernels are appended to the end.

static get_kernel_deats(kernel_path)[source]

Reads kernel.json from given kernel path and returns the details in a dictionary.

Parameters

kernel_path (str) – Full path to kernel directory

Returns

language (str), path to interpreter (str), display name (str), project (str) (NA for Python kernels)

Return type

dict

show_kernel_list_context_menu(self, pos)[source]

Shows the context-menu in the kernel list table view.

_open_kernel_json(self, checked=False)[source]

Opens kernel.json file using the default application for .json files.

_open_kernel_dir(self, checked=False)[source]

Opens kernel directory in OS file browser.

_remove_kernel(self, checked=False)[source]

Removes selected kernel by deleting the kernel directory.

mousePressEvent(self, e)[source]

Saves mouse position at the start of dragging.

Parameters

e (QMouseEvent) – Mouse event

mouseReleaseEvent(self, e)[source]

Saves mouse position at the end of dragging.

Parameters

e (QMouseEvent) – Mouse event

mouseMoveEvent(self, e)[source]

Moves the window when mouse button is pressed and mouse cursor is moved.

Parameters

e (QMouseEvent) – Mouse event

done(self, r)[source]

Overridden QDialog method. Sets the selected kernel instance attribute so that it can be read by the SettingsForm after this dialog has been closed.

Parameters

r (int) –

closeEvent(self, event=None)[source]

Handles dialog closing.

Parameters

event (QCloseEvent) – Close event

class spinetoolbox.widgets.kernel_editor.MiniKernelEditorBase(parent, python_or_julia)[source]

Bases: KernelEditorBase

Base class for kernel editors.

Parameters
  • parent (QSettingsWidget) – Toolbox settings widget

  • python_or_julia (str) – kernel type; valid values: “julia”, “python”

_python_interpreter_name(self)[source]
_julia_executable(self)[source]
_julia_project(self)[source]
_show_close_button(self, failed=False)[source]
make_kernel(self)[source]
abstract _do_make_kernel(self)[source]
class spinetoolbox.widgets.kernel_editor.MiniPythonKernelEditor(parent, python_exe)[source]

Bases: MiniKernelEditorBase

A reduced version of KernelEditor that basically just takes care of installing one Python kernel. The python exe is passed in the constructor, then calling make_kernel starts the process.

Parameters
  • parent (QSettingsWidget) – Toolbox settings widget

  • python_or_julia (str) – kernel type; valid values: “julia”, “python”

_python_kernel_name(self)[source]
_python_kernel_display_name(self)[source]
_do_make_kernel(self)[source]
handle_kernelspec_install_process_finished(self, retval)[source]

Handles case when the process for installing the kernel has finished.

Parameters

retval (int) – Process return value. 0: success, !0: failure

class spinetoolbox.widgets.kernel_editor.MiniJuliaKernelEditor(parent, julia_exe, julia_project)[source]

Bases: MiniKernelEditorBase

A reduced version of KernelEditor that basically just takes care of installing one Julia kernel. The julia exe and project are passed in the constructor, then calling make_kernel starts the process.

Parameters
  • parent (QSettingsWidget) – Toolbox settings widget

  • python_or_julia (str) – kernel type; valid values: “julia”, “python”

_julia_kernel_name(self)[source]
_do_make_kernel(self)[source]
handle_installkernel_process_finished(self, retval)[source]

Checks whether or not the IJulia.installkernel process finished successfully.

Parameters

retval (int) – Process return value. 0: success, !0: failure

spinetoolbox.widgets.kernel_editor.find_kernels()[source]

Returns a dictionary mapping kernel names to kernel paths.

spinetoolbox.widgets.kernel_editor.find_python_kernels()[source]

Returns a dictionary of Python kernels. Keys are kernel_names, values are kernel paths.

spinetoolbox.widgets.kernel_editor.find_julia_kernels()[source]

Returns a dictionary of Julia kernels. Keys are kernel_names, values are kernel paths.

spinetoolbox.widgets.kernel_editor.find_unknown_kernels()[source]

Returns a dictionary of kernels that are neither Python nor Julia kernels.

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.

author
  1. Soininen (VTT)

date

11.2.2020

Module Contents
Classes

MapEditor

A widget for editing maps.

class spinetoolbox.widgets.map_editor.MapEditor(parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

A widget for editing maps.

parent
Type

QWidget

_convert_leaves(self, _)[source]
_show_table_context_menu(self, position)[source]

Opens table context menu.

Parameters

position (QPoint) – menu’s position

set_value(self, value)[source]

Sets the parameter_value to be edited.

value(self)[source]

Returns the parameter_value currently being edited.

open_value_editor(self, index)[source]

Opens value editor dialog for given map model index.

Parameters

index (QModelIndex) – index

_open_header_editor(self, column)[source]
spinetoolbox.widgets.map_value_editor

An editor dialog for map indexes and values.

author
  1. Soininen (VTT)

date

2.11.2020

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

See base class.

spinetoolbox.widgets.multi_tab_spec_editor

Contains the MultiTabSpecEditor class.

author
  1. Marin (KTH)

date

12.12.2020

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

_make_other(self)[source]

Creates a new MultiTabWindow of this type.

Returns

new MultiTabWindow

Return type

MultiTabWindow

others(self)[source]

List of other MultiTabWindows of the same type.

Returns

other MutliTabWindows windows

Return type

list of MultiTabWindow

_make_new_tab(self, *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

property new_tab_title(self)[source]

Title for new tabs.

show_plus_button_context_menu(self, 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.

author
  1. Marin (KTH)

date

12.12.2020

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

_tab_slots[source]
abstract _make_other(self)[source]

Creates a new MultiTabWindow of this type.

Returns

new MultiTabWindow

Return type

MultiTabWindow

abstract others(self)[source]

List of other MultiTabWindows of the same type.

Returns

other MutliTabWindows windows

Return type

list of MultiTabWindow

abstract _make_new_tab(self, *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(self, global_pos)[source]

Opens a context menu for the tool bar.

Parameters

global_pos (QPoint) – menu position on screen

property new_tab_title(self)[source]

Title for new tabs.

connect_signals(self)[source]

Connects window’s signals.

name(self)[source]

Generates name based on the current tab and total tab count.

Returns

a name

Return type

str

all_tabs(self)[source]

Iterates over tab contents widgets.

Yields

QWidget – tab contents widget

add_new_tab(self, *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(self, 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(self, tab, text)[source]

Appends a new tab and connects signals.

Parameters
  • tab (QWidget) – tab contents widget

  • text (str) – appended tab title

_insert_connect_tab(self, 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(self, index)[source]

Disconnects and removes a tab.

Parameters

index (int) – tab index

_connect_tab(self, index)[source]

Connects signals from a tab contents widget.

Parameters

index (int) – tab index

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

Calculates the total ‘thickness’ of window frame in vertical direction.

Returns

frame height

Return type

int

timerEvent(self, 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(self, event)[source]

Stops the drag. This only happens when the detached tab is not reattached to another window.

reattach(self, 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.

_close_tab(self, index)[source]

Closes the tab at index.

Parameters

index (int) – tab index

set_current_tab(self, tab)[source]

Sets the tab that is shown on the window.

Parameters

tab (QWidget) – tab’s contents widget

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

Restore UI state from previous session.

save_window_state(self)[source]

Save window state parameters (size, position, state) via QSettings.

closeEvent(self, event)[source]
class spinetoolbox.widgets.multi_tab_window.TabBarPlus(parent)[source]

Bases: PySide2.QtWidgets.QTabBar

Tab bar that has a plus button floating to the right of the tabs.

Parameters

parent (MultiSpineDBEditor) –

plus_clicked[source]
resizeEvent(self, event)[source]

Sets the dimension of the plus button. Also, makes the tab bar as wide as the parent.

tabLayoutChange(self)[source]
_move_plus_button(self)[source]

Places the plus button at the right of the last tab.

mousePressEvent(self, event)[source]

Registers the position of the press, in case we need to detach the tab.

mouseMoveEvent(self, 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(self, pos)[source]

Sends a mouse release event at given position in local coordinates. Called just before detaching a tab.

Parameters

pos (QPoint) –

mouseReleaseEvent(self, event)[source]
start_dragging(self, index)[source]

Stars dragging the given index. This happens when a detached tab is reattached to this bar.

Parameters

index (int) –

index_under_mouse(self)[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(self, event)[source]
spinetoolbox.widgets.notification

Contains a notification widget.

author
  1. Savolainen (VTT)

date

12.12.2019

Module Contents
Classes

Notification

Custom pop-up notification widget with fade-in and fade-out effect.

InteractiveNotification

A notification that doesn't dissapear when the cursor is on it.

ButtonNotification

A notification with a button.

LinkNotification

A notification that may have a link.

NotificationStack

ChangeNotifier

param parent

class spinetoolbox.widgets.notification.Notification(parent, txt, anim_duration=500, life_span=None, word_wrap=True, corner=Qt.TopRightCorner)[source]

Bases: PySide2.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) –

opacity[source]
show(self)[source]
get_opacity(self)[source]

opacity getter.

set_opacity(self, op)[source]

opacity setter.

update_opacity(self, value)[source]

Updates graphics effect opacity.

start_self_destruction(self)[source]

Starts fade-out animation and closing of the notification.

enterEvent(self, e)[source]
dragEnterEvent(self, e)[source]
remaining_time(self)[source]
class spinetoolbox.widgets.notification.InteractiveNotification(parent, txt, anim_duration=500, life_span=None, word_wrap=True, corner=Qt.TopRightCorner)[source]

Bases: Notification

A notification that doesn’t dissapear when the cursor is on it.

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

enterEvent(self, e)[source]

Pauses timer as the mouse hovers the notification.

leaveEvent(self, e)[source]

Starts self destruction after the mouse leaves the notification.

class spinetoolbox.widgets.notification.ButtonNotification(*args, button_text='', button_slot=None, **kwargs)[source]

Bases: InteractiveNotification

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

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.NotificationStack(parent, anim_duration=500, life_span=None)[source]

Bases: PySide2.QtCore.QObject

push_notification(self, notification)[source]

Pushes a notification to the stack with the given text.

push(self, txt)[source]
handle_notification_destroyed(self, notification, height)[source]

Removes from the stack the given notification and move up subsequent ones.

class spinetoolbox.widgets.notification.ChangeNotifier(parent, undo_stack, settings, settings_key, corner=Qt.BottomLeftCorner)[source]

Bases: PySide2.QtCore.QObject

Parameters
  • parent (QWidget) –

  • undo_stack (QUndoStack) –

  • settings (QSettings) –

  • settings_key (str) –

_push_notification(self, index)[source]
spinetoolbox.widgets.open_project_widget

Contains a class for a widget that represents a ‘Open Project Directory’ dialog.

author
  1. Savolainen (VTT)

date

1.11.2019

Module Contents
Classes

OpenProjectDialog

A dialog that let's 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: PySide2.QtWidgets.QDialog

A dialog that let’s 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(self)[source]

Creates keyboard shortcuts for the ‘Root’, ‘Home’, etc. buttons.

connect_signals(self)[source]

Connects signals to slots.

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

Changes the combobox border color according to the current state of the validator.

current_index_changed(self, 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(self, 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(self, 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(self, text)[source]

Updates selected path when combobox text is edited. Note: pressing enter in combobox does not trigger this.

selection(self)[source]

Returns the selected path from dialog.

go_root(self, 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(self, checked=False)[source]

Slot for the ‘Home’ button. Scrolls the treeview to show and select the user’s home directory.

go_documents(self, checked=False)[source]

Slot for the ‘Documents’ button. Scrolls the treeview to show and select the user’s documents directory.

go_desktop(self, checked=False)[source]

Slot for the ‘Desktop’ button. Scrolls the treeview to show and select the user’s desktop directory.

open_project(self, 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(self, 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(self, pos)[source]

Shows the context menu for the QCombobox with a ‘Clear history’ entry.

Parameters

pos (QPoint) – Mouse position

closeEvent(self, event=None)[source]

Handles dialog closing.

Parameters

event (QCloseEvent) – Close event

class spinetoolbox.widgets.open_project_widget.CustomQFileSystemModel[source]

Bases: PySide2.QtWidgets.QFileSystemModel

Custom file system model.

columnCount(self, parent=QModelIndex())[source]

Returns one.

class spinetoolbox.widgets.open_project_widget.DirValidator(parent=None)[source]

Bases: PySide2.QtGui.QValidator

validate(self, 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.

author
  1. Soininen (VTT)

date

28.6.2019

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

See base class.

spinetoolbox.widgets.parameter_value_editor_base

A base for editor windows for editing parameter values.

author
  1. Soininen (VTT)

date

2.11.2020

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: PySide2.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(self)[source]

Saves the parameter_value shown in the currently selected editor widget to the database manager.

_change_parameter_type(self, 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(self, value)[source]

Shows the editor widget corresponding to the given value type on the editor stack.

_use_default_editor(self, message=None)[source]

Opens the default editor widget. Optionally, displays a warning dialog indicating the problem.

Parameters

message (str, optional) –

_use_editor(self, 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(self, 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

PersistentConsoleLineEdit

A line edit for the prompt of PersistentConsoleWidget.

PersistentConsoleWidget

A widget to interact with a persistent process.

PersistentRunnableBase

Base class for runnables that talk to the persistent process in another QThread.

Restarter

A runnable that restarts a persistent process.

Interrupter

A runnable that interrupts a persistent process.

CommandIssuer

A runnable that issues a command.

class spinetoolbox.widgets.persistent_console_widget.PersistentConsoleLineEdit(parent)[source]

Bases: PySide2.QtWidgets.QPlainTextEdit

A line edit for the prompt of PersistentConsoleWidget.

This widget is fully transparent. It’s only there to provide user interaction. The contents are constantly reflected in the console widget.

Parameters

parent (PersistentConsoleWidget) –

_adjust_size(self)[source]
_get_current_text(self)[source]

Returns current text.

Returns

the complete text str: the text before the cursor (for autocompletion)

Return type

str

keyPressEvent(self, ev)[source]
class spinetoolbox.widgets.persistent_console_widget.PersistentConsoleWidget(toolbox, key, language, owner=None)[source]

Bases: PySide2.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

name(self)[source]

Returns console name for display purposes.

property owner_names(self)[source]
_make_prompt(self)[source]
_make_cont_prompt(self)[source]
_reposition_line_edit(self)[source]

Moves line edit vertically to the position of the last block.

_insert_formatted_text(self, cursor, text)[source]

Inserts formatted text.

Parameters
  • cursor (QTextCursor) –

  • text (str) –

reflect_line_edit_contents(self)[source]

Reflects contents of line edit.

move_history(self, text, step)[source]

Moves history.

Parameters
  • text (str) –

  • step (int) –

autocomplete(self, text, partial_text)[source]

Autocompletes current text in the prompt (or print options if multiple matches).

Parameters
  • text (str) –

  • partial_text (str) –

_commit_line_edit(self)[source]

Clears line edit and moves it to the end of the document.

issue_command(self, text)[source]

Issues command.

Parameters

text (str) –

_scroll_to_bottom(self)[source]
_cursor_at_start_of_prompt(self)[source]

Returns a cursor at the start of the prompt.

Returns

QTextCursor

_insert_text_before_prompt(self, text, with_prompt=False, text_format=QTextCharFormat())[source]

Inserts given text before the prompt. Used when adding input and output from external execution.

Parameters

text (str) –

add_stdin(self, data)[source]

Adds new prompt with data. Used when adding stdin from external execution.

Parameters

data (str) –

add_stdout(self, data)[source]

Adds new line to stdout. Used when adding stdout from external execution.

Parameters

data (str) –

add_stderr(self, data)[source]

Adds new line to stderr. Used when adding stderr from external execution.

Parameters

data (str) –

_add_prompt(self, is_complete=True)[source]

Adds a prompt at the end of the document.

_restart_persistent(self, _=False)[source]

Restarts underlying persistent process.

_interrupt_persistent(self, _=False)[source]

Interrupts underlying persistent process.

paintEvent(self, ev)[source]

Repositions line edit.

focusInEvent(self, _ev)[source]

Gives focus to the line edit.

resizeEvent(self, ev)[source]

Makes line edit as wide as this.

_extend_menu(self, menu)[source]

Adds two more actions: Restart, and Interrupt.

contextMenuEvent(self, event)[source]

Reimplemented to extend menu with custom actions.

class spinetoolbox.widgets.persistent_console_widget.PersistentRunnableBase(engine_server_address, persistent_key)[source]

Bases: PySide2.QtCore.QRunnable

Base class for runnables that talk to the persistent process in another QThread.

Parameters
  • engine_server_address (str) – address of the remote engine, currently should always be an empty string

  • persistent_key (tuple) – persistent process identifier

class Signals[source]

Bases: PySide2.QtCore.QObject

finished[source]
class spinetoolbox.widgets.persistent_console_widget.Restarter(engine_server_address, persistent_key)[source]

Bases: PersistentRunnableBase

A runnable that restarts a persistent process.

Parameters
  • engine_server_address (str) – address of the remote engine, currently should always be an empty string

  • persistent_key (tuple) – persistent process identifier

run(self)[source]
class spinetoolbox.widgets.persistent_console_widget.Interrupter(engine_server_address, persistent_key)[source]

Bases: PersistentRunnableBase

A runnable that interrupts a persistent process.

Parameters
  • engine_server_address (str) – address of the remote engine, currently should always be an empty string

  • persistent_key (tuple) – persistent process identifier

run(self)[source]
class spinetoolbox.widgets.persistent_console_widget.CommandIssuer(engine_server_address, persistent_key, command)[source]

Bases: PersistentRunnableBase

A runnable that issues a command.

Parameters
  • engine_server_address (str) – address of the remote engine, currently should always be an empty string

  • persistent_key (tuple) – persistent process identifier

  • command (str) – command to execute

class Signals[source]

Bases: PySide2.QtCore.QObject

finished[source]
stdin_msg[source]
stdout_msg[source]
stderr_msg[source]
run(self)[source]
spinetoolbox.widgets.plain_parameter_value_editor

An editor widget for editing plain number database (relationship) parameter values.

author
  1. Soininen (VTT)

date

28.6.2019

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: PySide2.QtWidgets.QWidget

A widget to edit float or boolean type parameter values.

parent_widget

a parent widget

Type

QWidget

_set_number_or_string_enabled(self, on)[source]
set_value(self, value)[source]

Sets the value to be edited in this widget.

value(self)[source]

Returns the value currently being edited.

spinetoolbox.widgets.plot_canvas

A Qt widget to use as a matplotlib backend.

author
  1. Soininen (VTT)

date

3.6.2019

Module Contents
Classes

PlotCanvas

A widget for plotting with matplotlib.

class spinetoolbox.widgets.plot_canvas.PlotCanvas(parent=None)[source]

Bases: matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg

A widget for plotting with matplotlib.

Parameters

parent (QWidget) – a parent widget

property axes(self)[source]

matplotlib.axes.Axes: figure’s axes

spinetoolbox.widgets.plot_widget

A Qt widget showing a toolbar and a matplotlib plotting canvas.

author
  1. Soininen (VTT)

date

27.6.2019

Module Contents
Classes

PlotWidget

A widget that contains a toolbar and a plotting canvas.

Functions

_prepare_plot_in_window_menu(menu)

Fills a given menu with available plot window names.

class spinetoolbox.widgets.plot_widget.PlotWidget(parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

A widget that contains a toolbar and a plotting canvas.

canvas

the plotting canvas

Type

PlotCanvas

plot_type

type of currently plotted data or None

Type

type

plot_windows[source]

A global list of plot windows.

closeEvent(self, event)[source]

Removes the window from plot_windows and closes.

infer_plot_type(self, values)[source]

Decides suitable plot_type according to a list of values.

use_as_window(self, 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.

spinetoolbox.widgets.plot_widget._prepare_plot_in_window_menu(menu)[source]

Fills a given menu with available plot window names.

spinetoolbox.widgets.plugin_manager_widgets

Contains PluginManager dialogs and widgets.

author
  1. Marin (KTH)

date

21.2.2021

Module Contents
Classes

_InstallPluginModel

_ManagePluginsModel

InstallPluginDialog

Initialize class

ManagePluginsDialog

Initialize class

class spinetoolbox.widgets.plugin_manager_widgets._InstallPluginModel[source]

Bases: PySide2.QtGui.QStandardItemModel

data(self, index, role=None)[source]
class spinetoolbox.widgets.plugin_manager_widgets._ManagePluginsModel[source]

Bases: _InstallPluginModel

flags(self, index)[source]
class spinetoolbox.widgets.plugin_manager_widgets.InstallPluginDialog(parent)[source]

Bases: PySide2.QtWidgets.QDialog

Initialize class

item_selected[source]
populate_list(self, names)[source]
_handle_search_text_changed(self, _text)[source]
_filter_model(self)[source]
_handle_ok_clicked(self, _=False)[source]
_emit_item_selected(self, index)[source]
_update_ok_button_enabled(self, _selected, _deselected)[source]
class spinetoolbox.widgets.plugin_manager_widgets.ManagePluginsDialog(parent)[source]

Bases: PySide2.QtWidgets.QDialog

Initialize class

item_removed[source]
item_updated[source]
populate_list(self, names)[source]
_create_plugin_widget(self, plugin_name, can_update)[source]
_emit_item_removed(self, plugin_name)[source]
_emit_item_updated(self, plugin_name)[source]
spinetoolbox.widgets.project_item_drag

Classes for custom QListView.

author
  1. Marin (KTH)

date

14.11.2018

Module Contents
Classes

ProjectItemDragMixin

Custom class with dragging support.

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

Start dragging action if needed

mouseReleaseEvent(self, event)[source]

Forget drag start position

class spinetoolbox.widgets.project_item_drag.ProjectItemButtonBase(toolbox, item_type, icon, parent=None)[source]

Bases: ProjectItemDragMixin, PySide2.QtWidgets.QToolButton

Custom class with dragging support.

set_colored_icons(self, colored)[source]
_handle_drag_about_to_start(self)[source]
mousePressEvent(self, event)[source]

Register drag start position

abstract _make_mime_data_text(self)[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(self)[source]
mouseDoubleClickEvent(self, 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.

set_orientation(self, orientation)[source]
property spec_name(self)[source]
_make_mime_data_text(self)[source]
contextMenuEvent(self, event)[source]
mouseDoubleClickEvent(self, event)[source]
class spinetoolbox.widgets.project_item_drag.ShadeMixin[source]
paintEvent(self, 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(self)[source]
class spinetoolbox.widgets.project_item_drag.ShadeButton[source]

Bases: ShadeMixin, PySide2.QtWidgets.QToolButton

class spinetoolbox.widgets.project_item_drag._ChoppedIcon(icon, size)[source]

Bases: PySide2.QtGui.QIcon

update(self)[source]
class spinetoolbox.widgets.project_item_drag._ChoppedIconEngine(icon, size)[source]

Bases: PySide2.QtGui.QIconEngine

update(self)[source]
pixmap(self, size, mode, state)[source]
class spinetoolbox.widgets.project_item_drag.ProjectItemSpecArray(toolbox, model, item_type, icon)[source]

Bases: PySide2.QtWidgets.QToolBar

An array of ProjectItemSpecButton that can be expanded/collapsed.

Parameters
set_colored_icons(self, colored)[source]
update(self)[source]
_update_button_visible_icon_color(self)[source]
set_color(self, color)[source]
paintEvent(self, ev)[source]
_get_first_chopped_index(self)[source]

Returns the index of the first chopped action (chopped = not drawn because of space).

Returns

list(QAction) int or NoneType

_add_filling(self, 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(self, 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(self, 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(self, ev)[source]
_update_button_geom(self, orientation=None)[source]

Updates geometry of buttons given the orientation

Parameters

orientation (Qt.Orientation) –

_show_spec_form(self, _checked=False)[source]
toggle_visibility(self, _checked=False)[source]
set_visible(self, visible)[source]
_insert_specs(self, parent, first, last)[source]
_remove_specs(self, parent, first, last)[source]
_change_spec_data(self, top_left, bottom_right, roles)[source]
_reset_specs(self)[source]
_add_spec(self, row)[source]
spinetoolbox.widgets.rename_project_dialog

A widget for editing project name and description

Module Contents
Classes

RenameProjectDialog

Rename project dialog.

class spinetoolbox.widgets.rename_project_dialog.RenameProjectDialog(toolbox, project)[source]

Bases: PySide2.QtWidgets.QDialog

Rename project dialog.

Parameters
property name(self)[source]
property description(self)[source]
_set_ok_enabled(self)[source]
accept(self)[source]
spinetoolbox.widgets.report_plotting_failure

Functions to report failures in plotting to the user.

author
  1. Soininen (VTT)

date

10.7.2019

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.

spinetoolbox.widgets.settings_widget

Widget for controlling user settings.

author
  1. Savolainen (VTT)

date

17.1.2018

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_python_kernel_name_by_exe(python_exe)

Returns a kernel name corresponding to given python exe, or an empty string if none available.

_get_julia_kernel_name_by_env(julia_exe, julia_project)

Returns a kernel name corresponding to given julia exe and project, or an empty string if none available.

_samefile(a, b)

class spinetoolbox.widgets.settings_widget.SettingsWidgetBase(qsettings)[source]

Bases: PySide2.QtWidgets.QWidget

Parameters

qsettings (QSettings) – Toolbox settings

property qsettings(self)[source]
connect_signals(self)[source]

Connect signals.

keyPressEvent(self, e)[source]

Close settings form when escape key is pressed.

Parameters

e (QKeyEvent) – Received key press event.

mousePressEvent(self, e)[source]

Save mouse position at the start of dragging.

Parameters

e (QMouseEvent) – Mouse event

mouseReleaseEvent(self, e)[source]

Save mouse position at the end of dragging.

Parameters

e (QMouseEvent) – Mouse event

mouseMoveEvent(self, e)[source]

Moves the window when mouse button is pressed and mouse cursor is moved.

Parameters

e (QMouseEvent) – Mouse event

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

Gets selections and saves them to persistent memory.

update_ui_and_close(self, checked=False)[source]

Updates UI to reflect current settings and close.

save_and_close(self, checked=False)[source]

Saves settings and close.

class spinetoolbox.widgets.settings_widget.SpineDBEditorSettingsMixin[source]
connect_signals(self)[source]

Connect signals.

read_settings(self)[source]

Read saved settings from app QSettings instance and update UI to display them.

save_settings(self)[source]

Get selections and save them to persistent memory.

update_ui(self)[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.

show(self)[source]
set_auto_expand_objects(self, checked=False)[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.

connect_signals(self)[source]

Connect signals.

_update_python_widgets_enabled(self, state)[source]
_update_julia_widgets_enabled(self, state)[source]
_show_install_julia_wizard(self)[source]
_show_add_up_spine_opt_wizard(self)[source]
set_auto_expand_objects(self, checked=False)[source]
browse_gams_button_clicked(self, checked=False)[source]

Calls static method that shows a file browser for selecting a Gams executable.

browse_julia_button_clicked(self, checked=False)[source]

Calls static method that shows a file browser for selecting a Julia path.

browse_julia_project_button_clicked(self, checked=False)[source]

Calls static method that shows a folder browser for selecting a Julia project.

browse_python_button_clicked(self, checked=False)[source]

Calls static method that shows a file browser for selecting a Python interpreter.

browse_conda_button_clicked(self, checked=False)[source]

Calls static method that shows a file browser for selecting a Conda executable.

show_python_kernel_editor(self, checked=False)[source]

Opens kernel editor, where user can make a kernel for the Python Console.

python_kernel_editor_closed(self, ret_code)[source]

Catches the selected Python kernel name when the editor is closed.

show_julia_kernel_editor(self, checked=False)[source]

Opens kernel editor, where user can make a kernel the Julia Console.

julia_kernel_editor_closed(self, ret_code)[source]

Catches the selected Julia kernel name when the editor is closed.

browse_work_path(self, checked=False)[source]

Open file browser where user can select the path to wanted work directory.

show_color_dialog(self, checked=False)[source]

Let user pick the bg color.

Parameters

checked (boolean) – Value emitted with clicked signal

update_bg_color(self)[source]

Set tool button icon as the selected color and update Design View scene background color.

update_scene_bg(self, checked=False)[source]

Draw background on scene depending on radiobutton states.

Parameters

checked (boolean) – Toggle state

set_toolbar_colored_icons(self, checked=False)[source]
read_settings(self)[source]

Read saved settings from app QSettings instance and update UI to display them.

save_settings(self)[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.

_get_julia_settings(self)[source]
set_work_directory(self, new_work_dir)[source]

Sets new work directory.

Parameters

new_work_dir (str) – Possibly a new work directory

update_ui(self)[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.

spinetoolbox.widgets.settings_widget._get_python_kernel_name_by_exe(python_exe)[source]

Returns a kernel name corresponding to given python exe, or an empty string if none available.

Parameters

python_exe (str) –

Returns

str

spinetoolbox.widgets.settings_widget._get_julia_kernel_name_by_env(julia_exe, julia_project)[source]

Returns a kernel name corresponding to given julia exe and project, or an empty string if none available.

Parameters
  • julia_exe (str) –

  • julia_project (str) –

Returns

str

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.

_LogButton

A button to report unseen log messages, and show said log if clicked.

_EventLogButton

A button to report unseen log messages, and show said log if clicked.

_ItemLogButton

Reimplemented to store the document currently in the log and the character count,

class spinetoolbox.widgets.statusbars.MainStatusBar(toolbox)[source]

Bases: PySide2.QtWidgets.QStatusBar

A status bar for the main toolbox window.

Parameters

toolbox (ToolboxUI) –

_handle_item_log_visibility_changed(self, visible)[source]

Stores item log visible status to create _ItemLogButton instances later. See _handle_item_log_text_changed

_handle_item_log_text_changed(self)[source]

Runs when the text of the item log document changes. Creates an _ItemLogButton for the current item and adds it to the status bar.

class spinetoolbox.widgets.statusbars._LogButton(widget, log, icon, visible=False, color_name='', parent=None)[source]

Bases: PySide2.QtWidgets.QToolButton

A button to report unseen log messages, and show said log if clicked.

Parameters
  • widget (QDockWidget) – the dock widget that contains the log

  • log (CustomQTextBrowser) – the log

  • icon (str) – icon for the button

  • visible (bool) – whether or not the widget is visible at the moment of creating this button

  • color_name (str) – color for the button

  • parent (QObject) – passed to QToolButton constructor

_handle_clicked(self, checked)[source]

Runs when the button is clicked, shows and raises the widget.

abstract _handle_widget_visibility_changed(self, visible)[source]
abstract _handle_log_changed(self)[source]
class spinetoolbox.widgets.statusbars._EventLogButton(widget, log, icon, visible=False, color_name='', parent=None)[source]

Bases: _LogButton

A button to report unseen log messages, and show said log if clicked.

Parameters
  • widget (QDockWidget) – the dock widget that contains the log

  • log (CustomQTextBrowser) – the log

  • icon (str) – icon for the button

  • visible (bool) – whether or not the widget is visible at the moment of creating this button

  • color_name (str) – color for the button

  • parent (QObject) – passed to QToolButton constructor

_handle_widget_visibility_changed(self, visible)[source]

Hides the button when the widget becomes visible.

_handle_log_changed(self)[source]

Shows the button when the log text changes and the widget is non-visible.

class spinetoolbox.widgets.statusbars._ItemLogButton(widget, log, icon, visible=False, color_name='', parent=None)[source]

Bases: _LogButton

Reimplemented to store the document currently in the log and the character count, for monitoring that document only.

_handle_clicked(self, checked)[source]

Reimplemented to select the item before showing the widget.

_handle_widget_visibility_changed(self, visible)[source]

Hides the button when the widget becomes visible while showing the monitored document.

_handle_log_changed(self)[source]

Shows the button when the log text changes and the widget is non-visible, but only if the log’s document is the one being monitored.

hideEvent(self, ev)[source]

Reimplemented to update the current character count.

spinetoolbox.widgets.time_pattern_editor

An editor widget for editing a time pattern type (relationship) parameter values.

author
  1. Soininen (VTT)

date

28.6.2019

Module Contents
Classes

TimePatternEditor

A widget for editing time patterns.

class spinetoolbox.widgets.time_pattern_editor.TimePatternEditor(parent=None)[source]

Bases: PySide2.QtWidgets.QWidget

A widget for editing time patterns.

Parameters

parent (QWidget) – parent widget

_show_table_context_menu(self, position)[source]

Opens the table’s context menu.

Parameters

position (QPoint) – menu’s position on the table

set_value(self, value)[source]

Sets the parameter_value to be edited.

value(self)[source]

Returns the parameter_value currently being edited.

_open_header_editor(self, column)[source]
spinetoolbox.widgets.time_series_fixed_resolution_editor

Contains logic for the fixed step time series editor widget.

author
  1. Soininen (VTT)

date

14.6.2019

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: PySide2.QtWidgets.QWidget

A widget for editing time series data with a fixed time step.

Parameters

parent (QWidget) – a parent widget

_resolution_changed(self)[source]

Updates the models after resolution change.

_show_table_context_menu(self, position)[source]

Shows the table’s context menu.

Parameters

position (QPoint) – menu’s position in table view’s coordinates

_select_date(self, selected_date)[source]
set_value(self, value)[source]

Sets the parameter_value for editing in this widget.

_show_calendar(self)[source]
_start_time_changed(self)[source]

Updates the model due to start time change.

_update_plot(self, topLeft=None, bottomRight=None, roles=None)[source]

Updated the plot.

value(self)[source]

Returns the parameter_value currently being edited.

_open_header_editor(self, column)[source]
spinetoolbox.widgets.time_series_variable_resolution_editor

Contains logic for the variable resolution time series editor widget.

author
  1. Soininen (VTT)

date

31.5.2019

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: PySide2.QtWidgets.QWidget

A widget for editing variable resolution time series data.

Parameters

parent (QWidget) – a parent widget

_show_table_context_menu(self, position)[source]

Shows the table’s context menu.

Parameters

position (QPoint) – menu’s position on the table

set_value(self, value)[source]

Sets the time series being edited.

_update_plot(self, topLeft=None, bottomRight=None, roles=None)[source]

Updates the plot widget.

value(self)[source]

Return the time series currently being edited.

_open_header_editor(self, column)[source]
spinetoolbox.widgets.toolbars

Functions to make and handle QToolBars.

author
  1. Savolainen (VTT)

date

19.1.2018

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: PySide2.QtWidgets.QToolBar

Base class for Toolbox toolbars.

Parameters
  • name (str) – toolbar’s name

  • toolbox (ToolboxUI) – Toolbox main window

abstract set_color(self, color)[source]

Sets toolbar’s background color.

Parameters

color (QColor) – background color

set_project_actions_enabled(self, 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(self, 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(self, color)[source]

Sets toolbar’s background color.

Parameters

color (QColor) – background color

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

Enables or disables project related actions.

Parameters

enabled (bool) – True to enable actions, False to disable

set_color(self, color)[source]

Sets toolbar’s background color.

Parameters

color (QColor) – background color

setup(self)[source]
add_project_item_buttons(self)[source]
_add_project_item_button(self, item_type, factory, colored)[source]
set_colored_icons(self, colored)[source]
_make_tool_button(self, icon, tip, slot)[source]

Makes a new tool button and adds it to the toolbar.

Parameters
  • icon (QIcon) – button’s icon

  • tip (str) – button’s tooltip

  • slot (Callable) – slot where to connect button’s clicked signal

Returns

created button

Return type

QToolButton

_add_tool_button(self, button)[source]

Adds a button to the toolbar.

Parameters

button (QToolButton) – button to add

add_execute_buttons(self)[source]

Adds project execution buttons to the toolbar.

dragLeaveEvent(self, event)[source]
dragEnterEvent(self, event)[source]
dragMoveEvent(self, event)[source]
dropEvent(self, event)[source]
_update_drop_actions(self, event)[source]

Updates source and target actions for drop operation:

Parameters

event (QDragMoveEvent) –

paintEvent(self, ev)[source]

Draw a line as drop indicator.

_drop_line(self)[source]
icon_ordering(self)[source]
class spinetoolbox.widgets.toolbars.PaddingLabel(*args, **kwargs)[source]

Bases: PySide2.QtWidgets.QLabel

Submodules

spinetoolbox.__main__

Spine Toolbox application main file.

author
  1. Savolainen (VTT)

date

14.12.2017

Module Contents
spinetoolbox.__main__.return_code[source]
spinetoolbox.config

Application constants and style sheets

author
  1. Savolainen (VTT)

date

2.1.2018

Module Contents
Functions

_make_text_browser_ss(color)

Attributes

LATEST_PROJECT_VERSION

REQUIRED_SPINE_OPT_VERSION

INVALID_CHARS

INVALID_FILENAME_CHARS

_frozen

_path_to_executable

APPLICATION_PATH

_program_root

DEFAULT_WORK_DIR

DOCUMENTATION_PATH

ONLINE_DOCUMENTATION_URL

PLUGINS_PATH

PLUGIN_REGISTRY_URL

JUPYTER_KERNEL_TIME_TO_DEAD

PROJECT_FILENAME

STATUSBAR_SS

SETTINGS_SS

ICON_BACKGROUND

ICON_TOOLBAR_SS

TEXTBROWSER_SS

TEXTBROWSER_OVERRIDE_SS

MAINWINDOW_SS

TREEVIEW_HEADER_SS

PIVOT_TABLE_HEADER_COLOR

spinetoolbox.config.LATEST_PROJECT_VERSION = 6[source]
spinetoolbox.config.REQUIRED_SPINE_OPT_VERSION = 0.5.3[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-project.github.io/PluginRegistry/registry.json[source]
spinetoolbox.config.JUPYTER_KERNEL_TIME_TO_DEAD = 8.0[source]
spinetoolbox.config.PROJECT_FILENAME = project.json[source]
spinetoolbox.config.STATUSBAR_SS = QStatusBar{background-color: #EBEBE0; border-width: 1px; border-color: gray; border-style: groove;}[source]
spinetoolbox.config.SETTINGS_SS = #SettingsForm{background-color: ghostwhite;}QLabel{color: black;}QLineEdit{font-size:...[source]
spinetoolbox.config.ICON_BACKGROUND = qlineargradient(x1: 1, y1: 1, x2: 0, y2: 0, stop: 0 #cce0ff, stop: 1 #66a1ff);[source]
spinetoolbox.config.ICON_TOOLBAR_SS[source]
spinetoolbox.config._make_text_browser_ss(color)[source]
spinetoolbox.config.TEXTBROWSER_SS[source]
spinetoolbox.config.TEXTBROWSER_OVERRIDE_SS[source]
spinetoolbox.config.MAINWINDOW_SS = QMainWindow::separator{width: 3px; background-color: lightgray; border: 1px solid...[source]
spinetoolbox.config.TREEVIEW_HEADER_SS = QHeaderView::section{background-color: #ecd8c6; font-size: 12px;}[source]
spinetoolbox.config.PIVOT_TABLE_HEADER_COLOR = #efefef[source]
spinetoolbox.custom_file_system_watcher

Contains CustomFileSystemWatcher.

author
  1. Marin (KTH)

date

12.11.2020

Module Contents
Classes

CustomFileSystemWatcher

A file system watcher that keeps track of renamed files.

class spinetoolbox.custom_file_system_watcher.CustomFileSystemWatcher(parent=None)[source]

Bases: PySide2.QtCore.QFileSystemWatcher

A file system watcher that keeps track of renamed files.

file_renamed[source]
file_removed[source]
file_added[source]
_handle_dir_changed(self, dirname)[source]
add_persistent_file_path(self, path)[source]
add_persistent_file_paths(self, paths)[source]
remove_persistent_file_path(self, path)[source]
remove_persistent_file_paths(self, paths)[source]
add_persistent_dir_path(self, path)[source]
remove_persistent_dir_path(self, path)[source]
tear_down(self)[source]
_take_snapshot(self, dirname)[source]
static _absfilepaths(dirname)[source]
spinetoolbox.dag_handler

Contains classes for handling DAGs.

author
  1. Savolainen (VTT)

date

8.4.2019

Module Contents
Classes

DirectedGraphHandler

Class for manipulating graphs according to user's actions.

class spinetoolbox.dag_handler.DirectedGraphHandler[source]

Class for manipulating graphs according to user’s actions.

dags(self)[source]

Returns a list of graphs (DiGraph) in the project.

add_dag(self, dag)[source]

Add graph to list.

Parameters

dag (DiGraph) – Graph to add

remove_dag(self, dag)[source]

Remove graph from instance variable list.

Parameters

dag (DiGraph) – Graph to remove

add_dag_node(self, node_name)[source]

Create directed graph with one node and add it to list.

Parameters

node_name (str) – Project item name to add as a node

add_graph_edge(self, src_node, dst_node)[source]

Adds an edge between the src and dst nodes. If nodes are in different graphs, the reference to union graph is saved and the references to the original graphs are removed. If src and dst nodes are already in the same graph, the edge is added to the graph. If src and dst are the same node, a self-loop (feedback) edge is added.

Parameters
  • src_node (str) – Source project item node name

  • dst_node (str) – Destination project item node name

Returns

True if edge established, False if not (e.g. any of the nodes doesn’t really exist)

Return type

bool

remove_graph_edge(self, src_node, dst_node)[source]

Removes edge from a directed graph.

Parameters
  • src_node (str) – Source project item node name

  • dst_node (str) – Destination project item node name

Returns

One or two DAGs containing source and destination nodes.

Return type

list of DiGraph

remove_node_from_graph(self, node_name)[source]

Removes node from a graph that contains it. Called when project item is removed from project.

Parameters

node_name (str) – Project item name

rename_node(self, old_name, new_name)[source]

Handles renaming the node and edges in a graph when a project item is renamed.

Parameters
  • old_name (str) – Old project item name

  • new_name (str) – New project item name

Returns

True if successful, False if renaming failed

Return type

bool

dag_with_node(self, node_name)[source]

Returns directed graph that contains given node.

Parameters

node_name (str) – Node to look for

Returns

Directed graph that contains node or None if not found.

Return type

(DiGraph)

dag_with_edge(self, src_node, dst_node)[source]

Returns directed graph that contains given edge.

Parameters
  • src_node (str) – Source node name

  • dst_node (str) – Destination node name

Returns

Directed graph that contains edge or None if not found.

Return type

(DiGraph)

static node_successors(g)[source]

Returns a dict mapping nodes in the given graph to a list of its direct successors. The nodes are in topological sort order. Topological sort in the words of networkx: “a nonunique permutation of the nodes, such that an edge from u to v implies that u appears before v in the topological sort order.”

Parameters

g (DiGraph) – Directed graph to process

Returns

key is the node name, value is list of successor names Empty dict if given graph is not a DAG.

Return type

dict

successors_til_node(self, g, node)[source]

Like node_successors but only until the given node, and ignoring all nodes that are not its ancestors.

node_is_isolated(self, node, allow_self_loop=False)[source]

Checks if the project item with the given name has any connections.

Parameters
  • node (str) – Project item name

  • allow_self_loop (bool) – If default (False), Self-loops are considered as an in-neighbor or an out-neighbor so the method returns False. If True, single node with a self-loop is considered isolated.

Returns

True if project item has no in-neighbors nor out-neighbors, False if it does.

Single node with a self-loop is NOT isolated (returns False).

Return type

bool

static source_nodes(g)[source]

Returns a list of source nodes in given graph. A source node has no incoming edges. This is determined by calculating the in-degree of each node in the graph. If nodes in-degree == 0, it is a source node

Parameters

g (DiGraph) – Graph to examine

Returns

List of source node names or an empty list is there are none.

Return type

list

static edges_causing_loops(g)[source]

Returns a list of edges whose removal from g results in it becoming acyclic.

spinetoolbox.execution_managers

Classes to manage tool instance execution in various forms.

author
  1. Savolainen (VTT)

date

1.2.2018

Module Contents
Classes

ExecutionManager

Base class for all tool instance execution managers.

QProcessExecutionManager

Class to manage tool instance execution using a PySide2 QProcess.

class spinetoolbox.execution_managers.ExecutionManager(logger)[source]

Bases: PySide2.QtCore.QObject

Base class for all tool instance execution managers.

Class constructor.

Parameters

logger (LoggerInterface) – a logger instance

execution_finished[source]
abstract start_execution(self, workdir=None)[source]

Starts the execution.

Parameters

workdir (str) – Work directory

abstract stop_execution(self)[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 PySide2 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(self)[source]

Program getter method.

args(self)[source]

Program argument getter method.

start_execution(self, workdir=None)[source]

Starts the execution of a command in a QProcess.

Parameters

workdir (str, optional) – Work directory

wait_for_process_finished(self, msecs=30000)[source]

Wait for subprocess to finish.

Parameters

msecs (int) – Timeout in milliseconds

Returns

True if process finished successfully, False otherwise

process_started(self)[source]

Run when subprocess has started.

on_state_changed(self, new_state)[source]

Runs when QProcess state changes.

Parameters

new_state (int) – Process state number (QProcess::ProcessState)

on_process_error(self, process_error)[source]

Runs if there is an error in the running QProcess.

Parameters

process_error (int) – Process error number (QProcess::ProcessError)

teardown_process(self)[source]

Tears down the QProcess in case a QProcess.ProcessError occurred. Emits execution_finished signal.

stop_execution(self)[source]

See base class.

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

Emit data from stdout.

on_ready_stderr(self)[source]

Emit data from stderr.

spinetoolbox.headless

Contains facilities to open and execute projects without GUI.

authors
  1. Soininen (VTT)

date

29.4.2020

Module Contents
Classes

HeadlessLogger

A LoggerInterface compliant logger that uses Python's standard logging facilities.

ExecuteProject

A 'task' which opens and executes a Toolbox project when triggered to do so.

_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: PySide2.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(self, message)[source]

Writes an information message to Python’s logging system.

_log_warning(self, message)[source]

Writes a warning message to Python’s logging system.

_log_error(self, message)[source]

Writes an error message to Python’s logging system.

_show_information_box(self, title, message)[source]

Writes an information message with a title to Python’s logging system.

_show_error_box(self, title, message)[source]

Writes an error message with a title to Python’s logging system.

class spinetoolbox.headless.ExecuteProject(args, startup_event_type, parent)[source]

Bases: PySide2.QtCore.QObject

A ‘task’ which opens and executes a Toolbox project when triggered to do so.

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.

_execute(self)[source]

Executes this task.

_open_and_execute_project(self)[source]

Opens a project and executes all DAGs in that project.

Returns

status code

Return type

_Status

_process_engine_event(self, event_type, data)[source]
event(self, e)[source]
_handle_node_execution_started(self, data)[source]

Starts collecting messages from given node.

Parameters

data (dict) – execution start data

_handle_node_execution_finished(self, data)[source]

Prints messages for finished nodes.

Parameters

data (dict) – execution end data

_handle_event_msg(self, data)[source]

Stores event messages for later printing.

Parameters

data (dict) – event message data

_handle_process_msg(self, data)[source]

Stores process messages for later printing.

Parameters

data (dict) – process message data

_handle_standard_execution_msg(self, data)[source]

Handles standard execution messages.

Currently, these messages are ignored.

Parameters

data (dict) – execution message data

_handle_kernel_execution_msg(self, data)[source]

Handles kernel messages.

Currently, these messages are ignored.

Parameters

data (dict) – execution 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 (str) – path to a directory containing the .spinetoolbox dir

  • logger (LoggerInterface) – a logger

Returns

item dicts, specification dicts, connection 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]
spinetoolbox.helpers

General helper functions and classes.

authors
  1. Savolainen (VTT)

date

10.1.2018

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

CacheItem

A dictionary that behaves kinda like a row from a query result.

Functions

home_dir()

Returns user's home dir

format_log_message(msg_type, message, show_datetime=True)

Adds color tags and optional time stamp to message.

add_message_to_document(document, message)

Adds a message to a document and return the cursor.

busy_effect(func)

Decorator to change the mouse cursor to 'busy' while a function is processed.

create_dir(base_path, folder='', verbosity=False)

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.

pyside2_version_check()

Check that PySide2 version is 5.14 or 5.15.

get_datetime(show, date=True)

Returns date and time string for appending into Event Log messages.

copy_files(src_dir, dst_dir, includes=None, excludes=None)

Function for copying files. Does not copy folders.

erase_dir(path, verbosity=False)

Deletes a directory and all its contents without prompt.

recursive_overwrite(logger, src, dst, ignore=None, silent=True)

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

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, caption, given_dir, filter_='')

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, caption, given_dir, filter_='')

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.

file_is_valid(parent, file_path, msgbox_title, extra_check=None)

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=0.0, saturation=1.0)

unique_name(prefix, existing)

Creates a unique name in the form "prefix X" where X is a number.

get_upgrade_db_promt_text(url, current, expected)

parse_specification_file(spec_path, logger)

Parses specification file.

load_specification_from_file(spec_path, spec_factories, app_settings, logger)

Returns an Item specification from a definition file.

specification_from_dict(spec_dict, spec_factories, app_settings, logger)

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, spec_factories, app_settings, logger)

Loads plugin's specifications.

parameter_identifier(database, parameter, alternative, entities)

Concatenates given information into parameter value identifier string.

signal_waiter(signal)

inquire_index_name(model, column, title, parent_widget)

Asks for indexed parameter's index name and updates model accordingly.

preferred_row_height(widget, factor=1.5)

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=None)

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.add_message_to_document(document, message)[source]

Adds a message to a document and return the cursor.

Parameters
  • document (QTextDocument) –

  • message (str) –

Returns

QTextCursor

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

Check that PySide2 version is 5.14 or 5.15. Version 5.15 is allowed but it is not promoted yet because user’s may need to update their VC++ runtime libraries on Windows.

qt_version is the Qt version used to compile PySide2 as string. E.g. “5.14.2” qt_version_info is a tuple with each version component of Qt used to compile PySide2. E.g. (5, 14, 2)

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

Init model that can be used to display all icons in a list.

_model_data(self, 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: PySide2.QtGui.QIconEngine

Specialization of QIconEngine with transparent background.

pixmap(self, 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(self, painter, rect, mode=None, state=None)[source]
class spinetoolbox.helpers.ColoredIcon(icon_file_name, icon_color, icon_size, colored=None)[source]

Bases: PySide2.QtGui.QIcon

set_colored(self, colored)[source]
color(self, mode=QIcon.Normal)[source]
class spinetoolbox.helpers.ColoredIconEngine(icon_file_name, icon_color, icon_size, colored=None)[source]

Bases: PySide2.QtGui.QIconEngine

color(self, mode=QIcon.Normal)[source]
set_colored(self, colored)[source]
_do_make_pixmap(self, mode, state)[source]
_make_pixmap(self, mode, state)[source]
pixmap(self, 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: PySide2.QtWidgets.QFileIconProvider

QFileIconProvider that provides a Spine icon to the Open Project Dialog when a Spine Toolbox project directory is encountered.

icon(self, 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: PySide2.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(self, 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.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__(self, _)[source]
__call__(self, *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)[source]
spinetoolbox.helpers.unique_name(prefix, existing)[source]

Creates a unique name in the form “prefix X” where X is a number.

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, spec_factories, app_settings, logger)[source]

Returns an Item specification from a definition file.

Parameters
  • spec_path (str) – Path of the specification definition file

  • 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, spec_factories, app_settings, logger)[source]

Returns item specification from a dictionary.

Parameters
  • spec_dict (dict) – Dictionary with the specification

  • 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, spec_factories, app_settings, logger)[source]

Loads plugin’s specifications.

Parameters
  • plugin_dict (dict) – plugin dict

  • 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.DB_ITEM_SEPARATOR =  ǀ[source]

Display string to separate items such as entity names.

spinetoolbox.helpers.parameter_identifier(database, parameter, alternative, entities)[source]

Concatenates given information into parameter value identifier string.

Parameters
  • database (str, optional) – database’s code name

  • parameter (str) – parameter’s name

  • alternative (str) – name of the value’s alternative

  • entities (list of str) – name of the entity that holds the value

class spinetoolbox.helpers.SignalWaiter[source]

Bases: PySide2.QtCore.QObject

A ‘traffic light’ that allows waiting for a signal to be emitted in another thread.

trigger(self, *args)[source]

Signal receiving slot.

wait(self)[source]

Wait for signal to be received.

spinetoolbox.helpers.signal_waiter(signal)[source]
class spinetoolbox.helpers.CustomSyntaxHighlighter(*arg, **kwargs)[source]

Bases: PySide2.QtGui.QSyntaxHighlighter

set_style(self, style)[source]
yield_formats(self, text)[source]
highlightBlock(self, 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

class spinetoolbox.helpers.CacheItem[source]

Bases: dict

A dictionary that behaves kinda like a row from a query result.

It is used to store items in a cache, so we can access them as if they were rows from a query result. This is mainly because we want to use the cache as a replacement for db queries in some methods.

Initialize self. See help(type(self)) for accurate signature.

__getattr__(self, name)[source]

Overridden method to return the dictionary key named after the attribute, or None if it doesn’t exist.

_asdict(self)[source]
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]
spinetoolbox.load_project_items

Functions to load project item modules.

author
  1. Soininen (VTT)

date

29.4.2020

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

A logger interface.

authors
  1. Soininen (VTT)

date

16.1.2020

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

author
  1. Soininen (VTT)

date

4.10.2019

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.

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-project/Spine-Toolbox/issues/1230.

spinetoolbox.metaobject

MetaObject class.

authors
  1. Rinne (VTT), P. Savolainen (VTT)

date

18.12.2017

Module Contents
Classes

MetaObject

Class for an object which has a name, type, and some description.

class spinetoolbox.metaobject.MetaObject(name, description)[source]

Bases: PySide2.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(self, 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(self, description)[source]

Set object description.

Parameters

description (str) – Object description

spinetoolbox.plotting

Functions for plotting on PlotWidget.

Currently plotting from the table views found in the SpineDBEditor are supported.

The main entrance points to plotting are: - plot_selection() which plots selected cells on a table view returning a PlotWidget object - plot_pivot_column() which is a specialized method for plotting entire columns of a pivot table - add_time_series_plot() which adds a time series plot to an existing PlotWidget - add_map_plot() which adds a map plot to an existing PlotWidget

author
  1. Soininen (VTT)

date

9.7.2019

Module Contents
Classes

PlottingHints

A base class for plotting hints.

ParameterTablePlottingHints

Support for plotting data in Parameter table views.

PivotTablePlottingHints

Support for plotting data in Tabular view.

Functions

plot_pivot_column(proxy_model, column, hints, plot_widget=None)

Returns a plot widget with a plot of an entire column in PivotTableModel.

plot_selection(model, indexes, hints, plot_widget=None)

Returns a plot widget with plots of the selected indexes.

add_array_plot(plot_widget, value, label=None)

Adds an array plot to a plot widget.

add_map_plot(plot_widget, map_value, label=None)

Adds a map plot to a plot widget.

add_time_series_plot(plot_widget, value, label=None)

Adds a time series step plot to a plot widget.

_add_plot_to_widget(values, labels, plot_widget)

Adds a new plot to plot_widget.

_raise_if_not_all_indexed_values(values)

Raises an exception if not all values are TimeSeries or Maps.

_filter_name_columns(selections)

Returns a dict with all but the entry with the greatest key removed.

_organize_selection_to_columns(indexes)

Organizes a list of model indexes into a dictionary of {column: (rows)} entries.

_collect_single_column_values(model, column, rows, hints)

Collects selected parameter values from a single column.

_collect_x_column_values(model, column, rows, hints)

Collects selected parameter values from an x column.

_collect_index_column_values(model, column, rows, hints)

Collects selected values from an index column.

_collect_column_values(model, column, rows, hints)

Collects selected parameter values from a single column for plotting.

_expand_maps(maps, labels)

Gathers the leaf elements from maps and expands labels accordingly.

_label_nested_maps(map_, label)

Collects leaf values from given Maps and labels them.

_filter_and_check(xs, ys)

Filters Nones and empty values from x and y and checks that data types match.

_raise_if_indexed_values_not_plottable(values)

Raises an exception if the indexed values in values contain elements that cannot be plotted.

_raise_if_value_types_clash(values, plot_widget)

Raises a PlottingError if values type is incompatible with plot_widget.

_x_values_from_rows(model, rows, hints)

Returns x value array constructed from model rows.

Attributes

_LEGEND_SETTINGS

_PLOT_SETTINGS

spinetoolbox.plotting._LEGEND_SETTINGS[source]
spinetoolbox.plotting._PLOT_SETTINGS[source]
exception spinetoolbox.plotting.PlottingError(message)[source]

Bases: Exception

An exception signalling failure in plotting.

Parameters

message (str) – an error message

property message(self)[source]

str: the error message.

spinetoolbox.plotting.plot_pivot_column(proxy_model, column, hints, plot_widget=None)[source]

Returns a plot widget with a plot of an entire column in PivotTableModel.

Parameters
  • proxy_model (PivotTableSortFilterProxy) – a pivot table filter

  • column (int) – a column index to the model

  • hints (PlottingHints) – a helper needed for e.g. plot labels

  • plot_widget (PlotWidget) – an existing plot widget to draw into or None to create a new widget

Returns

a plot widget

Return type

PlotWidget

spinetoolbox.plotting.plot_selection(model, indexes, hints, plot_widget=None)[source]

Returns a plot widget with plots of the selected indexes.

Parameters
  • model (QAbstractTableModel) – a model

  • indexes (Iterable) – a list of QModelIndex objects for plotting

  • hints (PlottingHints) – a helper needed for e.g. plot labels

  • plot_widget (PlotWidget) – an existing plot widget to draw into or None to create a new widget

Returns

a PlotWidget object

spinetoolbox.plotting.add_array_plot(plot_widget, value, label=None)[source]

Adds an array plot to a plot widget.

Parameters
  • plot_widget (PlotWidget) – a plot widget to modify

  • value (Array) – the array to plot

  • label (str) – a label for the array

spinetoolbox.plotting.add_map_plot(plot_widget, map_value, label=None)[source]

Adds a map plot to a plot widget.

Parameters
  • plot_widget (PlotWidget) – a plot widget to modify

  • map_value (Map) – the map to plot

  • label (str) – a label for the map

spinetoolbox.plotting.add_time_series_plot(plot_widget, value, label=None)[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

  • label (str) – a label for the time series

class spinetoolbox.plotting.PlottingHints[source]

A base class for plotting hints.

The functionality in this class allows the plotting functions to work without explicit knowledge of the underlying table model or widget.

abstract cell_label(self, model, index)[source]

Returns a label for the cell given by index in a table.

abstract column_label(self, model, column)[source]

Returns a label for a column.

abstract filter_columns(self, selections, model)[source]

Filters columns and returns the filtered selections.

abstract is_index_in_data(self, model, index)[source]

Returns true if the cell given by index is actually plottable data.

static normalize_row(row, model)[source]

Returns a ‘human understandable’ row number

abstract special_x_values(self, model, column, rows)[source]

Returns X values if available, otherwise returns None.

abstract x_label(self, model)[source]

Returns a label for the x axis.

class spinetoolbox.plotting.ParameterTablePlottingHints[source]

Bases: PlottingHints

Support for plotting data in Parameter table views.

cell_label(self, model, index)[source]

Returns a label build from the columns on the left from the data column.

column_label(self, model, column)[source]

Returns the column header.

filter_columns(self, selections, model)[source]

Returns the ‘value’ or ‘default_value’ column only.

is_index_in_data(self, model, index)[source]

Always returns True.

special_x_values(self, model, column, rows)[source]

Always returns None.

x_label(self, model)[source]

Returns an empty string for the x axis label.

class spinetoolbox.plotting.PivotTablePlottingHints[source]

Bases: PlottingHints

Support for plotting data in Tabular view.

cell_label(self, model, index)[source]

Returns a label for the table cell given by index.

column_label(self, model, column)[source]

Returns a label for a table column.

filter_columns(self, selections, model)[source]

Filters the X column from selections.

is_index_in_data(self, model, index)[source]

Returns True if index is in the data portion of the table.

static normalize_row(row, model)[source]

See base class.

special_x_values(self, model, column, rows)[source]

Returns the values from the X column if one is designated otherwise returns None.

x_label(self, model)[source]

Returns the label of the X column, if available.

static _map_column_to_source(proxy_model, proxy_column)[source]

Maps a proxy model column to source model.

static _map_column_from_source(proxy_model, source_column)[source]

Maps a source model column to proxy model.

spinetoolbox.plotting._add_plot_to_widget(values, labels, plot_widget)[source]

Adds a new plot to plot_widget.

spinetoolbox.plotting._raise_if_not_all_indexed_values(values)[source]

Raises an exception if not all values are TimeSeries or Maps.

spinetoolbox.plotting._filter_name_columns(selections)[source]

Returns a dict with all but the entry with the greatest key removed.

spinetoolbox.plotting._organize_selection_to_columns(indexes)[source]

Organizes a list of model indexes into a dictionary of {column: (rows)} entries.

spinetoolbox.plotting._collect_single_column_values(model, column, rows, hints)[source]

Collects selected parameter values from a single column.

The return value of this function depends on what type of data the given column contains. In case of plain numbers, a list of scalars and a single label string are returned. In case of indexed parameters (time series, maps), a list of parameter_value objects is returned, accompanied by a list of labels, each label corresponding to one of the indexed parameters.

Parameters
  • model (QAbstractTableModel) – a table model

  • column (int) – a column index to the model

  • rows (Sequence) – row indexes to plot

  • hints (PlottingHints) – a plot support object

Returns

values and label(s)

Return type

tuple

spinetoolbox.plotting._collect_x_column_values(model, column, rows, hints)[source]

Collects selected parameter values from an x column.

Parameters
  • model (QAbstractTableModel) – a table model

  • column (int) – a column index to the model

  • rows (Sequence) – row indexes to plot

  • hints (PlottingHints) – a plot support object

Returns

a tuple of values and label(s)

spinetoolbox.plotting._collect_index_column_values(model, column, rows, hints)[source]

Collects selected values from an index column.

Parameters
  • model (QAbstractTableModel) – a table model

  • column (int) – a column index to the model

  • rows (Sequence) – row indexes to plot

  • hints (PlottingHints) – a plot support object

Returns

column’s values

Return type

list

spinetoolbox.plotting._collect_column_values(model, column, rows, hints)[source]

Collects selected parameter values from a single column for plotting.

The return value of this function depends on what type of data the given column contains. In case of plain numbers, a single tuple of two lists of x and y values and a single label string are returned. In case of time series, a list of TimeSeries objects is returned, accompanied by a list of labels, each label corresponding to one of the time series.

Parameters
  • model (QAbstractTableModel) – a table model

  • column (int) – a column index to the model

  • rows (Sequence) – row indexes to plot

  • hints (PlottingHints) – a support object

Returns

a tuple of values and label(s)

Return type

tuple

spinetoolbox.plotting._expand_maps(maps, labels)[source]

Gathers the leaf elements from maps and expands labels accordingly.

Parameters
  • maps (list of Map) – maps to expand

  • labels (list of str) – map labels

Returns

expanded maps and labels

Return type

tuple

spinetoolbox.plotting._label_nested_maps(map_, label)[source]

Collects leaf values from given Maps and labels them.

Parameters
  • map (Map) – a map

  • label (str) – map’s label

Returns

list of values and list of corresponding labels

Return type

tuple

spinetoolbox.plotting._filter_and_check(xs, ys)[source]

Filters Nones and empty values from x and y and checks that data types match.

spinetoolbox.plotting._raise_if_indexed_values_not_plottable(values)[source]

Raises an exception if the indexed values in values contain elements that cannot be plotted.

spinetoolbox.plotting._raise_if_value_types_clash(values, plot_widget)[source]

Raises a PlottingError if values type is incompatible with plot_widget.

spinetoolbox.plotting._x_values_from_rows(model, rows, hints)[source]

Returns x value array constructed from model rows.

spinetoolbox.plugin_manager

Contains PluginManager class.

author
  1. Marin (KTH)

date

21.2.2021

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

property plugin_toolbars(self)[source]
property plugin_specs(self)[source]
load_installed_plugins(self)[source]

Loads installed plugins and adds their specifications to toolbars.

load_individual_plugin(self, plugin_dir)[source]

Loads plugin from directory.

Parameters

plugin_dir (str) – path of plugin dir with “plugin.json” in it.

_create_worker(self)[source]
_clean_up_worker(self, worker)[source]
_load_registry(self)[source]
show_install_plugin_dialog(self, _=False)[source]
_do_show_install_plugin_dialog(self)[source]
_install_plugin(self, plugin_name)[source]

Installs plugin from the registry and loads it.

Parameters

plugin_name (str) – plugin name

_load_installed_plugin(self, plugin_local_dir)[source]
show_manage_plugins_dialog(self, _=False)[source]
_do_show_manage_plugins_dialog(self)[source]
_remove_plugin(self, plugin_name)[source]

Removes installed plugin.

Parameters

plugin_name (str) – plugin name

_update_plugin(self, 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: PySide2.QtCore.QObject

failed[source]
finished[source]
succeeded[source]
start(self, function, *args, **kwargs)[source]
_do_work(self)[source]
clean_up(self)[source]
spinetoolbox.project

Spine Toolbox project class.

authors
  1. Savolainen (VTT), E. Rinne (VTT)

date

10.1.2018

Module Contents
Classes

ItemNameStatus

Generic enumeration.

SpineToolboxProject

Class for Spine Toolbox projects.

Functions

_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, name, description, p_dir, plugin_specs, settings, logger)[source]

Bases: spinetoolbox.metaobject.MetaObject

Class for Spine Toolbox projects.

Parameters
  • toolbox (ToolboxUI) – toolbox of this project

  • name (str) – Project name

  • description (str) – Project description

  • p_dir (str) – Project directory

  • plugin_specs (Iterable of ProjectItemSpecification) – specifications available as plugins

  • settings (QSettings) – Toolbox settings

  • logger (LoggerInterface) – a logger instance

renamed[source]

Emitted after project has been renamed.

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

Emitted after a connection has been replaced by another.

jump_added[source]

Emitted after a jump has been added.

jump_about_to_be_removed[source]

Emitted before a jump is removed.

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

toolbox(self)[source]

Returns Toolbox main window.

Returns

main window

Return type

ToolboxUI

_create_project_structure(self, 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_name_and_description(self, name, description)[source]
set_name(self, name)[source]

Changes project name.

Parameters

name (str) – New project name

set_description(self, description)[source]

Set object description.

Parameters

description (str) – Object description

save(self)[source]

Collects project information and objects into a dictionary and writes it to a JSON file.

Returns

True or False depending on success

Return type

bool

static _dump(project_dict, out_stream)[source]

Dumps project dict into output stream.

Parameters
  • project_dict (dict) – project dictionary

  • out_stream (IOBase) – output stream

load(self, 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

_load_project_dict(self)[source]

Loads project dictionary from project directory.

Returns

project dictionary

Return type

dict

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

Yields project’s specifications.

Yields

ProjectItemSpecification – specification

_specification_id(self)[source]

Creates an id for specification.

Returns

new id

Return type

int

get_specification(self, 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(self, 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(self, id_or_name)[source]

Removes a specification from project.

Parameters

id_or_name (int or str) – specification’s id or name

replace_specification(self, name, specification)[source]

Replaces an existing specification.

Saves the given spec to disk and refreshes the spec in all items that use it.

Parameters
  • name (str) – name of the specification to replace

  • specification (ProjectItemSpecification) – a specification

Returns

True if operation was successful, False otherwise

Return type

bool

save_specification_file(self, specification)[source]

Saves the given project item specification.

Save path is determined by specification directory and specification’s name.

Parameters

specification (ProjectItemSpecification) – specification to save

Returns

True if operation was successful, False otherwise

Return type

bool

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

Returns True if project has project items.

Returns

True if project has items, False otherwise

Return type

bool

get_item(self, name)[source]

Returns project item.

Parameters

name (str) – item’s name

Returns

project item

Return type

ProjectItem

get_items(self)[source]

Returns all project items.

Returns

all project items

Return type

list of ProjectItem

rename_item(self, 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(self, name)[source]

Validates item name.

Parameters

name (str) – proposed project item’s name

Returns

validation result

Return type

ItemNameStatus

property connections(self)[source]
find_connection(self, 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(self, 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(self, connection, silent=False)[source]

Adds a connection to the project.

Parameters
  • connection (Connection) – connection to add

  • silent (bool) – If False, prints ‘Link establ…’ msg to Event Log

Returns

True if connection was added successfully, False otherwise

Return type

bool

remove_connection(self, connection)[source]

Removes a connection from the project.

Parameters

connection (Connection) – connection to remove

replace_connection(self, existing_connection, new_connection)[source]

Replaces an existing connection between items.

Replacing does not trigger any updates to the DAG or project items.

Parameters
  • existing_connection (Connection) – an established connection

  • new_connection (Connection) – connection to replace by

add_jump(self, 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(self, 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(self, jump)[source]

Removes a jump from the project.

Parameters

jump (Jump) – jump to remove

replace_jump(self, existing_jump, new_jump)[source]

Replaces an existing jump between items.

Parameters
  • existing_jump (Jump) – an established jump

  • new_jump (Jump) – jump to replace by

jump_issues(self, jump)[source]

Checks if jump is OK.

Parameters

jump (Jump) – jump to check

Returns

list of issues, if any

Return type

list of str

restore_project_items(self, 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(self, 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(self, dags, execution_permits, msg)[source]

Executes given dags.

Parameters
  • dags (Sequence(DiGraph)) –

  • execution_permits (Sequence(dict)) –

get_node_successors(self, dag, dag_identifier)[source]
_execute_dags(self, dags, execution_permits_list)[source]
create_engine_worker(self, dag, execution_permits, dag_identifier, settings)[source]
_handle_engine_worker_finished(self, worker)[source]
dag_with_node(self, item_name)[source]
execute_selected(self, names)[source]

Executes DAGs corresponding to given project items.

Parameters

names (Iterable of str) – item names to execute

execute_project(self)[source]

Executes all dags in the project.

stop(self)[source]

Stops execution. Slot for the main window Stop tool button in the toolbar.

notify_resource_changes_to_predecessors(self, item)[source]

Updates resources for direct predecessors of given item.

Parameters

item (ProjectItem) – item whose resources have changed

notify_resource_changes_to_successors(self, item)[source]

Updates resources for direct successors and outgoing connections of given item.

Parameters

item (ProjectItem) – item whose resources have changed

_notify_resource_changes(self, 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(self, item, old, new)[source]

Replaces a resource for direct successors and outgoing connections of given item.

Parameters
  • item (ProjectItem) – item whose resources have changed

  • old (ProjectItemResource) – old resource

  • new (ProjectItemResource) – new resource

notify_resource_replacement_to_predecessors(self, item, old, new)[source]

Replaces a resource for direct predecessors.

Parameters
  • item (ProjectItem) – item whose resources have changed

  • old (ProjectItemResource) – old resource

  • new (ProjectItemResource) – new resource

_update_item_resources(self, 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

successor_names(self, 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

_outgoing_connections(self, 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

_incoming_connections(self, 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

_update_successor(self, successor, incoming_connections, resource_cache)[source]
_update_predecessor(self, predecessor, outgoing_connections, resource_cache)[source]
_is_dag_valid(self, dag)[source]
_update_ranks(self, dag)[source]
property settings(self)[source]
tear_down(self)[source]

Cleans up project.

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.

authors
  1. Marin (KTH)

date

12.2.2020

Module Contents
Classes

Id

Id numbers for project commands.

SpineToolboxCommand

SetItemSpecificationCommand

Command to set the specification for a Tool.

MoveIconCommand

Command to move icons in the Design view.

SetProjectNameAndDescriptionCommand

Command to set the project name.

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.

SetFiltersOnlineCommand

Command to toggle filter value.

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.Id[source]

Bases: enum.IntEnum

Id numbers for project commands.

Initialize self. See help(type(self)) for accurate signature.

JUMP_CONDITION = 1[source]
class spinetoolbox.project_commands.SpineToolboxCommand[source]

Bases: PySide2.QtWidgets.QUndoCommand

successfully_undone = False[source]

Flag to register the outcome of undoing a critical command, so toolbox can react afterwards.

static is_critical()[source]

Returns True if this command needs to be undone before closing the project without saving changes.

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(self)[source]
undo(self)[source]
class spinetoolbox.project_commands.MoveIconCommand(icon, project)[source]

Bases: SpineToolboxCommand

Command to move icons in the Design view.

Parameters
redo(self)[source]
undo(self)[source]
_move_to(self, positions)[source]
class spinetoolbox.project_commands.SetProjectNameAndDescriptionCommand(project, name, description)[source]

Bases: SpineToolboxCommand

Command to set the project name.

Parameters
  • project (SpineToolboxProject) – the project

  • name (str) – The new name

  • description (str) – The new description

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

redo(self)[source]
undo(self)[source]
static is_critical()[source]

Returns True if this command needs to be undone before closing the project without saving changes.

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(self)[source]
undo(self)[source]
class spinetoolbox.project_commands.RemoveConnectionsCommand(project, connections)[source]

Bases: SpineToolboxCommand

Command to remove links.

Parameters
  • project (SpineToolboxProject) – project

  • connections (list of Connection) – the connections

redo(self)[source]
undo(self)[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(self)[source]
undo(self)[source]
class spinetoolbox.project_commands.RemoveJumpsCommand(project, jumps)[source]

Bases: SpineToolboxCommand

Command to remove jumps.

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

id(self)[source]
mergeWith(self, other)[source]
redo(self)[source]
undo(self)[source]
class spinetoolbox.project_commands.SetFiltersOnlineCommand(resource_filter_model, resource, filter_type, online)[source]

Bases: SpineToolboxCommand

Command to toggle filter value.

Parameters
  • resource_filter_model (ResourceFilterModel) – filter model

  • resource (str) – resource label

  • filter_type (str) – filter type identifier

  • online (dict) – mapping from scenario/tool id to online flag

redo(self)[source]
undo(self)[source]
class spinetoolbox.project_commands.SetConnectionOptionsCommand(link, options)[source]

Bases: SpineToolboxCommand

Command to set connection options.

Parameters
  • link (Link) –

  • options (dict) – containing options to be set

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

redo(self)[source]
undo(self)[source]
static is_critical()[source]

Returns True if this command needs to be undone before closing the project without saving changes.

class spinetoolbox.project_commands.RemoveSpecificationCommand(project, name)[source]

Bases: SpineToolboxCommand

Command to remove specs from a project.

Parameters
redo(self)[source]
undo(self)[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(self)[source]
undo(self)[source]
spinetoolbox.project_item_icon

Classes for drawing graphics items on QGraphicsScene.

authors
  1. Marin (KTH), P. Savolainen (VTT)

date

4.4.2018

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: PySide2.QtWidgets.QGraphicsRectItem

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]
finalize(self, 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(self, brush, svg, svg_color)[source]

Setup item’s attributes.

Parameters
  • brush (QBrush) – Used in filling the background rectangle

  • svg (str) – Path to SVG icon file

  • svg_color (QColor) – Color of SVG icon

name(self)[source]

Returns name of the item that is represented by this icon.

Returns

icon’s name

Return type

str

update_name_item(self, new_name)[source]

Set a new text to name item.

Parameters

new_name (str) – icon’s name

set_name_attributes(self)[source]

Set name QGraphicsSimpleTextItem attributes (font, size, position, etc.)

_reposition_name_item(self)[source]

Set name item position (centered on top of the master icon).

conn_button(self, 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

run_execution_leave_animation(self, excluded)[source]

Starts the animation associated with execution leaving the icon.

Parameters

excluded (bool) – True if project item was not actually executed.

hoverEnterEvent(self, event)[source]

Sets a drop shadow effect to icon when mouse enters its boundaries.

Parameters

event (QGraphicsSceneMouseEvent) – Event

hoverLeaveEvent(self, event)[source]

Disables the drop shadow when mouse leaves icon boundaries.

Parameters

event (QGraphicsSceneMouseEvent) – Event

mousePressEvent(self, event)[source]

Updates scene’s icon group.

Updates geometry of connected links to reflect this item’s most recent position.

mouseReleaseEvent(self, event)[source]

Clears pre-bump rects, and pushes a move icon command if necessary.

notify_item_move(self)[source]
contextMenuEvent(self, event)[source]

Show item context menu.

Parameters

event (QGraphicsSceneMouseEvent) – Mouse event

itemChange(self, 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(self, pos)[source]

Sets position without bumping other items. Needed for undoing move operations.

Parameters

pos (QPointF) –

_handle_collisions(self)[source]

Handles collisions with other items.

make_room_for_item(self, other)[source]

Makes room for another item.

Parameters

item (ProjectItemIcon) –

_restablish_bumped_items(self)[source]

Moves bumped items back to their original position if no collision would happen anymore.

select_item(self)[source]

Update GUI to show the details of the selected item.

class spinetoolbox.project_item_icon.ConnectorButton(parent, toolbox, position='left')[source]

Bases: PySide2.QtWidgets.QGraphicsRectItem

Connector button graphics item. Used for Link drawing between project items.

Parameters
  • parent (QGraphicsItem) – Project item bg rectangle

  • toolbox (ToolboxUI) – QMainWindow instance

  • position (str) – Either “top”, “left”, “bottom”, or “right”

brush[source]
hover_brush[source]
property parent(self)[source]
parent_name(self)[source]

Returns project item name owning this connector button.

project_item(self)[source]

Returns the project item this connector button is attached to.

Returns

project item

Return type

ProjectItem

mousePressEvent(self, event)[source]

Connector button mouse press event. Either starts or closes a link.

Parameters

event (QGraphicsSceneMouseEvent) – Event

set_friend_connectors_enabled(self, enabled)[source]

Enables or disables all connectors in the parent.

This is called by LinkDrawer to disable invalid connectors while drawing and reenabling them back when done.

Parameters

enabled (bool) – True to enable connectors, False to disable

hoverEnterEvent(self, event)[source]

Sets a darker shade to connector button when mouse enters its boundaries.

Parameters

event (QGraphicsSceneMouseEvent) – Event

hoverLeaveEvent(self, event)[source]

Restore original brush when mouse leaves connector button boundaries.

Parameters

event (QGraphicsSceneMouseEvent) – Event

itemChange(self, 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: PySide2.QtWidgets.QGraphicsEllipseItem

An icon to show information about the item’s execution.

Parameters

parent (ProjectItemIcon) – the parent item

_CHECK = [source]
_CROSS = [source]
_CLOCK = [source]
_SKIP = [source]
item_name(self)[source]
_repaint(self, text, color)[source]
mark_execution_waiting(self)[source]
mark_execution_started(self)[source]
mark_execution_finished(self, item_finish_state)[source]
hoverEnterEvent(self, event)[source]
hoverLeaveEvent(self, event)[source]
class spinetoolbox.project_item_icon.ExclamationIcon(parent)[source]

Bases: PySide2.QtWidgets.QGraphicsTextItem

An icon to notify that a ProjectItem is missing some configuration.

Parameters

parent (ProjectItemIcon) – the parent item

clear_notifications(self)[source]

Clear all notifications.

add_notification(self, text)[source]

Add a notification.

remove_notification(self, subtext)[source]

Remove the first notification that includes given subtext.

hoverEnterEvent(self, event)[source]

Shows notifications as tool tip.

Parameters

event (QGraphicsSceneMouseEvent) – Event

hoverLeaveEvent(self, event)[source]

Hides tool tip.

Parameters

event (QGraphicsSceneMouseEvent) – Event

class spinetoolbox.project_item_icon.RankIcon(parent)[source]

Bases: PySide2.QtWidgets.QGraphicsTextItem

An icon to show the rank of a ProjectItem within its DAG.

Parameters

parent (ProjectItemIcon) – the parent item

set_rank(self, rank)[source]
spinetoolbox.project_tree_item

Project Tree items.

authors
  1. Soininen (VTT)

date

17.1.2020

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

Returns the item flags.

parent(self)[source]

Returns parent project tree item.

child_count(self)[source]

Returns the number of child project tree items.

children(self)[source]

Returns the children of this project tree item.

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

Returns the row on which this item is located.

abstract add_child(self, child_item)[source]

Base method that shall be overridden in subclasses.

remove_child(self, 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(self, 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.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(self, 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(self, toolbox)[source]

See base class.

class spinetoolbox.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(self)[source]

Returns the item flags.

add_child(self, 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(self, toolbox)[source]

Returns the context menu for this item.

Parameters

toolbox (ToolboxUI) – Toolbox main window

Returns

context menu

Return type

QMenu

class spinetoolbox.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(self)[source]

the project item linked to this leaf

abstract add_child(self, child_item)[source]

See base class.

flags(self)[source]

Returns the item flags.

custom_context_menu(self, toolbox)[source]

Returns the context menu for this item.

Parameters

toolbox (ToolboxUI) – Toolbox main window

Returns

context menu

Return type

QMenu

spinetoolbox.project_upgrader

Contains ProjectUpgrader class used in upgrading and converting projects and project dicts from earlier versions to the latest version.

authors
  1. Savolainen (VTT)

date

8.11.2019

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(self, 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(self, 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(self, 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

Returns

Version 6 project dictionary

Return type

dict

static make_unique_importer_specification_name(importer_name, label, k)[source]
get_project_directory(self)[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(self, v, p)[source]

Checks given project dict if it is valid for given version.

is_valid_v1(self, 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_6(self, p, v)[source]

Checks that the given project JSON dictionary contains a valid version 2 to 6 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 project, False if it is not

Return type

bool

backup_project_file(self, project_dir, v)[source]

Makes a backup copy of project.json file.

force_save(self, 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.spine_db_commands

QUndoCommand subclasses for modifying the db.

authors
  1. Marin (KTH)

date

31.1.2020

Module Contents
Classes

AgedUndoStack

AgedUndoCommand

param parent

The parent command, used for defining macros.

SpineDBCommand

param db_mngr

SpineDBManager instance

AddItemsCommand

param db_mngr

SpineDBManager instance

UpdateItemsCommand

param db_mngr

SpineDBManager instance

RemoveItemsCommand

param db_mngr

SpineDBManager instance

class spinetoolbox.spine_db_commands.AgedUndoStack[source]

Bases: PySide2.QtWidgets.QUndoStack

property redo_age(self)[source]
property undo_age(self)[source]
commands(self)[source]
class spinetoolbox.spine_db_commands.AgedUndoCommand(parent=None)[source]

Bases: PySide2.QtWidgets.QUndoCommand

Parameters

parent (QUndoCommand, optional) – The parent command, used for defining macros.

redo(self)[source]
undo(self)[source]
property age(self)[source]
class spinetoolbox.spine_db_commands.SpineDBCommand(db_mngr, db_map, parent=None)[source]

Bases: AgedUndoCommand

Parameters
  • db_mngr (SpineDBManager) – SpineDBManager instance

  • db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance

  • parent (QUndoCommand, optional) – The parent command, used for defining macros.

_add_command_name[source]
_update_command_name[source]
_add_method_name[source]
_update_method_name[source]
_added_signal_name[source]
_updated_signal_name[source]
static redomethod(func)[source]

Returns a new redo method that determines if the command was completed. The command is completed if calling the function triggers the completed_signal. Once the command is completed, we don’t listen to the signal anymore and we also silence the affected Spine db editors. If the signal is not received, then the command is declared obsolete.

static undomethod(func)[source]

Returns a new undo method that silences the affected Spine db editors.

abstract receive_items_changed(self, _)[source]
class spinetoolbox.spine_db_commands.AddItemsCommand(db_mngr, db_map, data, item_type, parent=None, check=True)[source]

Bases: SpineDBCommand

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

  • parent (QUndoCommand, optional) – The parent command, used for defining macros.

redo(self)[source]
undo(self)[source]
receive_items_changed(self, db_map_data)[source]
class spinetoolbox.spine_db_commands.UpdateItemsCommand(db_mngr, db_map, data, item_type, parent=None, check=True)[source]

Bases: SpineDBCommand

Parameters
  • db_mngr (SpineDBManager) – SpineDBManager instance

  • db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance

  • data (list) – list of dict-items to update

  • item_type (str) – the item type

  • parent (QUndoCommand, optional) – The parent command, used for defining macros.

_undo_item(self, db_map, id_)[source]
redo(self)[source]
undo(self)[source]
receive_items_changed(self, db_map_data)[source]
class spinetoolbox.spine_db_commands.RemoveItemsCommand(db_mngr, db_map, typed_data, parent=None)[source]

Bases: SpineDBCommand

Parameters
  • db_mngr (SpineDBManager) – SpineDBManager instance

  • db_map (DiffDatabaseMapping) – DiffDatabaseMapping instance

  • typed_data (dict) – lists of dict-items to remove keyed by string type

  • parent (QUndoCommand, optional) – The parent command, used for defining macros.

redo(self)[source]
undo(self)[source]
receive_items_changed(self, typed_db_map_data)[source]
spinetoolbox.spine_db_fetcher

SpineDBFetcher class.

authors
  1. Marin (KTH)

date

13.3.2020

Module Contents
Classes

SpineDBFetcher

Fetches content from a Spine database.

class spinetoolbox.spine_db_fetcher.SpineDBFetcher(db_mngr, db_map)[source]

Bases: PySide2.QtCore.QObject

Fetches content from a Spine database.

Initializes the fetcher object.

Parameters
  • db_mngr (SpineDBManager) – used for fetching

  • db_map (DiffDatabaseMapping) – The db to fetch

_fetch_more_requested[source]
_fetch_all_requested[source]
_fetch_all_finished[source]
cache_items(self, item_type, items)[source]
get_item(self, item_type, id_)[source]
_make_fetch_successful(self, parent)[source]
_can_fetch_more_from_cache(self, item_type, parent=None)[source]
can_fetch_more(self, item_type, parent=None)[source]
_fetch_more_from_cache(self, item_type, parent=None, iter_chunk_size=1000)[source]
fetch_more(self, item_type, parent=None, iter_chunk_size=1000)[source]

Fetches items from the database.

Parameters

item_type (str) – the type of items to fetch, e.g. “object_class”

_fetch_more(self, item_type, parent)[source]
_do_fetch_more(self, item_type, parent)[source]
_refetch_parents(self, item_type)[source]

Refetches parents that might have missed some content from the cache. Called after adding items to the cache from the DB thread.

Parameters

item_type (str) –

fetch_all(self, item_types=None, only_descendants=False, include_ancestors=False)[source]
_fetch_all(self, item_types)[source]
_do_fetch_all(self, item_types)[source]
_get_db_items(self, item_type, order_by=('id',), query_chunk_size=1000, iter_chunk_size=1000)[source]

Runs the given query and yields results by chunks of given size.

Parameters

item_type (str) – item type

Yields

list – chunk of items

_make_query(self, item_type, order_by=('id',))[source]

Makes a database query for given item type.

Parameters
  • item_type (str) – item type

  • order_by (Iterable) – key for order by

Returns

database query

Return type

Query

_populate_commit_cache(self, item_type, items)[source]
spinetoolbox.spine_db_icon_manager

Provides SpineDBIconManager.

authors
  1. Marin (KTH)

date

3.2.2021

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

Bases: PySide2.QtSvg.QSvgRenderer

scene[source]
classmethod from_scene(cls, scene)[source]
class spinetoolbox.spine_db_icon_manager.SpineDBIconManager[source]

A class to manage object_class icons for spine db editors.

update_icon_caches(self, 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(self, icon_code, color_code)[source]
icon_renderer(self, icon_code, color_code)[source]
_create_class_renderer(self, class_name)[source]
class_renderer(self, class_name)[source]
_create_rel_cls_renderer(self, object_class_names)[source]
relationship_class_renderer(self, rel_cls_name, str_object_class_name_list)[source]
_create_group_renderer(self, class_name)[source]
group_renderer(self, class_name)[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(self, painter, rect, mode=None, state=None)[source]
spinetoolbox.spine_db_manager

The SpineDBManager class

authors
  1. Vennström (VTT) and M. Marin (KTH)

date

2.10.2019

Module Contents
Classes

SpineDBManager

Class to manage DBs within a project.

CombinedCache

Functions

do_create_new_spine_database(url)

Creates a new spine database at the given url.

_split_and_parse_value_list(item)

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

Bases: PySide2.QtCore.QObject

Class to manage DBs within a project.

Initializes the instance.

Parameters
  • settings (QSettings) – Toolbox settings

  • parent (QObject, optional) – parent object

error_msg[source]
session_refreshed[source]
session_committed[source]
session_rolled_back[source]
scenarios_added[source]
alternatives_added[source]
object_classes_added[source]
objects_added[source]
relationship_classes_added[source]
relationships_added[source]
entity_groups_added[source]
parameter_definitions_added[source]
parameter_values_added[source]
parameter_value_lists_added[source]
features_added[source]
tools_added[source]
tool_features_added[source]
tool_feature_methods_added[source]
scenarios_removed[source]
alternatives_removed[source]
object_classes_removed[source]
objects_removed[source]
relationship_classes_removed[source]
relationships_removed[source]
entity_groups_removed[source]
parameter_definitions_removed[source]
parameter_values_removed[source]
parameter_value_lists_removed[source]
features_removed[source]
tools_removed[source]
tool_features_removed[source]
tool_feature_methods_removed[source]
scenarios_updated[source]
alternatives_updated[source]
object_classes_updated[source]
objects_updated[source]
relationship_classes_updated[source]
relationships_updated[source]
parameter_definitions_updated[source]
parameter_values_updated[source]
parameter_value_lists_updated[source]
features_updated[source]
tools_updated[source]
tool_features_updated[source]
tool_feature_methods_updated[source]
items_removed_from_cache[source]
scenario_alternatives_added[source]
scenario_alternatives_updated[source]
scenario_alternatives_removed[source]
db_map_fetched[source]
connect_signals(self)[source]

Connects signals.

_get_fetcher(self, db_map)[source]

Returns a fetcher.

Parameters

db_map (DiffDatabaseMapping) –

Returns

SpineDBFetcher

can_fetch_more(self, db_map, item_type, parent=None)[source]

Whether or not we can fetch more items of given type from given db.

Parameters
  • db_map (DiffDatabaseMapping) –

  • item_type (str) – the type of items to fetch, e.g. “object_class”

  • parent (object, optional) – The object that requests the fetching. Can implement fetch_successful, i.e., a function that receives a db_map and a dictionary-item and returns a Boolean indicating whether or not to stop fetching.

Returns

bool

fetch_more(self, db_map, item_type, parent=None)[source]

Fetches more items of given type from given db.

Parameters
  • db_map (DiffDatabaseMapping) –

  • item_type (str) – the type of items to fetch, e.g. “object_class”

  • parent (object, optional) – The object that requests the fetching. Can implement fetch_successful, i.e., a function that receives a db_map and a dictionary-item and returns a Boolean indicating whether or not to stop fetching. If not implemented, then fetching is stopped immediately after one step. Can also provide fully_fetched, a Signal that gets emitted whenever fetching is complete.

cache_items_for_fetching(self, db_map, item_type, items)[source]
cache_items(self, item_type, db_map_data)[source]

Caches data for a given type. It works for both insert and update operations.

Parameters
  • item_type (str) –

  • db_map_data (dict) – lists of dictionary items keyed by DiffDatabaseMapping

_pop_item(self, db_map, item_type, id_)[source]
uncache_items(self, db_map_typed_ids)[source]

Removes data from cache.

Parameters

db_map_typed_ids (dict) – items to remove

get_db_map_cache(self, db_map, item_types=None, only_descendants=False, include_ancestors=False)[source]
get_icon_mngr(self, db_map)[source]

Returns an icon manager for given db_map.

Parameters

db_map (DiffDatabaseMapping) –

Returns

SpineDBIconManager

update_icons(self, db_map_data)[source]

Runs when object classes are added or updated. Setups icons for those classes.

Parameters

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

property worker_thread(self)[source]
property db_maps(self)[source]
property db_urls(self)[source]
db_map(self, 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(self, url, logger)[source]
close_session(self, url)[source]

Pops any db map on the given url and closes its connection.

Parameters

url (str) –

close_all_sessions(self)[source]

Closes connections to all database mappings.

get_db_map(self, url, logger, codename=None, upgrade=False, create=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(self, url, codename, upgrade, create)[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

register_listener(self, listener, *db_maps)[source]

Register given listener for all given db_map’s signals.

Parameters
  • listener (object) –

  • db_maps (DiffDatabaseMapping) –

unregister_listener(self, listener, commit_dirty, commit_msg, *db_maps)[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) –

  • commit_dirty (bool) – True to commit dirty database mapping, False to roll back

  • commit_msg (str) – commit message

  • *db_maps (DiffDatabaseMapping) –

dirty(self, *db_maps)[source]

Checks which of the given database mappings are dirty.

Parameters

*db_maps – mappings to check

Returns

dirty mappings

Return type

list of DiffDatabaseMapping

dirty_or_orphan(self, listener, *db_maps)[source]

Checks which of the given database mappings are dirty or orphaned.

Parameters
  • listener (Any) – a listener object

  • *db_maps – mappings to check

Returns

dirty or orphaned mappings

Return type

list of DiffDatabaseMapping

clean_up(self)[source]
refresh_session(self, *db_maps)[source]
_finish_rolling_back(self, rolled_back_db_maps)[source]

Clears caches and emits session_rolled_back signal.

Parameters

rolled_back_db_maps (set of DiffDatabaseMap) – database maps that have been rolled back

_clear_fetchers(self, db_maps)[source]
commit_session(self, 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 session_committed signal

rollback_session(self, *dirty_db_maps)[source]

Rolls back the current session.

Parameters

*dirty_db_maps – dirty database maps to commit

entity_class_renderer(self, db_map, entity_type, entity_class_id, for_group=False)[source]

Returns an icon renderer for a given entity class.

Parameters
  • db_map (DiffDatabaseMapping) – database map

  • entity_type (str) – either ‘object_class’ or ‘relationship_class’

  • 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(self, db_map, entity_type, entity_class_id, for_group=False)[source]

Returns an appropriate icon for a given entity class.

Parameters
  • db_map (DiffDatabaseMapping) – database map

  • entity_type (str) – either ‘object_class’ or ‘relationship_class’

  • 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

get_item(self, db_map, item_type, id_, only_visible=True)[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) –

  • only_visible (bool, optional) – If True, only looks in items that have already made it into the cache.

Returns

dict

get_field(self, db_map, item_type, id_, field, only_visible=True)[source]
get_items(self, db_map, item_type, only_visible=True)[source]

Returns a list of the items of the given type in the given db map.

Parameters
  • db_map (DiffDatabaseMapping) –

  • item_type (str) –

  • only_visible (bool, optional) – If True, only returns items that have already made it into the cache.

Returns

list

get_items_by_field(self, db_map, item_type, field, value, only_visible=True)[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(self, db_map, item_type, field, value, only_visible=True)[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.DisplayRole.

static tool_tip_data_from_parsed(parsed_data)[source]

Returns the value’s database representation formatted for Qt.ToolTipRole.

get_value(self, db_map, item_type, id_, role=Qt.DisplayRole)[source]

Returns the value or default value of a parameter.

Parameters
  • db_map (DiffDatabaseMapping) –

  • item_type (str) – either “parameter_definition” or “parameter_value”

  • id (int) – The parameter_value or definition id

  • role (int, optional) –

Returns

any

get_value_from_data(self, data, role=Qt.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(self, parsed_value, role=Qt.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(self, 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(self, db_map, item_type, id_, index, role=Qt.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(self, db_map, id_, index, role=Qt.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(self, db_map, id_, role=Qt.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(self, db_map, scen_id)[source]
import_data(self, 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_or_update_items(self, db_map_data, method_name, item_type, signal_name, readd=False, check=True)[source]
add_alternatives(self, db_map_data)[source]

Adds alternatives to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_scenarios(self, db_map_data)[source]

Adds scenarios to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_object_classes(self, db_map_data)[source]

Adds object classes to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_objects(self, db_map_data)[source]

Adds objects to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_relationship_classes(self, db_map_data)[source]

Adds relationship classes to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_relationships(self, db_map_data)[source]

Adds relationships to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_object_groups(self, db_map_data)[source]

Adds object groups to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_entity_groups(self, db_map_data)[source]

Adds entity groups to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_parameter_definitions(self, 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(self, 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(self, db_map_data)[source]

Adds parameter_value lists to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_features(self, db_map_data)[source]

Adds features to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_tools(self, db_map_data)[source]

Adds tools to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_tool_features(self, db_map_data)[source]

Adds tool features to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

add_tool_feature_methods(self, db_map_data)[source]

Adds tool feature methods to db.

Parameters

db_map_data (dict) – lists of items to add keyed by DiffDatabaseMapping

update_alternatives(self, db_map_data)[source]

Updates alternatives in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_scenarios(self, db_map_data)[source]

Updates scenarios in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_object_classes(self, db_map_data)[source]

Updates object classes in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_objects(self, db_map_data)[source]

Updates objects in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_relationship_classes(self, db_map_data)[source]

Updates relationship classes in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_relationships(self, db_map_data)[source]

Updates relationships in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_parameter_definitions(self, 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(self, db_map_data)[source]

Updates parameter values in db without checking integrity.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_expanded_parameter_values(self, db_map_data)[source]

Updates expanded parameter values in db without checking integrity.

Parameters

db_map_data (dict) – lists of expanded items to update keyed by DiffDatabaseMapping

update_parameter_value_lists(self, db_map_data)[source]

Updates parameter_value lists in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_features(self, db_map_data)[source]

Updates features in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_tools(self, db_map_data)[source]

Updates tools in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_tool_features(self, db_map_data)[source]

Updates tools features in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

update_tool_feature_methods(self, db_map_data)[source]

Updates tools feature methods in db.

Parameters

db_map_data (dict) – lists of items to update keyed by DiffDatabaseMapping

set_scenario_alternatives(self, db_map_data)[source]

Sets scenario alternatives in db.

Parameters

db_map_data (dict) – lists of items to set keyed by DiffDatabaseMapping

remove_items(self, db_map_typed_ids)[source]
do_remove_items(self, db_map_typed_ids)[source]

Removes items from database.

Parameters

db_map_typed_ids (dict) – lists of items to remove, keyed by item type (str), keyed by DiffDatabaseMapping

static db_map_ids(db_map_data)[source]
static db_map_class_ids(db_map_data)[source]
find_cascading_relationship_classes(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading relationship classes for the given object_class ids.

find_cascading_entities(self, db_map_ids, item_type, only_visible=True)[source]

Finds and returns cascading entities for the given entity_class ids.

find_cascading_relationships(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading relationships for the given object ids.

find_cascading_parameter_data(self, db_map_ids, item_type, only_visible=True)[source]

Finds and returns cascading parameter definitions or values for the given entity_class ids.

find_cascading_parameter_definitions_by_value_list(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading parameter definitions for the given parameter_value_list ids.

find_cascading_parameter_definitions_by_removed_value_list(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading parameter definitions for the given parameter_value_list ids that have been removed.

find_cascading_parameter_values_by_entity(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading parameter values for the given entity ids.

find_cascading_parameter_values_by_definition(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading parameter values for the given parameter_definition ids.

find_groups_by_entity(self, db_map_ids, only_visible=True)[source]

Finds and returns groups for the given entity ids.

find_groups_by_member(self, db_map_ids, only_visible=True)[source]

Finds and returns groups for the given entity ids.

find_cascading_parameter_values_by_alternative(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading parameter values for the given alternative ids.

find_cascading_features_by_parameter_definition(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading features for the given parameter definition ids.

find_cascading_features_by_parameter_value_list(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading features for the given parameter value list ids.

find_cascading_tool_features_by_feature(self, db_map_ids, only_visible=True)[source]

Finds and returns cascading tool features for the given feature ids.

_refresh_scenario_alternatives(self, db_map_data, only_visible=True)[source]

Refreshes cached scenarios when updating scenario alternatives.

Parameters

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

_cascade_refresh_relationship_classes(self, db_map_data)[source]

Refreshes cached relationship classes when updating object classes.

Parameters

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

_cascade_refresh_relationships_by_object(self, db_map_data)[source]

Refreshed cached relationships in cascade when updating objects.

Parameters

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

_cascade_refresh_parameter_definitions(self, db_map_data)[source]

Refreshes cached parameter definitions in cascade when updating entity classes.

Parameters

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

_cascade_refresh_parameter_definitions_by_value_list(self, db_map_data)[source]

Refreshes cached parameter definitions when updating parameter_value lists.

Parameters

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

_cascade_refresh_parameter_definitions_by_removed_value_list(self, db_map_data)[source]

Refreshes cached parameter definitions when removing parameter_value lists.

Parameters

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

_cascade_refresh_parameter_values_by_entity_class(self, db_map_data)[source]

Refreshes cached parameter values in cascade when updating entity classes.

Parameters

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

_cascade_refresh_parameter_values_by_entity(self, db_map_data)[source]

Refreshes cached parameter values in cascade when updating entities.

Parameters

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

_cascade_refresh_parameter_values_by_alternative(self, db_map_data)[source]

Refreshes cached parameter values in cascade when updating alternatives.

Parameters

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

_cascade_refresh_parameter_values_by_definition(self, db_map_data)[source]

Refreshes cached parameter values in cascade when updating parameter definitions.

Parameters

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

_cascade_refresh_features_by_paremeter_definition(self, db_map_data)[source]

Refreshes cached features in cascade when updating parameter definitions.

Parameters

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

_cascade_refresh_features_by_paremeter_value_list(self, db_map_data)[source]

Refreshes cached features in cascade when updating parameter value lists.

Parameters

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

_cascade_refresh_tool_features_by_feature(self, db_map_data)[source]

Refreshes cached tool features in cascade when updating features.

Parameters

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

duplicate_object(self, db_maps, object_data, orig_name, dup_name)[source]
_get_data_for_export(self, db_map_item_ids)[source]
export_data(self, caller, db_map_item_ids, file_path, file_filter)[source]
_is_url_available(self, url, logger)[source]
export_to_sqlite(self, file_path, data_for_export, caller)[source]

Exports given data into SQLite file.

export_to_json(self, file_path, data_for_export, caller)[source]

Exports given data into JSON file.

export_to_excel(self, file_path, data_for_export, caller)[source]

Exports given data into Excel file.

get_metadata_per_entity(self, db_map, entity_ids)[source]
get_metadata_per_parameter_value(self, db_map, parameter_value_ids)[source]
get_items_for_commit(self, 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(self)[source]

Yields all instances of SpineDBEditor currently open.

Yields

SpineDBEditor

_get_existing_spine_db_editor(self, db_url_codenames)[source]
open_db_editor(self, 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

static cache_to_db(item_type, item)[source]

Returns the db equivalent of a cache item.

Parameters
  • item_type (str) – The item type

  • item (dict) – The item in the cache

Returns

dict

db_to_cache(self, db_map, item_type, item)[source]

Returns the cache equivalent of a db item.

Parameters
  • db_map (DiffDatabaseMapping) – the db map

  • item_type (str) – The item type

  • item (dict) – The item in the db

Returns

dict

class spinetoolbox.spine_db_manager.CombinedCache(d1, d2)[source]
__getitem__(self, key)[source]
get(self, key, default)[source]
spinetoolbox.spine_db_manager._split_and_parse_value_list(item)[source]
spinetoolbox.spine_db_parcel

SpineDBParcel class.

authors
  1. Marin (KTH)

date

10.5.2020

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(self)[source]
_get_fields(self, db_map, item_type, field, ids)[source]
push_object_class_ids(self, db_map_ids)[source]

Pushes object_class ids.

push_relationship_class_ids(self, db_map_ids)[source]

Pushes relationship_class ids.

push_object_ids(self, db_map_ids)[source]

Pushes object ids.

push_relationship_ids(self, db_map_ids)[source]

Pushes relationship ids.

push_parameter_value_list_ids(self, db_map_ids)[source]

Pushes parameter_value_list ids.

push_parameter_definition_ids(self, db_map_ids, entity_type)[source]

Pushes parameter_definition ids.

push_parameter_value_ids(self, db_map_ids, entity_type)[source]

Pushes parameter_value ids.

push_object_group_ids(self, db_map_ids)[source]

Pushes object group ids.

push_alternative_ids(self, db_map_ids)[source]

Pushes alternative ids.

push_scenario_ids(self, db_map_ids)[source]

Pushes scenario ids.

push_scenario_alternative_ids(self, db_map_ids)[source]

Pushes scenario_alternative ids.

push_feature_ids(self, db_map_ids)[source]

Pushes feature ids.

push_tool_ids(self, db_map_ids)[source]

Pushes tool ids.

push_tool_feature_ids(self, db_map_ids)[source]

Pushes tool_feature ids.

push_tool_feature_method_ids(self, db_map_ids)[source]

Pushes tool_feature_method ids.

full_push_object_class_ids(self, db_map_ids)[source]

Pushes parameter definitions associated with given object classes. This essentially full_pushes the object classes and their parameter definitions.

full_push_relationship_class_ids(self, db_map_ids)[source]

Pushes parameter definitions associated with given relationship classes. This essentially full_pushes the relationships classes, their parameter definitions, and their member object classes.

full_push_object_ids(self, db_map_ids)[source]

Pushes parameter values associated with objects and with any relationships involving those objects. This essentially full_pushes objects, their relationships, all the parameter values, and all the necessary classes, definitions, and lists.

full_push_relationship_ids(self, db_map_ids)[source]

Pushes parameter values associated with relationships. This essentially full_pushes relationships, their parameter values, and all the necessary classes, definitions, and lists.

inner_push_object_ids(self, db_map_ids)[source]

Pushes object ids, cascading relationship ids, and the associated parameter values, but not any entity classes or parameter definitions. Mainly intended for the Duplicate object action.

inner_push_relationship_ids(self, db_map_ids)[source]

Pushes relationship ids, and the associated parameter values, but not any entity classes or parameter definitions.

inner_push_parameter_value_ids(self, db_map_ids, entity_type)[source]

Pushes parameter_value ids.

_update_ids(self, db_map_ids, key)[source]

Updates ids for given database item.

Parameters
  • db_map_ids (dict) – mapping from DatabaseMappingBase to ids or Asterisk

  • key (str) – the key

_setdefault(self, db_map)[source]

Adds new id sets for given db_map or returns existing ones.

Parameters

db_map (DatabaseMappingBase) – a database map

Returns

mapping from item name to set of ids

Return type

dict

spinetoolbox.spine_db_signaller

Spine DB Signaller class.

authors
  1. Marin (KTH)

date

31.10.2019

Module Contents
Classes

SpineDBSignaller

Handles signals from DB manager and channels them to listeners.

class spinetoolbox.spine_db_signaller.SpineDBSignaller(db_mngr)[source]

Bases: PySide2.QtCore.QObject

Handles signals from DB manager and channels them to listeners.

Initializes the signaler object.

Parameters

db_mngr (SpineDBManager) –

add_db_map_listener(self, db_map, listener)[source]

Adds listener for given db_map.

remove_db_map_listener(self, db_map, listener)[source]

Removes db_map from the the maps listener listens to.

db_map_listeners(self, db_map)[source]
connect_signals(self)[source]

Connects signals.

receive_scenarios_added(self, db_map_data)[source]
receive_alternatives_added(self, db_map_data)[source]
receive_object_classes_added(self, db_map_data)[source]
receive_objects_added(self, db_map_data)[source]
receive_relationship_classes_added(self, db_map_data)[source]
receive_relationships_added(self, db_map_data)[source]
receive_entity_groups_added(self, db_map_data)[source]
receive_parameter_definitions_added(self, db_map_data)[source]
receive_parameter_values_added(self, db_map_data)[source]
receive_parameter_value_lists_added(self, db_map_data)[source]
receive_features_added(self, db_map_data)[source]
receive_tools_added(self, db_map_data)[source]
receive_tool_features_added(self, db_map_data)[source]
receive_tool_feature_methods_added(self, db_map_data)[source]
receive_scenarios_updated(self, db_map_data)[source]
receive_alternatives_updated(self, db_map_data)[source]
receive_object_classes_updated(self, db_map_data)[source]
receive_objects_updated(self, db_map_data)[source]
receive_relationship_classes_updated(self, db_map_data)[source]
receive_relationships_updated(self, db_map_data)[source]
receive_parameter_definitions_updated(self, db_map_data)[source]
receive_parameter_values_updated(self, db_map_data)[source]
receive_parameter_value_lists_updated(self, db_map_data)[source]
receive_features_updated(self, db_map_data)[source]
receive_tools_updated(self, db_map_data)[source]
receive_tool_features_updated(self, db_map_data)[source]
receive_tool_feature_methods_updated(self, db_map_data)[source]
receive_scenarios_removed(self, db_map_data)[source]
receive_alternatives_removed(self, db_map_data)[source]
receive_object_classes_removed(self, db_map_data)[source]
receive_objects_removed(self, db_map_data)[source]
receive_relationship_classes_removed(self, db_map_data)[source]
receive_relationships_removed(self, db_map_data)[source]
receive_entity_groups_removed(self, db_map_data)[source]
receive_parameter_definitions_removed(self, db_map_data)[source]
receive_parameter_values_removed(self, db_map_data)[source]
receive_parameter_value_lists_removed(self, db_map_data)[source]
receive_features_removed(self, db_map_data)[source]
receive_tools_removed(self, db_map_data)[source]
receive_tool_features_removed(self, db_map_data)[source]
receive_tool_feature_methods_removed(self, db_map_data)[source]
receive_error_msg(self, db_map_error_log)[source]
static _shared_db_map_data(db_map_data, db_maps)[source]
_call_in_listeners(self, callback, db_map_data)[source]
receive_session_refreshed(self, db_maps)[source]
receive_session_committed(self, db_maps, cookie)[source]
receive_session_rolled_back(self, db_maps)[source]
spinetoolbox.spine_db_worker

The SpineDBWorker class

authors
  1. Vennström (VTT) and M. Marin (KTH)

date

2.10.2019

Module Contents
Classes

SpineDBWorker

Does all the DB communication for SpineDBManager, in the non-GUI thread.

class spinetoolbox.spine_db_worker.SpineDBWorker(db_mngr)[source]

Bases: PySide2.QtCore.QObject

Does all the DB communication for SpineDBManager, in the non-GUI thread.

session_rolled_back[source]
_get_db_map_called[source]
_get_metadata_per_entity_called[source]
_get_metadata_per_parameter_value_called[source]
_close_db_map_called[source]
_add_or_update_items_called[source]
_readd_items_called[source]
_remove_items_called[source]
_commit_session_called[source]
_rollback_session_called[source]
connect_signals(self)[source]
get_db_map(self, *args, **kwargs)[source]
_get_db_map(self)[source]
close_db_map(self, db_map)[source]
_close_db_map(self, db_map)[source]
get_metadata_per_entity(self, db_map, entity_ids)[source]
_get_metadata_per_entity(self, db_map, entity_ids, d)[source]
get_metadata_per_parameter_value(self, db_map, parameter_value_ids)[source]
_get_metadata_per_parameter_value(self, db_map, parameter_value_ids, d)[source]
add_or_update_items(self, db_map_data, method_name, item_type, signal_name, readd=False, check=True)[source]

Adds or updates items in db.

Parameters
  • db_map_data (dict) – lists of items to add or update keyed by DiffDatabaseMapping

  • method_name (str) – attribute of DiffDatabaseMapping to call for performing the operation

  • item_type (str) – item type

  • signal_name (str) – signal attribute of SpineDBManager to emit if successful

  • readd (bool) – Whether or not to readd items

  • check (bool) – Whether or not to check integrity

_add_or_update_items(self, db_map_data, method_name, item_type, check, signal_name)[source]
_do_add_or_update_items(self, db_map_data, method_name, item_type, check, signal_name)[source]
_readd_items(self, db_map_data, method_name, item_type, signal_name)[source]
_do_readd_items(self, db_map_data, method_name, item_type, signal_name)[source]
remove_items(self, db_map_typed_ids)[source]

Removes items from database.

Parameters

db_map_typed_ids (dict) – lists of items to remove, keyed by item type (str), keyed by DiffDatabaseMapping

_remove_items(self, db_map_typed_ids)[source]
_do_remove_items(self, db_map_typed_ids)[source]
commit_session(self, dirty_db_maps, commit_msg, cookie=None)[source]

Initiates commit session action for given database maps in the worker thread.

Parameters
  • dirty_db_maps (Iterable of DiffDatabaseMapping) – database mapping to commit

  • commit_msg (str) – commit message

  • cookie (Any) – a cookie to include in session_committed signal

_commit_session(self, dirty_db_maps, commit_msg, undo_stacks, cookie=None)[source]

Commits session for given database maps.

Parameters
  • dirty_db_maps (Iterable of DiffDatabaseMapping) – database mapping to commit

  • commit_msg (str) – commit message

  • undo_stacks (dict of AgedUndoStack) – undo stacks that outlive the DB manager

  • cookie (Any) – a cookie to include in session_committed signal

rollback_session(self, dirty_db_maps)[source]

Initiates rollback session action for given database maps in the worker thread.

Parameters

dirty_db_maps (Iterable of DiffDatabaseMapping) – database mapping to roll back

_rollback_session(self, dirty_db_maps, undo_stacks)[source]

Rolls back session for given database maps.

Parameters
  • dirty_db_maps (Iterable of DiffDatabaseMapping) – database mapping to roll back

  • undo_stacks (dict of AgedUndoStack) – undo stacks that outlive the DB manager

spinetoolbox.spine_engine_manager

Contains SpineEngineManagerBase.

authors
  1. Marin (KTH)

date

14.10.2020

Module Contents
Functions

make_engine_manager(engine_server_address)

class spinetoolbox.spine_engine_manager.SpineEngineManagerBase[source]
abstract run_engine(self, engine_data)[source]

Runs an engine with given data.

Parameters

engine_data (dict) – The engine data.

abstract get_engine_event(self)[source]

Gets next event from engine currently running.

Returns

two element tuple: event type identifier string, and event data dictionary

Return type

tuple(str,dict)

abstract stop_engine(self)[source]

Stops engine currently running.

abstract answer_prompt(self, 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(self, connection_file)[source]

Restarts the jupyter kernel associated to given connection file.

Parameters

connection_file (str) – path of connection file

abstract shutdown_kernel(self, 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(self, persistent_key, command)[source]

Issues a command to a persistent process.

Parameters
  • persistent_key (tuple) – persistent identifier

  • command (str) – command to issue

Returns

stdio and stderr messages (dictionaries with two keys: type, and data)

Return type

generator

abstract restart_persistent(self, persistent_key)[source]

Restart a persistent process.

Parameters

persistent_key (tuple) – persistent identifier

abstract interrupt_persistent(self, persistent_key)[source]

Interrupts a persistent process.

Parameters

persistent_key (tuple) – persistent identifier

abstract get_persistent_completions(self, 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(self, persistent_key, index)[source]

Returns an item from persistent history.

Parameters
  • persistent_key (tuple) – persistent identifier

  • index (int) – index of the history item, most recent first

Returns

history item or empty string if none

Return type

str

class spinetoolbox.spine_engine_manager.RemoteSpineEngineManager(engine_server_address)[source]

Bases: SpineEngineManagerBase

Parameters

engine_server_address (str) –

_ENCODING = ascii[source]
run_engine(self, engine_data)[source]

See base class.

get_engine_event(self)[source]

See base class.

stop_engine(self)[source]

See base class.

abstract answer_prompt(self, item_name, accepted)[source]

See base class.

restart_kernel(self, connection_file)[source]

See base class.

shutdown_kernel(self, connection_file)[source]

See base class.

abstract issue_persistent_command(self, persistent_key, command)[source]

See base class.

abstract restart_persistent(self, persistent_key)[source]

See base class.

abstract interrupt_persistent(self, persistent_key)[source]

See base class.

abstract get_persistent_completions(self, persistent_key, text)[source]

See base class.

_send(self, request, *args, receive=True)[source]

Sends a request to the server with the given arguments.

Parameters
  • request (str) – One of the supported engine server requests

  • args – Request arguments

  • receive (bool, optional) – If True (the default) also receives the response and returns it.

Returns

response, or None if receive is False

Return type

str or NoneType

_recvall(self)[source]

Receives and returns all data in the current request.

Returns

str

class spinetoolbox.spine_engine_manager.LocalSpineEngineManager[source]

Bases: SpineEngineManagerBase

run_engine(self, engine_data)[source]

Runs an engine with given data.

Parameters

engine_data (dict) – The engine data.

get_engine_event(self)[source]

Gets next event from engine currently running.

Returns

two element tuple: event type identifier string, and event data dictionary

Return type

tuple(str,dict)

stop_engine(self)[source]

Stops engine currently running.

answer_prompt(self, item_name, accepted)[source]

Answers prompt.

Parameters
  • item_name (str) – The item that emitted the prompt

  • accepted (bool) – The user’s decision.

restart_kernel(self, connection_file)[source]

Restarts the jupyter kernel associated to given connection file.

Parameters

connection_file (str) – path of connection file

shutdown_kernel(self, connection_file)[source]

Shuts down the jupyter kernel associated to given connection file.

Parameters

connection_file (str) – path of connection file

issue_persistent_command(self, persistent_key, command)[source]

Issues a command to a persistent process.

Parameters
  • persistent_key (tuple) – persistent identifier

  • command (str) – command to issue

Returns

stdio and stderr messages (dictionaries with two keys: type, and data)

Return type

generator

restart_persistent(self, persistent_key)[source]

Restart a persistent process.

Parameters

persistent_key (tuple) – persistent identifier

interrupt_persistent(self, persistent_key)[source]

Interrupts a persistent process.

Parameters

persistent_key (tuple) – persistent identifier

get_persistent_completions(self, 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(self, persistent_key, index)[source]

Returns an item from persistent history.

Parameters
  • persistent_key (tuple) – persistent identifier

  • index (int) – index of the history item, most recent first

Returns

history item or empty string if none

Return type

str

spinetoolbox.spine_engine_manager.make_engine_manager(engine_server_address)[source]
spinetoolbox.spine_engine_worker

Contains SpineEngineWorker. :authors: M. Marin (KTH) :date: 14.10.2020

Module Contents
Classes

SpineEngineWorker

param engine_server_address

Address of engine server if any

Functions

_handle_dag_execution_started(project_items)

_handle_node_execution_started(item, direction)

_handle_node_execution_finished(item, direction, state, item_state)

_handle_event_message_arrived(item, filter_id, msg_type, msg_text)

_handle_process_message_arrived(item, filter_id, msg_type, msg_text)

_handle_prompt_arrived(prompt, engine_mngr)

_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_started(item, direction)[source]
spinetoolbox.spine_engine_worker._handle_node_execution_finished(item, direction, state, 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)[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_server_address, engine_data, dag, dag_identifier, project_items, logger)[source]

Bases: PySide2.QtCore.QObject

Parameters
  • engine_server_address (str) – Address of engine server if any

  • engine_data (dict) – engine data

  • dag (DirectedGraphHandler) –

  • dag_identifier (str) –

  • project_items (dict) – mapping from project item name to ProjectItem

  • logger (LoggerInterface) – a logger

finished[source]
_dag_execution_started[source]
_node_execution_started[source]
_node_execution_finished[source]
_event_message_arrived[source]
_process_message_arrived[source]
_prompt_arrived[source]
_all_items_failed[source]
property engine_data(self)[source]

Engine data dictionary.

get_engine_data(self)[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(self, engine_data)[source]

Sets the engine data.

Parameters

engine_data (dict) – New data

_handle_event_message_arrived(self, item, filter_id, msg_type, msg_text)[source]
_handle_process_message_arrived(self, item, filter_id, msg_type, msg_text)[source]
stop_engine(self)[source]
engine_final_state(self)[source]
thread(self)[source]
_connect_log_signals(self, silent)[source]
start(self, 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.

do_work(self)[source]

Does the work and emits finished when done.

_process_event(self, event_type, data)[source]
_handle_prompt(self, prompt)[source]
_handle_standard_execution_msg(self, msg)[source]
_handle_persistent_execution_msg(self, msg)[source]
_handle_kernel_execution_msg(self, msg)[source]
_handle_process_msg(self, data)[source]
_do_handle_process_msg(self, item_name, filter_id, msg_type, msg_text)[source]
_handle_event_msg(self, data)[source]
_do_handle_event_msg(self, item_name, filter_id, msg_type, msg_text)[source]
_handle_node_execution_started(self, data)[source]
_do_handle_node_execution_started(self, item_name, direction)[source]

Starts item icon animation when executing forward.

_handle_node_execution_finished(self, data)[source]
_do_handle_node_execution_finished(self, item_name, direction, state, item_state)[source]
clean_up(self)[source]
spinetoolbox.ui_main

Contains ToolboxUI class.

author
  1. Savolainen (VTT)

date

14.12.2017

Module Contents
Classes

ToolboxUI

Class for application main GUI functions.

class spinetoolbox.ui_main.ToolboxUI[source]

Bases: PySide2.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]
eventFilter(self, obj, ev)[source]
connect_signals(self)[source]

Connect signals.

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

Updates obsolete settings.

_update_execute_enabled(self)[source]
_update_execute_selected_enabled(self)[source]
update_window_modified(self, clean)[source]

Updates window modified status and save actions depending on the state of the undo stack.

parse_project_item_modules(self)[source]

Collects data from project item factories.

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

Returns current project or None if no project open.

Returns

current project or None

Return type

SpineToolboxProject

qsettings(self)[source]

Returns application preferences object.

item_specification_factories(self)[source]

Returns project item specification factories.

Returns

specification factories

Return type

list of ProjectItemSpecificationFactory

update_window_title(self)[source]

Updates main window title.

init_project(self, 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(self)[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(self, name, description, location)[source]

Creates new project and sets it active.

Parameters
  • name (str) – Project name

  • description (str) – Project description

  • location (str) – Path to project directory

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

Yields all toolbars in the window.

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

Enables all project-related actions. Called when a new project is created and when a project is opened.

refresh_toolbars(self)[source]

Set toolbars’ color using highest possible contrast.

show_recent_projects_menu(self)[source]

Updates and sets up the recent projects menu to File-Open recent menu item.

save_project(self)[source]

Saves project.

save_project_as(self)[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(self, ask_confirmation=True)[source]

Closes the current project.

Returns

True when no project open or when it’s closed successfully, False otherwise.

Return type

bool

rename_project(self, _checked=False)[source]

Opens a dialog where the user can enter a new name for the project.

_update_project_name(self, new_name)[source]

Updates window title and recent projects.

Parameters

new_name (str) – project’s new name

init_project_item_model(self)[source]

Initializes project item model. Create root and category items and add them to the model.

init_specification_model(self)[source]

Initializes specification model.

make_item_properties_uis(self)[source]
add_project_items(self, 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(self, 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(self)[source]

Restore UI state from previous session.

clear_ui(self)[source]

Clean UI to make room for a new or opened project.

undo_critical_commands(self)[source]

Undoes critical commands in the undo stack.

Returns

False if any critical commands aren’t successfully undone

Return type

Bool

overwrite_check(self, 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

selected_item_names(self)[source]

Returns names of selected project items.

Returns

names of selected project items

Return type

list of str

item_selection_changed(self, selected, deselected)[source]

Synchronizes selection with scene. The scene handles item/link de/activation.

refresh_active_elements(self, active_project_item, active_link)[source]
_set_active_project_item(self, active_project_item)[source]
Parameters

active_project_item (ProjectItemBase or NoneType) –

Sets active link and connects to corresponding properties widget.

Parameters

active_link (JumpLink or Link, optional) –

activate_no_selection_tab(self)[source]

Shows ‘No Selection’ tab.

activate_item_tab(self)[source]

Shows active project item properties tab according to item type.

Shows link properties tab.

add_specification(self, specification)[source]

Pushes an AddSpecificationCommand to undo stack.

import_specification(self)[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(self, name, specification)[source]

Pushes an ReplaceSpecificationCommand to undo stack.

repair_specification(self, name)[source]

Repairs specification if it is broken.

Parameters

name (str) – specification’s name

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

Pushes a RemoveAllProjectItemsCommand to the undo stack.

register_anchor_callback(self, 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(self, qurl)[source]

Open file explorer in the directory given in qurl.

Parameters

qurl (QUrl) – The url to open

_change_specification_file_location(self, 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(self, ind, global_pos)[source]

Context menu for item specifications.

Parameters
  • ind (QModelIndex) – In the ProjectItemSpecificationModel

  • global_pos (QPoint) – Mouse position

edit_specification(self, 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(self, index)[source]

Removes specification from project.

Parameters

index (QModelIndex) – Index of the specification item

open_specification_file(self, index)[source]

Open the specification definition file in the default (.json) text-editor.

Parameters

index (QModelIndex) – Index of the item

new_db_editor(self)[source]
_handle_zoom_minus_pressed(self)[source]

Slot for handling case when ‘-‘ button in menu is pressed.

_handle_zoom_plus_pressed(self)[source]

Slot for handling case when ‘+’ button in menu is pressed.

_handle_zoom_reset_pressed(self)[source]

Slot for handling case when ‘reset zoom’ button in menu is pressed.

add_zoom_action(self)[source]

Setups zoom widget action in view menu.

restore_dock_widgets(self)[source]

Dock all floating and or hidden QDockWidgets back to the main window.

_add_actions(self)[source]

Sets adds actions to the main window.

set_debug_qactions(self)[source]

Sets shortcuts for QActions that may be needed in debugging.

add_menu_actions(self)[source]

Adds extra actions to Edit and View menu.

toggle_properties_tabbar_visibility(self)[source]

Shows or hides the tab bar in properties dock widget. For debugging purposes.

update_datetime(self)[source]

Returns a boolean, which determines whether date and time is prepended to every Event Log message.

add_message(self, msg)[source]

Append regular message to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_success_message(self, msg)[source]

Append message with green text color to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_error_message(self, msg)[source]

Append message with red color to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_warning_message(self, msg)[source]

Append message with yellow (golden) color to Event Log.

Parameters

msg (str) – String written to QTextBrowser

add_process_message(self, msg)[source]

Writes message from stdout to process output QTextBrowser.

Parameters

msg (str) – String written to QTextBrowser

add_process_error_message(self, msg)[source]

Writes message from stderr to process output QTextBrowser.

Parameters

msg (str) – String written to QTextBrowser

restore_original_logs_and_consoles(self)[source]
override_logs_and_consoles(self)[source]
override_item_log(self)[source]

Sets the log document of the active project item in Item Execution Log and updates title.

_do_override_item_log(self, document)[source]
override_console(self)[source]

Sets the jupyter console of the active project item in Jupyter Console and updates title.

_do_override_console(self, console)[source]
override_execution_list(self)[source]

Displays executions of the active project item in Executions and updates title.

restore_original_item_log_document(self)[source]

Sets the Item Execution Log document back to the original.

restore_original_console(self)[source]

Sets the Console back to the original.

_update_item_log_title(self)[source]

Updates Event Log title.

_set_override_console(self, console)[source]
_refresh_log_execution_list(self)[source]

Refreshes log executions as the active project item starts new executions.

_refresh_console_execution_list(self)[source]

Refreshes console executions as the active project item starts new executions.

static _refresh_execution_list(view, select)[source]
_select_log_execution(self, current, _previous)[source]

Sets the log documents of the selected execution in Event and Process Log.

_select_console_execution(self, current, _previous)[source]

Sets the console of the selected execution in Console.

_select_execution(self, view, current)[source]

Sets the log documents of the selected execution in Event and Process Log, and any consoles in Python and Julia Console.

show_add_project_item_form(self, item_type, x=0, y=0, spec='')[source]

Show add project item widget.

supports_specification(self, 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(self, 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(self, item_type, specification, item)[source]
show_settings(self)[source]

Show Settings widget.

show_about(self)[source]

Show About Spine Toolbox form.

show_user_guide(self)[source]

Open Spine Toolbox documentation index page in browser.

show_getting_started_guide(self)[source]

Open Spine Toolbox Getting Started HTML page in browser.

show_item_context_menu(self, pos)[source]

Context menu for project items listed in the project QTreeView.

Parameters

pos (QPoint) – Mouse position

show_project_item_context_menu(self, 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(self)[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(self)[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.

tear_down_consoles(self)[source]

CLoses the ‘base’ Python and Juliö Consoles if running.

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

Confirms exiting from user.

Returns

True if exit should proceed, False if user cancelled

_confirm_save_and_exit(self)[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(self, p)[source]

Removes entry that contains given path from the recent project files list in QSettings.

Parameters

p (str) – Full path to a project directory

update_recent_projects(self)[source]

Adds a new entry to QSettings variable that remembers twenty most recent project paths.

closeEvent(self, event)[source]

Method for handling application exit.

Parameters

event (QCloseEvent) – PySide2 event

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

Copies the selected project items to system’s clipboard.

project_item_from_clipboard(self, 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(self, duplicate_files=False)[source]

Duplicates the selected project items.

propose_item_name(self, prefix)[source]

Proposes a name for a project item.

The format is prefix_xx where xx is a counter value [01..99].

Parameters

prefix (str) – a prefix for the name

Returns

a name string

Return type

str

_share_item_edit_actions(self)[source]

Adds generic actions to project tree view and Design View.

_show_message_box(self, title, message)[source]

Shows an information message box.

_show_error_box(self, title, message)[source]
_connect_project_signals(self)[source]

Connects signals emitted by project.

_execute_project(self, checked=False)[source]

Executes all DAGs in project.

Parameters

checked (bool) – unused

_execute_selection(self, checked=False)[source]

Executes selected items.

Parameters

checked (bool) – unused

_stop_execution(self, checked=False)[source]

Stops execution in progress.

Parameters

checked (bool) – unused

_set_execution_in_progress(self)[source]
_unset_execution_in_progress(self)[source]
set_icon_and_properties_ui(self, item_name)[source]

Adds properties UI to given project item.

Parameters

item_name (str) – item’s name

project_item_properties_ui(self, 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(self, item_type)[source]
_open_project_directory(self, _)[source]

Opens project’s root directory in system’s file browser.

_open_project_item_directory(self, _)[source]

Opens project item’s directory in system’s file browser.

_remove_selected_items(self, _)[source]

Pushes commands to remove selected project items and links from project.

_rename_project_item(self, _)[source]

Renames current project item.

item_category_context_menu(self)[source]

Creates a context menu for category items.

Returns

category context menu

Return type

QMenu

project_item_context_menu(self, 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_base_julia_console(self)[source]

Shows and starts the ‘base’ Julia Console if not running or activates the window if running.

_start_base_python_console(self)[source]

Shows and starts the ‘base’ Python Console if not running or activates the window if running.

destroy_base_python_console(self)[source]
destroy_julia_console(self)[source]
make_jupyter_console(self, 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(self, 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

_shutdown_engine_kernels(self)[source]

Shuts down all kernels managed by Spine Engine.

restore_and_activate(self)[source]
spinetoolbox.version

Version info for Spine Toolbox package. Inspired by python sys.version and sys.version_info.

author
  1. Savolainen (VTT)

date

8.1.2020

Module Contents
Classes

VersionInfo

A class for a named tuple containing the five components of the version number: major, minor,

Attributes

major

minor

micro

releaselevel

serial

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

Create a version string following PEP 440

spinetoolbox.version.major = 0[source]
spinetoolbox.version.minor = 6[source]
spinetoolbox.version.micro = 6[source]
spinetoolbox.version.releaselevel = dev[source]
spinetoolbox.version.serial = 0[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