lib.lib

lib.py - Contains all the core functions and classes for the simulation and execution of the graphs.

Classes

Button(name, coords[, active])

Class to create and show buttons in the user interface.

DBlock(block_fn, sid, coords, color[, ...])

Class to initialize, mantain and modify function blocks.

DLine(sid, srcblock, srcport, dstblock, ...)

Class to initialize and maintain lines that connect blocks.

DSim()

Class that manages the simulation interface and main functions.

MenuBlocks(block_fn, fn_name, io_params, ...)

Class to create and show basic blocks used as a mark to generate functional blocks in the user interface.

SignalPlot(dt[, labels, xrange])

Class that manages the display of dynamic plots through the simulation.

TkWidget(name, params[, external])

Class used to create popup windows for changing data, like ports and parameters.

class lib.lib.Button(name, coords, active=True)

Class to create and show buttons in the user interface.

Parameters:
  • name (str) – Name of the variable associated to the button.

  • coords (list) – Coordinates of the button in the canvas.

  • active (bool) – Boolean that indicates the state of the function associated to the button.

draw_button(zone)
Purpose:

Draws the button.

class lib.lib.DBlock(block_fn, sid, coords, color, in_ports=1, out_ports=1, b_type=2, io_edit=True, fn_name='block', params={}, external=False, username='')

Class to initialize, mantain and modify function blocks.

Parameters:
  • block_fn (str) – Block name, defined according to the available blocks created in DSim.

  • sid (int) – Unique identification for the created block.

  • coords (list) – List with tuples that contain the location and size of the block in the canvas.

  • color (str/triplet) – String or triplet that defines the color of the block in the canvas.

  • in_ports (int) – Number of inputs for the block.

  • out_ports (int) – Number of outputs for the block.

  • b_type (int) – Variable for block type identification (0: source, 1: N_process, 2: Z_process, 3: drain).

  • io_edit (str) – Variable that defines if a block can change the number of its input ports and/or output ports.

  • fn_name (str) – Function name, function associated to the block. That function defined in the Functions class.

  • params (dict) – Dictionary with function-related parameters.

  • external (bool) – Parameter that set a block with an external function (not defined in Functions class).

  • username (str) – String that contains the name of the block previously assigned by the user

change_params()
Purpose:

Generates a pop-up window to change modifiable parameters only.

Description:

Through the use of the TkWidget class, a pop-up is created to modify parameters associated to the blocks. It should be noted that the only parameters that can be modified are those defined at the beginning (during the definition of the block in ‘DSim.menu_blocks_init’), as well as those that do not start with ‘_’ underscore. The function separates the parameters, they are shown to the user, returned to the system and all are put back together at the end.

change_port_numbers()
Purpose:

Generates a pop-up window for the user to change number of input and/or output ports for the block.

Description:

Through the use of the TkWidget class, a pop-up window is created containing 2 parameters that can be changed by the user: inputs and outputs. After loading them, the ‘update_Block’ function is executed to adjust the size of the block and the position of its ports. It should be noted that whether the number of inputs or outputs can be changed depends on the type of block, which is differentiated within the function.

draw_Block(zone)
Purpose:

Draws block and its ports.

Parameters:

zone – Pygame’s layer where the figure is drawn.

draw_selected(zone)
Purpose:

Draws the black line indicating that the block is selected.

Parameters:

zone – Pygame’s layer where the figure is drawn.

load_external_data(params_reset=False)
Purpose:

Loads initialization data of a function located in a external python file.

Description:

Through the use of the importlib library, a .py file is imported from the ‘usermodels’ folder, from where the function parameters and the block parameters (input, output, block_type) are extracted, importing them to the existing block, modifying its qualities if necessary.

loading_params(new_params)
Purpose:

Loads parameters from a dictionary list, converting lists in array vectors.

Parameters:

new_params – Dictionary with parameters for block.

port_collision(m_coords)
Purpose:

Checks if a point collides with one of the ports of a block. Returns a tuple with the port type and port id.

Parameters:

m_coords (tuple) – Coordinates of mouse input.

reload_external_data()
Purpose:

Reloads the external function parameters.

relocate_Block(new_coords)
Purpose:

Relocates port.

Parameters:

m_coords (tuple) – New coordinates for the block (left, top).

resize_Block(new_coords)
Purpose:

Resizes block.

Parameters:

m_coords (tuple) – New parameters for block (width, height).

saving_params()
Purpose:

Saves parameters only defined at initialization.

update_Block()
Purpose:

Updates location and size of the block, including its ports.

Description:

This function handles what is necessary to display the block on the screen. It draws the square of the block, draws the ports and places them depending on their quantity, and even extends or reduces the size of the block if the number of ports is not enough or too many. This function always acts when the block is updated, being much more important when it changes location.

class lib.lib.DLine(sid, srcblock, srcport, dstblock, dstport, points, cptr=0)

Class to initialize and maintain lines that connect blocks.

Parameters:
  • sid (int) – Unique identification for the created line.

  • srcblock (int) – Block from where the line starts.

  • srcport (int) – Port of the block where the line starts.

  • dstblock (int) – Block to where the line ends.

  • dstport (int) – Port of the block where the line ends.

  • points (list) – List of tuples that defines the vertex of the trajectory of the line (if it’s not a straight line).

  • cptr (int) – Variable used as a pointer to assign a color to the line. It depends on the ‘colors’ list defined in DSim.

change_color(ptr)
Purpose:

Pointer indicating which color is chosen from the color list defined in DSim.

Parameters:

ptr (int) – Value that adds or subtracts 1 depending of the user’s input.

collision(m_coords)
Purpose:

Checks if there is collision between a point and the line.

draw_line(zone)
Purpose:

Draws line.

Parameters:

zone – Pygame’s layer where the figure is drawn.

trajectory(points)
Purpose:

Generates segments to display a connection between blocks linked by a line.

Parameters:

points (list) – List with coordinates for each vertex of the line group.

update_line(block_list)
Purpose:

Updates line from size and location of blocks.

Description:

The function searches in the canvas for the location of the input and output ports to which it is connected, then produces a new trajectory using the ‘trajectory’ function.

class lib.lib.DSim

Class that manages the simulation interface and main functions.

Parameters:
  • SCREEN_WIDTH (int) – The width of the window

  • SCREEN_HEIGHT (int) – The height of the window

  • canvas_top_limit (int) – Top limit where blocks and lines must be drawn.

  • canvas_left_limit (int) – Left limit where blocks and lines must be drawn.

  • colors (dict) – List of predefined colors for elements that show in the canvas.

  • fps (int) – Base frames per seconds for pygame’s loop.

  • l_width (int) – Width of the line when a block or a line is selected.

  • ls_width (int) – Space between a selected block and the line that indicates the former is selected.

  • filename (str) – Name of the file that was recently loaded. By default is ‘data.dat’.

  • sim_time (float) – Simulation time for graph execution.

  • sim_dt (float) – Simulation sampling time for graph execution.

  • plot_trange (int) – Width in number of elements that must be shown when a graph is getting executed with dynamic plot enabled.

add_block(block, m_pos=(0, 0))
Purpose:

Function that adds a block to the interface, with a unique ID.

Description:

From a visible list of MenuBlocks objects, a complete Block instance is created, which is available for editing its parameters or connecting to other blocks.

Parameters:
  • block (BaseBlock class) – Base-block containing the base parameters for each type of block.

  • m_pos (tuple) – Coordinates (x, y) to locate the upper left corner of the future block.

Bugs:

Under a wrongly configured MenuBlock, the resulting block may not have the correct qualities or parameters.

add_line(srcData, dstData)
Purpose:

Function that adds a line to the interface, with a unique ID.

Description:

Based on the existence of one or more blocks, this function creates a line between the last selected ports.

Parameters:
  • srcData (triplet) – Triplet containing ‘block name’, ‘port number’, ‘port coordinates’ of an output port (starting point for the line).

  • dstData (triplet) – Triplet containing ‘block name’, ‘port number’, ‘port coordinates’ of an input port (finish point for the line).

check_diagram_integrity()
Purpose:

Checks if the graph diagram doesn’t have blocks with ports unconnected before the simulation execution.

Description:

This function is only used to check that the network is properly connected. All ports must be connected without exception. In case something is disconnected, a warning is printed indicating where the problem is and returns to the main function indicating that it cannot continue.

Returns:

0 if there are no errors, 1 if there are errors.

Return type:

int

check_global_list()
Purpose:

Checks if there are no blocks of a graph left unexecuted.

check_line_block(line, b_del_list)
Purpose:

Checks if a line is connected to one or more removed blocks.

Parameters:
  • line – Line object.

  • b_del_list – List of recently removed blocks.

check_line_port(line, block)
Purpose:

Checks if there are lines left from a removed port (associated to a block).

Parameters:
  • line – Line object.

  • block – Block object.

children_recognition(block_name, children_list)
Purpose:

For a block, checks all the blocks that are connected to its outputs and sends a list with them.

Parameters:
  • block_name (str) – Block object name id.

  • children_list (list) – List of dictionaries with blocks data that require the output of block ‘block_name’.

clear_all()
Purpose:

Cleans the screen from all blocks, lines and some main variables.

count_computed_global_list()
Purpose:

Counts the number of already computed blocks of a graph.

count_rk45_ints()
Purpose:

Checks all integrators and looks if there’s at least one that use ‘RK45’ as integration method.

display_blocks(zone)
Purpose:

Draws blocks defined in the main list on the screen.

Parameters:

zone – A layer in a pygame canvas where the figure is drawn.

display_buttons(zone)
Purpose:

Displays all the buttons on the screen.

Parameters:

zone – Pygame’s layer where the figure is drawn.

display_lines(zone)
Purpose:

Draws lines connecting blocks in the screen.

Parameters:

zone – Pygame’s layer where the figure is drawn.

display_menu_blocks(zone)
Purpose:

Draws MenuBlocks objects in the screen.

Parameters:

zone – Pygame’s layer where the figure is drawn.

dynamic_pyqtPlotScope(step)
Purpose:

Plots the data saved in Scope blocks dynamically with pyqtgraph.

Description:

This function is executed while the simulation is running, starting after all the blocks were executed in the first loop. It looks for Scope blocks, from which takes their ‘labels’ parameter and initializes a SignalPlot class object that uses pyqtgraph to show a graph. Then for each loop completed, it calls those Scope blocks again to get their vectors and update the graph with the new information.

execution_failed()
Purpose:

If an error is found while executing the graph, this function stops all the processes and resets values to the state before execution.

execution_init()
Purpose:

Initializes the graph execution.

Description:

This is the first stage of the graph simulation, where variables and vectors are initialized, as well as testing to verify that everything is working properly. A previous autosave is done, as well as a block connection check and possible algebraic loops. If everything goes well, we continue with the loop stage.

execution_init_time()
Purpose:

Creates a pop-up window to ask for graph simulation setup values.

Description:

The first step in order to be able to perform a network simulation, is to have the execution data. These are mainly simulation time and sampling period, but we also ask for variables needed for the graphs.

execution_loop()
Purpose:

Continues with the execution sequence in loop until time runs out or an special event stops it.

Description:

This is the second stage of the network simulation. Here the reading of the complete graph will be done cyclically until the time is up, the user indicates that it is finished (by pressing Stop) or simply until one of the blocks gives error. At the end, the data saved in blocks like ‘Scope’ and ‘External_data’, will be exported to other libraries to perform their functions.

export_data()
Purpose:

Exports the data saved in Export blocks in .npz format.

Description:

This function is executed after the simulation has finished or stopped. It looks for export blocks, which have some vectors saved with signal outputs from previous blocks. Then it merge all vectors in one big matrix, which is exported with the time vector to a .npz file, formatted in a way it is ready for graph libraries.

get_max_hierarchy()
Purpose:

Finds in the global execution list the max value in hierarchy.

get_neighbors(block_name)
Purpose:

Finds all the connected blocks to “block_name”.

Parameters:

block_name (str) – Block object name id.

get_outputs(block_name)
Purpose:

Finds all the blocks that need a “block_name” result as input.

Parameters:

block_name (str) – Block object name id.

main_buttons_init()
Purpose:

Creates a button list with all the basic functions available

menu_blocks_init()
Purpose:

Function that initializes all types of blocks available in the menu.

Description:

From the MenuBlocks class, base blocks are generated for the functions already defined in lib.functions.py. Then they are accumulated in a list so that they are available in the interface menu.

open()
Purpose:

Loads blocks, lines and other data from a .dat.

Description:

Starting from the .dat file, the data saved in the dictionaries are unpacked, updating the data in DSim, creating new blocks and lines, leaving the canvas and the configurations as they were saved before.

Notes:

The name of the loaded file is saved in the system, in order to facilitate the saving of data in it (overwriting it).

plot_again()
Purpose:

Plots the data saved in Scope blocks without needing to execute the simulation again.

port_availability(dst_line)
Purpose:

Checks if an input port is free to get connected with a line to another port.

Parameters:

dst_line (str) – The name of a Line object.

pyqtPlotScope()
Purpose:

Plots the data saved in Scope blocks using pyqtgraph.

Description:

This function is executed while the simulation has stopped. It looks for Scope blocks, from which takes their ‘vec_labels’ parameter to get the labels of each vector and the ‘vector’ parameter containing the vector (or matrix if the input for the Scope block was a vector) and initializes a SignalPlot class object that uses pyqtgraph to show a graph.

remove_block_and_lines()
Purpose:

Function to remove blocks or lines.

Description:

Removes a block or a line depending on whether it is selected or not.

Notes:

Lines associated to a block being removed are also removed.

reset_execution_data()
Purpose:

Resets the execution state for all the blocks of a graph.

reset_memblocks()
Purpose:

Resets the “_init_start_” parameter in all blocks.

save(autosave=False)
Purpose:

Saves blocks, lines and other data in a .dat file.

Description:

Obtaining the location where the file is to be saved, all the important data of the DSim class, each one of the blocks and each one of the lines, are copied into dictionaries, which will then be loaded to the external file by means of the JSON library.

Parameters:

autosave (bool) – Flag that defines whether the process to be performed is an autosave or not.

Notes:

This function is executed automatically when you want to simulate, so as not to lose unsaved information.

screenshot(zone)
Purpose:

Takes a capture of the screen with all elements seen on display.

Parameters:

zone – Pygame’s layer where the figures, lines and buttons are drawn.

set_color(color)
Purpose:

Defines color for an element drawn in pygame.

Parameters:

color (str/(float, float, float)) – The color in string or rgb to set.

update_blocks_data(block_data)
Purpose:

Updates information related with all the blocks saved in a file to the current simulation.

Parameters:

block_data (dict) – Dictionary with Block object id, parameters, variables, etc.

update_global_list(block_name, h_value, h_assign=False)
Purpose:

Updates the global execution list.

Parameters:
  • block_name (str) – Block object name id.

  • h_value (int) – Value in graph hierarchy.

  • h_assign (bool) – Flag that defines if the block gets assigned with h_value or not.

update_lines()
Purpose:

Updates lines according to the location of blocks if these changed place.

update_lines_data(line_data)
Purpose:

Updates information related with all the lines saved in a file to the current simulation.

Parameters:

line_data (dict) – Dictionary with Line object id, parameters, variables, etc.

update_sim_data(data)
Purpose:

Updates information related with the main class variables saved in a file to the current simulation.

Parameters:

data (dict) – Dictionary with DSim parameters.

class lib.lib.MenuBlocks(block_fn, fn_name, io_params, ex_params, b_color, coords, external=False)

Class to create and show basic blocks used as a mark to generate functional blocks in the user interface.

Parameters:
  • block_fn (str) – Block type, defined according to the available blocks created in DSim

  • fn_name (str) – Function name, function associated to the block type. That function defined in the Functions class.

  • io_params (dict) – Dictionary with block-related parameters (input ports, output ports, b_type, edit inputs/outputs).

  • ex_params (dict) – Dictionary with function-related parameters.

  • b_color (str/triplet) – String or triplet that defines the color of the block in the canvas.

  • coords (list) – List with tuples that contain the location and size of the block in the canvas.

  • external (bool) – Parameter that set a block with an external function (not defined in Functions class).

draw_menublock(zone, pos)
Purpose:

Draws the menu block.

class lib.lib.SignalPlot(dt, labels=['default'], xrange=100)

Class that manages the display of dynamic plots through the simulation. WARNING: It uses pyqtgraph as base (MIT license, but interacts with PyQT5 (GPL)).

Parameters:
  • dt (float) – Sampling time of the system.

  • labels (list) – List of names of the vectors.

  • xrange (int) – Maximum number of elements to plot in axis x.

loop(new_t, new_y)
Purpose:

Updates the time and scope vectors and plot them.

pltcolor(index, hues=9, hueOff=180, minHue=0, maxHue=360, val=255, sat=255, alpha=255)
Purpose:

Assigns a color to a vector for plotting purposes.

sort_labels(labels)
Purpose:

Rearranges the list if some elements are lists too.

sort_vectors(ny)
Purpose:

Rearranges all vectors in one matrix.

class lib.lib.TkWidget(name, params, external=False)

Class used to create popup windows for changing data, like ports and parameters.

Parameters:
  • name (str) – Name of the source (class, block, line, element that calls this class function).

  • params (dict) – Parameters of the source to display in the popup window.

create_entry_widget(x)
Purpose:

Creates a new entry for the widget.

destroy()
Purpose:

Finishes the window instance.

external_toggle()
Purpose:

Creates a prompt to reset value parameters from a external block.

get_values()
Purpose:

Gets values in a dictionary after the pop-up window is closed.

string_to_vector(string)
Purpose:

Converts the string into an array vector.

Description:

This function takes the resulting string and checks whether or not it corresponds to a vector. The function supports receiving up to a three-dimensional array.