populse_mia.user_interface.data_browser package¶
Handle the data browser tab. Visualize, modify and search data.
- Contains:
- Module:
advanced_search
count_table
data_browser
mini_viewer
modify_table
rapid_search
Submodules¶
populse_mia.user_interface.data_browser.advanced_search module¶
Module to define the advanced search.
- Contains:
- Class:
AdvancedSearch
- class populse_mia.user_interface.data_browser.advanced_search.AdvancedSearch(project, data_browser, scans_list=None, tags_list=None, from_pipeline=False)[source]¶
Bases:
QWidgetClass that manages the widget of the advanced search
The advanced search creates a complex query to the database and is a combination of several “query lines” which are linked with AND or OR and all composed of: - A negation or not - A tag name or all visible tags - A condition (==, !=, >, <, >=, <=, CONTAINS, IN, BETWEEN) - A value
- __init__(project, data_browser, scans_list=None, tags_list=None, from_pipeline=False)[source]¶
Initialize the AdvancedSearch widget.
- Parameters:
project – The current project instance.
data_browser – The parent DataBrowser widget that contains this search.
scans_list – List of document scans to search within. Defaults to empty list.
tags_list – List of tags to display in the search interface. Defaults to empty list.
(bool) (from_pipeline) – Whether the widget is instantiated from the pipeline manager. Defaults to False.
- add_search_bar()[source]¶
Add an advanced search bar row to the search interface.
- Creates a complete search row containing:
NOT operator toggle
Field selector (populated with available tags)
Condition operator selector (==, !=, >, <, etc.)
Value input field
Remove button to delete this row
The row components are connected with signals to update dynamically based on field type and selected condition.
- apply_filter(filter)[source]¶
Apply a filter to update the displayed scans in the data browser.
Retrieves documents from the database based on the provided filter criteria and updates the table visualization accordingly. If the filter is invalid or an error occurs, displays a warning and reverts to showing all scans.
- Parameters:
filter –
Filter object containing the query criteria with attributes:
nots (list): Negation flags for each condition
values (list): Values to match against
- conditions (list): Comparison operators
(e.g., ‘==’, ‘>’, ‘<’)
- links (list): Logical operators connecting
conditions (‘AND’, ‘OR’)
fields (list): Database fields to query
- Side Effects:
Updates self.rows with filter parameters
Modifies self.data_browser.table_data.scans_to_visualize
May display a warning dialog on error
Calls self.data_browser.table_data.update_visualized_rows()
- displayConditionRules(field, condition)[source]¶
Update available condition operators based on the selected field’s type.
Dynamically adjusts the condition dropdown to show only operators that are valid for the selected field’s data type. Numeric fields allow comparison operators (<, >, <=, >=, BETWEEN), while non-numeric fields exclude them. List fields exclude the IN operator, while non-list fields include it.
- Parameters:
field – QComboBox widget containing the selected tag name.
condition – QComboBox widget whose items will be updated based on the field’s type.
- Behavior:
Numeric types: Include <, >, <=, >=, BETWEEN operators
String/Boolean/List types: Exclude comparison operators
List types: Exclude IN operator
Non-list types: Include IN operator
Special case “All visualized tags”: Treated as non-numeric
- displayValueRules(choice, value)[source]¶
Configure the value input widget based on the selected condition operator.
Adjusts the enabled state and placeholder text of the value input to match the requirements of the selected condition operator.
- Parameters:
choice – QComboBox containing the selected condition operator.
value – QLineEdit widget that will be configured.
- Behavior:
BETWEEN: Enabled with placeholder “value1; value2”
IN: Enabled with placeholder for semicolon-separated list
HAS VALUE/HAS NO VALUE: Disabled and cleared
Other operators: Enabled with no placeholder
- get_filters(replace_all_by_fields)[source]¶
Extract filter criteria from UI widgets.
Parses the filter rows to extract search criteria including fields, conditions, values, logical operators, and negation flags. Handles special cases like “All visualized tags” expansion and operator compatibility validation.
- Parameters:
replace_all_by_fields – If True, replaces “All visualized tags” with the actual list of visible fields. If False, keeps the literal “All visualized tags” text.
- Return (tuple):
A 5-tuple containing: - fields (list): Field names to filter on - conditions (list): Comparison operators (e.g., ‘=’, ‘BETWEEN’) - values (list): Filter values (strings or lists for BETWEEN/IN) - links (list): Logical operators connecting filters (AND/OR) - nots (list): Negation flags for each filter
- Note:
BETWEEN and IN conditions have their values split into lists
Fields incompatible with operators are automatically removed
- launch_search()[source]¶
Execute search query and update the data browser table.
Retrieves filter parameters, constructs and executes a database query, then updates the data browser’s visualized scans with the results. If the search fails, displays an error dialog and reverts to showing all available scans.
- Side Effects:
Updates self.data_browser.table_data.scans_to_visualize
Updates self.data_browser.table_data.scans_to_search
Updates self.project.currentFilter (if not from_pipeline)
Displays error dialog on search failure
- static prepare_filters(links, fields, conditions, values, nots, scans)[source]¶
Construct a filter query string from filter components.
Builds a query by combining multiple filter rows with logical operators (AND/OR), where each row can filter across multiple fields with optional negation.
- Parameters:
links – Logical operators joining filter rows (e.g., [‘AND’, ‘OR’]). Length should be len(fields) - 1.
fields – Nested list where each sublist contains field names to filter on. Fields within a row are OR-combined.
conditions – Filter operators for each row. Supported values: ‘==’, ‘!=’, ‘<’, ‘>’, ‘<=’, ‘>=’, ‘IN’, ‘BETWEEN’, ‘CONTAINS’, ‘HAS VALUE’, ‘HAS NO VALUE’.
values – Filter values corresponding to each condition. For ‘BETWEEN’, provide a two-element sequence [min, max].
nots – Negation flags for each row (‘NOT’ to negate, empty string otherwise).
scans – List of scan identifiers to restrict the search scope.
- Returns:
Complete filter query string with all conditions and scan restrictions.
- refresh_search()[source]¶
Refresh the search widget by rebuilding its layout with the current filters.
- This method performs the following steps:
Retrieves the current filter values without replacing “All visualized tags”.
Clears the old layout and cleans up its widgets.
Removes and restores row borders according to the links.
Rebuilds the main grid layout with all row widgets.
Adds the search button in a horizontal layout at the bottom.
Sets the new combined layout as the widget’s layout.
- remove_row(row_layout)[source]¶
Remove a specified row from the layout while ensuring at least one row remains.
This method deletes all widgets in the specified row, removes the row from the internal rows list, and refreshes the view.
- Parameters:
row_layout – The row (list of widgets) to remove.
- rows_borders_added(links)[source]¶
Add UI controls (links and add button) to search query rows.
Adds a green plus button to the last row for adding new search bars, and adds AND/OR combo boxes to all rows except the first one for linking query conditions.
- Parameters:
links – List of previously selected link operators (‘AND’/’OR’) to restore when rebuilding the UI.
populse_mia.user_interface.data_browser.count_table module¶
Medical Scan Completeness Verification Tool
This module provides a sophisticated quality assurance tool for medical imaging projects, enabling systematic verification of scan completeness through interactive tag-based analysis. The tool helps identify missing scans, incomplete datasets, and data inconsistencies across multiple metadata dimensions.
The primary component is a dynamic table-based interface that visualizes all possible combinations of selected metadata tags (patient names, scan types, time points, etc.) and indicates which combinations have corresponding scan data available.
- Core Functionality:
Interactive tag selection with expandable interface (2 to n tags)
Real-time database querying and scan counting
Matrix visualization of tag combinations vs. data availability
- Visual indicators: ✓ (green checkmark) for present data,
✗ (red cross) for missing
Detailed tooltips showing specific scan filenames
Statistical summaries with total counts per category
- Use Cases:
Quality assurance before data analysis
Identifying incomplete patient visits or missing sequences
Verifying protocol compliance across studies
Dataset completeness reporting
Pre-processing validation for longitudinal studies
- Technical Features:
Efficient database integration with lazy loading
Dynamic UI generation based on selected metadata
Scalable to handle large datasets with multiple tag dimensions
Qt-based interface with responsive table resizing
Memory-efficient combination generation using odometer algorithms
- Example Workflow:
Select relevant metadata tags (e.g., PatientName, TimePoint, SequenceName)
Generate combination matrix showing all expected data points
Review visual indicators to identify missing scans
Use tooltips to examine specific scan files
Export or act on completeness findings
- Contains:
- Class:
- CountTable: Main dialog class providing the scan verification
interface
- class populse_mia.user_interface.data_browser.count_table.CountTable(project)[source]¶
Bases:
QDialogA visual tool for verifying medical scan completeness through tag combination analysis.
This dialog provides an interactive interface to analyze medical scan data by selecting multiple tags (metadata fields) and displaying their combinations in a matrix format. The tool helps identify missing scans by showing which combinations of tag values have corresponding data.
The interface consists of: - Dynamic tag selection buttons (expandable from 2 to n tags) - Add/remove controls for tag management - A results table showing all possible combinations - Visual indicators (✓/✗) for data presence/absence
- Table Structure:
Rows: All combinations of the first (n-1) selected tags
Columns: First (n-1) tag names + values of the last tag
Cells: Count of matching scans or absence indicator
Footer: Total counts per column
- Example:
With tags [PatientName, TimePoint, SequenceName] for 2 patients (P1, P2), 3 timepoints (T1, T2, T3), and sequences (RARE, MDEFT, FLASH):
- Key Features:
Dynamic tag addition/removal
Real-time scan counting
Visual missing data indicators
Hover tooltips showing specific scan files
Automatic table resizing
- __init__(project) None[source]¶
Initialize the CountTable with the given project.
- Parameters:
project – The current medical imaging project containing scan database
- count_scans() None[source]¶
Generate and populate the scan count table.
Creates a matrix showing all combinations of selected tag values, with counts or indicators for each combination’s scan availability. Early returns if no tags are selected or if database access fails.
- fill_first_tags() None[source]¶
Populate table cells for the first (n-1) selected tags.
Generates all possible combinations of the first n-1 tag values and fills corresponding table cells. Also adds total counts in the bottom row.
- fill_headers() None[source]¶
Populate table headers with tag names and last tag values.
- Sets horizontal headers for:
First n-1 columns: tag names
Remaining columns: values of the last selected tag
Also adds a “Total” row header.
- fill_last_tag() None[source]¶
Populate cells for the last selected tag with scan counts or indicators.
- For each combination of first n-1 tags and each value of the last tag:
Queries database for matching scans
Shows count with checkmark if scans exist
Shows red X if no scans found
Adds scan filenames as tooltip
Updates column totals
- fill_values(idx: int) None[source]¶
Populate values list for the tag at the specified index.
Extracts all unique values for the selected tag from the database and stores them for table generation.
- Parameters:
(Int) (idx) – Index of the select tag
populse_mia.user_interface.data_browser.data_browser module¶
Module to define data browser tab appearance, settings and methods.
- Contains:
- Class:
DataBrowser
DateFormatDelegate
DateTimeFormatDelegate
NumberFormatDelegate
TableDataBrowser
TimeFormatDelegate
- class populse_mia.user_interface.data_browser.data_browser.DataBrowser(project, main_window)[source]¶
Bases:
QWidgetWidget that manages and displays the contents of the Data Browser tab.
The Data Browser provides an interface for viewing, filtering, tagging, and sending documents to the pipeline manager. It integrates tools for advanced search, tag management, and visual inspection of loaded data.
- __init__(project, main_window)[source]¶
Initialization of the data_browser class.
- Parameters:
project – Current project in the software
main_window – Main window of the software
- add_tag_infos(new_tag_name, new_default_value, tag_type, new_tag_description, new_tag_unit)[source]¶
Add a new tag to both current and initial database collections.
This method creates a new tag field in the database schema and populates it with default values for all existing scans. The operation is tracked in the project’s undo/redo history.
- Parameters:
(str) (new_tag_unit) – Name of the new tag to create
new_default_value – Default value to assign to all existing scans
(str) – Data type of the tag (e.g., FIELD_TYPE_STRING, FIELD_TYPE_FLOAT)
(str) – Human-readable description of the tag
(str) – Unit of measurement for the tag value
- Note:
Marks the project as having unsaved modifications
Adds the operation to the undo history
Updates the UI table with the new column
- add_tag_pop_up()[source]¶
Display a popup window for adding a new tag to the project.
This method initializes and shows a PopUpAddTag dialog, allowing the user to add a new tag to the current project. The popup is modal and tied to the current project context.
- clone_tag_infos(tag_to_clone, new_tag_name)[source]¶
Clone a tag and its associated data, creating a new tag with the same attributes and values.
This method clones the specified tag, including its schema and data, into a new tag. The new tag is added to both the current and initial collections, and all existing values for the original tag are copied to the new tag. The operation is recorded in the project’s undo history.
- Parameters:
(str) (new_tag_name) – Name of the tag to clone
(str) –
Name of the new tag to create
- Notes:
The new tag is added to the database schema and data for both COLLECTION_CURRENT amd COLLECTION_INITIAL collections.
The project’s unsaved modifications flag is set to True.
The operation is recorded in the project’s undo history.
- connect_actions()[source]¶
Connect UI actions to their corresponding methods.
Binds each action’s triggered signal to the appropriate slot method, enabling interactive functionality for tag management and filter operations.
- move_splitter()[source]¶
Connect the mini viewer if the splitter is not at its minimum position.
Checks whether the bottom pane of the vertical splitter is at its minimum height. If it’s larger than the minimum, connects the mini viewer.
- open_filter()[source]¶
Display a dialog for selecting and opening a saved project filter.
Creates and shows a PopUpSelectFilter dialog, allowing the user to choose from previously saved filters associated with the current project. The dialog is stored as an instance attribute to maintain a reference during its lifetime.
- open_filter_infos()[source]¶
Apply the current project filter to the data table.
Opens the advanced search interface if the filter contains exclusion criteria (nots), updates the search bar text, and refreshes the visualized scans to match the filtered document collection.
- The method:
Retrieves documents from the current collection
Updates scans_to_visualize and scans_to_search
Applies the filter’s search bar text
Shows advanced search interface if exclusion filters exist
- remove_tag_infos(tag_names_to_remove)[source]¶
Remove specified tags from the database and update the UI.
This method removes tags from both the current and initial collections, preserving tag attributes and values in the undo history. The table display is updated to reflect the changes.
- Parameters:
tag_names_to_remove – Iterable of tag names (str) to remove from the database and table display.
- Side Effects:
Marks project as having unsaved modifications
Adds removal operation to undo history
Clears redo history
Removes columns from table display
Temporarily disconnects and reconnects table selection signal
- remove_tag_pop_up()[source]¶
Display a modal dialog for removing user tags from the project.
Creates and shows a PopUpRemoveTag instance, allowing the user to select and remove tags associated with the current project.
- reset_search_bar()[source]¶
Clear the search bar input field.
This method resets the search bar to an empty state by clearing any existing text content.
- search_str(str_search)[source]¶
Search and filter documents in the table based on a search string.
Updates the table’s visualized documents based on the search criteria. An empty string shows all searchable scans. The special value NOT_DEFINED_VALUE filters for documents with undefined field values.
- Parameters:
str_search – The search string to filter documents. Empty string returns all searchable scans. NOT_DEFINED_VALUE returns scans with undefined values.
- send_documents_to_pipeline()[source]¶
Display a popup dialog for sending filtered scans to the Pipeline Manager.
Retrieves the currently filtered scans from the table data and presents them in a selection popup, allowing the user to confirm which scans to send to the pipeline.
The popup is shown modally and references the main window as its parent.
- show_clone_tag_popup()[source]¶
Display a popup dialog for cloning a tag.
This method initializes and shows a popup dialog (PopUpCloneTag) to allow the user to clone a tag within the current project context.
The popup is stored as an instance variable for later reference if needed.
- toggle_advanced_search()[source]¶
Toggle the visibility of the advanced search interface.
If the advanced search is hidden, it resets and displays the search interface, updating the scans list to the current visualized scans. If the advanced search is visible, it hides the interface, resets the search state, and restores the original scans list to the data browser.
This method ensures the UI and data state are synchronized with the visibility of the advanced search.
- update_database(database)[source]¶
Update the project database and reset UI state.
This method propagates the database instance to all components that need it and resets UI elements to their default state. It’s called during project lifecycle events (new, open, save as).
- Parameters:
database – The new Database instance to use across the application.
- class populse_mia.user_interface.data_browser.data_browser.DateFormatDelegate(parent=None)[source]¶
Bases:
QItemDelegateA custom delegate for handling date editing in table views.
This delegate provides a QDateEdit widget for editing date values in table cells, with dates formatted as DD/MM/YYYY. It replaces the default text editor with a calendar-based date picker for improved user experience and data validation.
- __init__(parent=None)[source]¶
Initialize the DateFormatDelegate.
- Parameters:
parent – Optional parent QObject. Defaults to None.
- createEditor(parent, option, index)[source]¶
Create and return a QDateEdit widget for editing dates.
This method is called by the view when a cell needs to be edited. It creates a date editor with DD/MM/YYYY format.
- Parameters:
parent – The parent widget for the editor.
option – Style options for rendering the item.
index – The model index of the item being edited.
- Return (QDateEdit):
A configured date editor widget.
- class populse_mia.user_interface.data_browser.data_browser.DateTimeFormatDelegate(parent=None)[source]¶
Bases:
QItemDelegateCustom delegate for displaying and editing datetime values in table views.
This delegate provides a QDateTimeEdit widget for editing datetime cells, formatted as DD/MM/YYYY HH:MM:SS.mmm (day/month/year with milliseconds).
- DATETIME_FORMAT = 'dd/MM/yyyy hh:mm:ss.zzz'¶
- class populse_mia.user_interface.data_browser.data_browser.NumberFormatDelegate(parent=None)[source]¶
Bases:
QItemDelegateDelegate for handling numeric input in table cells.
The number of decimal places is automatically inferred from the existing cell value, ensuring consistent formatting of numeric inputs.
- __init__(parent=None)[source]¶
Initialize the NumberFormatDelegate.
- Parameters:
(QWidget) (parent) – The parent widget. Defaults to None.
- createEditor(parent, option, index)[source]¶
Create and configure a QDoubleSpinBox editor for numeric input.
The number of decimal places is determined by examining the current cell value.
- Parameters:
parent – Parent widget for the editor.
option – Style options for the item.
- Paramindex:
Model index of the item being edited.
- Return (QDoubleSpinBox):
A spin box editor configured with the appropriate decimal precision.
- class populse_mia.user_interface.data_browser.data_browser.TableDataBrowser(project, data_browser, tags_to_display, update_values, activate_selection, link_viewer=True)[source]¶
Bases:
QTableWidgetTable widget that displays the documents contained in the database and their associated tags.
- __init__(project, data_browser, tags_to_display, update_values, activate_selection, link_viewer=True)[source]¶
Initialize the data table widget with project data and browser context.
- Parameters:
(Project) (project) – The current project instance containing data and configuration.
(DataBrowser) (data_browser) – Parent DataBrowser widget that contains this table.
(list[str]) (tags_to_display) – List of metadata tags to show as table columns.
(bool) (update_values) – If True, enables cell editing; if False, table is read-only.
bool) (activate_selection (dict |) – Dictionary with process execution metadata for document generation, or False to disable selection functionality.
link_viewer(bool) – If True, links table selection to external viewer widget. Defaults to True.
- Notes:
Column sorting and reordering are enabled by default (except first column).
Extended selection mode is used unless
activate_selectionis falsy.A custom context menu is available only when both
activate_selectionandlink_viewerare True.
- add_column(column, tag)[source]¶
Add a new column to the table with the specified tag.
Inserts a column at the given index, configures its header with metadata from the database, sets the appropriate delegate based on field type, and populates cells with current values from the database.
- Parameters:
(int) (column) – Zero-based index where the column should be inserted.
(str) (tag) – Tag name identifying the field to add from the database.
- Note:
Temporarily disconnects item change signals during insertion to prevent unwanted event triggers, then reconnects them after completion.
- add_columns()[source]¶
Add and update table columns based on database fields.
This method synchronizes the table’s columns with the current database schema by:
Adding columns for new database fields that don’t exist in the table
Populating new columns with values from the database
Removing columns that no longer exist in the database
Applying appropriate formatting delegates based on field types
Maintaining column visibility settings
The method temporarily disconnects item change signals during operation to prevent unwanted events, then reconnects them after completion.
- Note:
The TAG_FILENAME column is always placed first
Columns are sorted alphabetically (except TAG_FILENAME)
System tags (TAG_CHECKSUM, TAG_HISTORY) are excluded
Undefined values are displayed in italic bold text
- add_path()[source]¶
Open a dialog to add documents to the current project.
Creates and displays a PopUpAddPath dialog that allows users to select and add document paths to the project’s data browser.
- add_rows(rows)[source]¶
Insert rows into the table if they don’t already exist.
This method adds new scans to the table, populating each column with data from the database. It displays a progress dialog during the operation and handles special cases like the TAG_BRICKS column with custom widgets.
- Parameters:
rows – An iterable of scan identifiers to be added to the table.
- Note:
Duplicate scans (already present in the table) are automatically skipped
Sorting is temporarily disabled during the insertion process
The first column (name) is set as non-editable
TAG_BRICKS columns receive custom button widgets for interaction
- clear_cell()[source]¶
Clear values from selected cells in the table.
This method removes data from the currently selected cells in the database and updates the UI to reflect the cleared state. The operation is recorded in the project’s undo history for potential reversal.
- The method performs the following actions for each selected cell:
Retrieves the current value from the database
Removes the value from the database
Updates the cell’s visual appearance (italic + bold)
Records the change for undo/redo functionality
- Side Effects:
Modifies database values in COLLECTION_CURRENT
Updates table cell formatting
Appends operation to project.undos
Clears project.redos
Create and display the context menu for the table, and perform the corresponding action based on the user’s selection.
- Parameters:
(QPoint) (position) – The mouse cursor position relative to the widget.
- delete_from_brick(brick_id)[source]¶
Delete a brick and its associated documents from the database.
This method cleans up the database when a pipeline (composed of multiple bricks) is initialized but not executed before another pipeline is started or the software is closed. It removes the brick and any orphaned output documents that are not used as inputs elsewhere.
- Parameters:
(str) (brick_id) – The unique identifier of the brick to be deleted.
- display_file()[source]¶
Open the selected file(s) in the user’s default application.
Iterates over all selected items in the view, resolves their absolute paths, and opens each file using the platform’s default application.
Supported platforms: Linux, macOS, and Windows.
- display_unreset_values()[source]¶
Displays a warning dialog listing values that cannot be reset.
This method shows a QMessageBox warning when certain values (such as user tags, FileName, or undefined cells) cannot be reset because they lack a raw value. The dialog includes a descriptive message and an OK button for dismissal.
- edit_table_data_values()[source]¶
Edit and update selected cell values in the DataBrowser table.
This method handles the selection of cells, validation of list lengths, and updating of values in both the table and the database. It supports list-type fields and ensures data consistency across selections.
- Steps:
Collects selected cells and their metadata (coordinates, types, lengths, etc.).
Validates list lengths for compatibility.
Opens a dialog for value modification if valid.
Updates the table and database, and records changes for undo/redo history.
- Note:
Exits early if the selected tag is ‘TAG_BRICKS’ or if the field type is not a list.
Disconnects and reconnects the itemChanged signal to prevent recursive updates.
- fill_cells_update_table()[source]¶
Initialize and populate table cells with scan data from the database.
- This method performs the following operations:
Creates a progress dialog to track cell population
Retrieves scan documents matching scans_to_visualize from the database
Populates each cell with appropriate data based on column type
Handles special cases (name column, bricks column)
Applies saved sorting preferences
Resizes rows and columns to fit content
- Special column handling:
Column 0 (name): Read-only, always displays as string
Bricks column: Displays clickable buttons for brick history
Other columns: Editable, type-specific formatting
- Notes:
Displays a modal progress dialog during population
Temporarily hides the table during updates for performance
Connects cell change signals after population completes
- fill_headers(take_tags_to_update=False)[source]¶
Initialize and populate table headers with field metadata.
- Sets up table columns based on database fields, configuring each with:
Appropriate tooltips showing description, unit, and type
Specialized delegates for numeric and temporal data types
Visibility based on display settings or field attributes
- Parameters:
take_tags_to_update – If True, use tags_to_display for visibility. If False, use field visibility attributes. Defaults to False.
- get_current_filter()[source]¶
Get the current data browser selection.
Returns the list of selected scan paths if a selection is active, otherwise returns all visible scan paths in the data browser.
- Return (list):
List of scan paths from either the current selection or all visible scans in the data browser.
- get_index_insertion(to_insert)[source]¶
Find the insertion index for a new column to maintain alphabetical order.
Uses binary search to efficiently locate the correct position for inserting a column header while preserving the existing alphabetical sort order.
- Parameters:
(str) (to_insert) – The column header text to insert.
- Return (int):
The column index where the new column should be inserted. Returns columnCount() if it should be appended at the end.
- Note: Assumes that column 0 is reserved (TAG_FILENAME must always be
the first tag on the left) and start the search from column 1.
- get_scan_row(scan)[source]¶
Find the row index for a given scan filename.
- Parameters:
scan – The scan filename to search for.
- Return(int):
The zero-based row index if the scan is found, None otherwise.
- get_tag_column(tag)[source]¶
Find the column index for a given tag name.
Searches through the table’s horizontal headers to locate the column corresponding to the specified tag.
- Parameters:
(str) (tag) – The name of the tag to search for.
- Return (int):
The zero-based column index if the tag is found, None otherwise.
- mouseReleaseEvent(event)[source]¶
Handle mouse release event and update table data.
This method is called when a mouse button is released over the widget. It delegates to the parent class handler and then updates the table data values.
- Parameters:
(QMouseEvent) (event) – The mouse event containing information about the button released, position, and modifiers.
- multiple_sort_infos(list_tags, order)[source]¶
Sort table rows by multiple tag values.
Sorts the visualized scans based on the values of specified tags, then reorganizes the table rows to reflect the new order. Handles both regular items and special brick widgets during the reordering.
- Parameters:
list_tags(list) – List of tag names to sort by (primary to secondary).
(str) (order) – Sort direction, either “Ascending” or “Descending”.
- Note:
Temporarily disables item change signals during sorting to prevent triggering update handlers. The sort is stable and preserves the relative order of items with equal sort keys.
- multiple_sort_pop_up()[source]¶
Display the multiple sort configuration dialog.
Creates and shows a modal dialog that allows users to configure multiple sorting criteria for the current project data.
- Note:
The dialog instance is stored in self.pop_up.
- on_cell_changed(item_origin)[source]¶
Update cell values and appearance when edited by the user.
This method handles both single and multi-cell selection, validating type compatibility across all selected cells before applying changes. It performs the following operations:
Validates that all selected cells have compatible types
Verifies the new value matches the expected type(s)
Updates the database with validated values
Maintains undo/redo history for all modifications
Refreshes cell colors and formatting
Special handling: - PatientName: Removes spaces (used for subfolder naming in
calculations)
TAG_BRICKS/TAG_FILENAME: Read-only fields, changes are rejected
- List types: Prevents mixed type selections but allows homogeneous
lists
- Parameters:
item_origin – QTableWidgetItem from which the edit originated
- Side effects:
Modifies database values for selected cells
Updates cell appearance (colors, fonts)
Adds entry to project undo history
Clears redo history
Resizes columns to fit content
- remove_scan()[source]¶
Remove selected scans from the database and file system.
This method handles the removal of scan documents from both the current and initial collections in the project database. It performs the following:
Prompts user for confirmation if scans are in the active scan list
Preserves modification history for removed scan values
Deletes associated files (.nii and .json) from the file system
Updates the UI table to reflect removals
The removal process can be cancelled by the user when prompted. If multiple scans are selected, the user can choose to apply their decision to all remaining scans.
- Side effects:
Modifies database by removing documents from COLLECTION_CURRENT and COLLECTION_INITIAL
Deletes scan files from the project folder
Updates UI table rows and marks project as having unsaved modifications
- reset_cell()[source]¶
Reset selected cells to their original values from the initial collection.
This method restores the values of all selected cells to their original state by retrieving values from COLLECTION_INITIAL and updating COLLECTION_CURRENT. If any cells lack initial values (e.g., user-created tags), a warning is displayed. The operation is recorded in the project history for undo/redo functionality.
- Side effects:
Updates database values in COLLECTION_CURRENT
Updates table cell display values
Appends operation to project.undos
Clears project.redos
May display a warning dialog for unreset values
Resizes table columns to fit content
- reset_column()[source]¶
Reset selected columns to their original values.
Restores values in selected cells to their initial state from the database. If a cell’s initial value doesn’t exist (e.g., user-added tags), it cannot be reset and a warning will be displayed.
The operation is recorded in the project’s undo history. Any existing redo history is cleared after this operation.
- Side effects:
Updates database values in COLLECTION_CURRENT
Updates table cell displays
Appends to project.undos
Clears project.redos
Resizes columns to fit content
May display warning dialog for unreset values
- reset_row()[source]¶
Reset selected cells to their original values from the initial collection.
Restores the values of all cells in selected rows to their initial state by copying values from COLLECTION_INITIAL to COLLECTION_CURRENT. Only cells with available initial values are reset. User-defined tags without initial values are skipped and trigger a warning dialog.
The operation is recorded in the project’s undo/redo history, allowing users to revert the reset if needed. After resetting, columns are automatically resized to fit their contents.
- Side Effects:
Updates database values in COLLECTION_CURRENT
Updates table cell display values
Appends operation to project.undos
Clears project.redos
Shows warning dialog if any values couldn’t be reset
Resizes table columns
- section_moved(logical_index, old_index, new_index)[source]¶
Handle section movement to keep the FileName column fixed at position 0.
This slot is triggered when a user attempts to reorder table columns. It ensures the FileName column (logical index 0) always remains at the leftmost visual position, regardless of user drag-and-drop actions.
- Parameters:
logical_index – The logical index of the moved column (unused).
old_index – The previous visual position of the column (unused).
new_index – The new visual position of the column (unused).
- Note:
Parameters are required by the Qt signal signature but not used in the implementation. Uses a guard flag to prevent recursive calls when programmatically repositioning the FileName column.
- select_all_column(col)[source]¶
Select all cells in a column when its header is double-clicked.
This method clears any existing selection before selecting the entire column, ensuring only the specified column is highlighted.
- Parameters:
(int) (col) – The zero-based index of the column to select.
- select_all_columns()[source]¶
Select all columns containing currently selected cells.
Expands the current cell selection to include entire columns. If cells from multiple columns are selected, all corresponding columns will be selected. This method is typically invoked from the context menu.
- Note:
Temporarily switches selection mode to MultiSelection during operation, then restores ExtendedSelection mode.
- selection_changed()[source]¶
Update the tab view when the table selection changes.
Rebuilds the internal scans list based on currently selected items, grouping tag names by scan name. If link_viewer is enabled, updates the connected mini viewer display.
- Side effects:
Clears and repopulates self.scans with [scan_name, [tag_names]] pairs
Calls data_browser.connect_mini_viewer() if self.link_viewer is True
- show_brick_history(scan)[source]¶
Display a popup window showing the history of a brick.
This method retrieves the brick UUID associated with the triggering sender, creates a history popup dialog, and displays it to the user.
- Parameters:
scan – The scan data to display in the history popup.
- Note:
The sender (typically a UI widget) must be registered in self.bricks to retrieve the corresponding brick UUID.
- sort_column(order)[source]¶
Sort the currently selected column.
- Parameters:
int) (order (Qt.SortOrder or) – Sort order to apply. - Qt.AscendingOrder (0): Sort from lowest to highest - Qt.DescendingOrder (1): Sort from highest to lowest
- Note:
Temporarily disconnects signals during sorting to prevent unwanted side effects, then reconnects them afterward.
- sort_updated(column, order)[source]¶
Update project state and apply sorting to the table.
Temporarily disconnects signals, updates the project’s sort configuration, applies the sort to table items, refreshes visual elements, and reconnects signals.
- Parameters:
column – The column index to sort by. Use -1 to indicate no sorting.
order – The sort order (Qt.AscendingOrder or Qt.DescendingOrder).
- Note:
This method is a no-op when column is -1, allowing safe calls with invalid column indices.
- update_colors()[source]¶
Update cell background colors based on data state and visibility.
- Colors indicate:
- White/Grey: Unmodified builtin tags (alternating for visible
rows)
Cyan/Blue: Modified builtin tags (alternating for visible rows)
- Pink/Red: User-defined tags or null values (alternating for
visible rows)
Note: This method assumes the itemChanged signal is disconnected. Automatically saves modifications if auto-save is enabled.
- update_selection()[source]¶
Update table selection based on current scan results.
Clears existing selection and selects cells corresponding to tags found in the current scan results. For each scan, selects the cells at the intersection of the scan’s row and its associated tag columns.
- update_table(take_tags_to_update=False)[source]¶
Refresh the table with current project data.
Completely resets and repopulates the table when switching projects. This involves clearing selections, fetching current scan documents, refilling headers and cells, resizing columns/rows, and updating the visual appearance.
- Parameters:
take_tags_to_update – If True, updates tags during the header fill operation. Defaults to False.
- Side Effects:
Clears current table selection
Resets scans_to_visualize and scans_to_search attributes
Clears selected scans list if selection is active
Disconnects and reconnects table signals
Modifies table dimensions and visual styling
- update_visualized_columns(old_tags, showed)[source]¶
Update column visibility based on tag selection changes.
Synchronizes the table’s visible columns with the provided tag list by:
Hiding columns for tags that are no longer displayed
Showing columns for newly displayed tags
Updating advanced search dropdowns if the search panel is open
Refreshing column sizing and colors
- Parameters:
(list) (showed) – Previously visualized tags.
(list) – Tags to currently display in the table.
- update_visualized_rows(old_scans)[source]¶
Update table row visibility based on current scan visualization state.
Temporarily disconnects selection signals, hides rows for scans no longer in the visualization list, shows rows for newly visualized scans, and updates the table appearance.
- Parameters:
old_scans – Collection of scans from the previous state, used to determine which rows need to be hidden.
- class populse_mia.user_interface.data_browser.data_browser.TimeFormatDelegate(parent=None)[source]¶
Bases:
QItemDelegateDelegate for handling time data display and editing in table views.
This delegate creates a QTimeEdit widget with millisecond precision (hh:mm:ss.zzz format) for editing time values in a TableDataBrowser.
- __init__(parent=None)[source]¶
Initialize the time format delegate.
- Parameters:
parent – Parent QWidget, if any. Defaults to None.
- createEditor(parent, option, index)[source]¶
Create and configure the editor widget for time values.
- Parameters:
parent – Parent widget for the editor.
option – Style options for the item (unused, required by Qt API).
index – Model index of the item being edited (unused, required by Qt API).
- Return (QTimeEdit):
Configured time editor widget with hh:mm:ss.zzz format.
populse_mia.user_interface.data_browser.mini_viewer module¶
This module provides the MiniViewer class, which is a PyQt-based widget designed for rapid visualization of medical scans. The MiniViewer allows users to view and interact with 3D, 4D, and 5D NIfTI images, providing tools to navigate through slices and time points.
Key Features: - Visualize single images per scan with cursors to move in multiple dimensions. - Display all images of the greater dimension of the scan. - Support for 3D, 4D, and 5D NIfTI images. - Configurable display settings, including orientation and slice navigation. - Integration with project-specific configurations and preferences.
- Contains:
- Class:
MiniViewer
- class populse_mia.user_interface.data_browser.mini_viewer.MiniViewer(project)[source]¶
Bases:
QWidgetMiniViewer allows rapid visualization of scans with either a single image per scan or all images of the greater dimension of the scan.
Displayed images depend on their dimension: - 3D: Display all slices. - 4D: Display the middle slice of the third dimension for each time of the
fourth dimension.
- 5D: Display the middle slice of the third dimension for the first time
of the fourth dimension for each time of the fifth dimension.
- Note:
idx corresponds to the index of the displayed image
idx in [0, self.max_scans]
- most of the class’s attributes are lists of 0 to self.max_scans
elements
- __init__(project)[source]¶
Initialize the MiniViewer with project configuration.
The MiniViewer provides a thumbnail preview interface for scans, initially hidden to maximize space for the data browser.
- Parameters:
project – The current project instance containing scan data and project-specific configuration.
- boxSlider(idx)[source]¶
Initialize dimensional sliders and value fields for a given index.
Creates three sliders (3D, 4D, 5D) with their corresponding text fields and connects each slider’s valueChanged signal to the appropriate position update handler.
- Parameters:
(int) (idx) – The index position where sliders should be inserted.
- Note: Each slider is connected to changePosValue with dimension
- offsets:
3D slider: dimension 1
4D slider: dimension 2
5D slider: dimension 3
- changePosValue(idx, cursor_to_change)[source]¶
Synchronize cursor positions across multiple image viewers when chain mode is enabled.
When the “Chain cursors” checkbox is checked, this method propagates the cursor value from the modified viewer to all other viewers, scaling the value proportionally to account for different cursor ranges.
- Parameters:
(int) (cursor_to_change) – Index of the viewer whose cursor was changed.
(int) – Cursor identifier (1=3D, 2=4D, 3=5D).
- Notes:
If chain mode is disabled, only updates the image for the given index.
Boundary values (min/max) are preserved exactly.
Intermediate values are scaled linearly to maintain relative position.
- check_box_cursors_state_changed()[source]¶
Update cursor chaining configuration based on checkbox state.
Synchronizes the cursor chaining setting in the configuration with the current state of the checkbox. When enabled, cursors will be chained together across views.
- clear()[source]¶
Clear cached Nibabel image to free memory.
Removes the internal image reference if it exists, allowing the image object to be garbage collected.
- clear_layouts()[source]¶
Remove all widgets from the final layout.
This prepares the layout for new content by detaching and deleting all existing widgets.
- createDimensionLabels(idx)[source]¶
Create and configure dimension labels for the specified index.
Creates three QLabel widgets (3D, 4D, and 5D) at the given index position, configures them with a 9-point font, and sets their text labels.
- Parameters:
idx – The index position where the labels should be inserted.
- createFieldValue()[source]¶
Create a read-only field for displaying cursor position.
- Return (QLineEdit):
A disabled, center-aligned text field with fixed width (65px) and font size (9pt) for displaying coordinate values.
- create_slider(minimum=0, maximum=0, position=0)[source]¶
Create a horizontal slider widget.
- Parameters:
minimum – The minimum value of the slider. Defaults to 0.
maximum – The maximum value of the slider. Defaults to 0.
position – The initial position/value of the slider. Defaults to 0.
- Return QSlider:
A configured horizontal slider widget, initially disabled.
Note: The slider is created with strong focus policy and a tick interval of 1. It starts in a disabled state. With default parameters (min=0, max=0), the slider has no range and should be configured before enabling.
- displayPosValue(idx)[source]¶
Update position display for all dimensional sliders at the given index.
Updates the text labels for 3D, 4D, and 5D sliders to show the current position (1-indexed) and maximum value in the format “current / max”.
- Parameters:
idx – Index of the slider group to update (0-based).
- enableSliders(idx)[source]¶
Enable sliders at the specified index across all dimensions.
- Parameters:
idx – Index of the sliders to enable across 3D, 4D, and 5D slider collections.
- image2DModifications(idx, im2D=None)[source]¶
Apply display modifications to a 2D image slice.
Processes an image for optimal display by: 1. Resizing to standard display dimensions 2. Rescaling intensities with percentile-based clipping 3. Converting to appropriate display data type 4. Applying orientation rotation (radiological/neurological)
- Parameters:
idx – Index of the image slice in the internal array
im2D – Optional 2D numpy array to modify. If None, uses self.im_2D[idx]
- Note: When im2D is not provided, the modified image is stored in
self.im_2D[idx]
- image_to_pixmap(im, i)[source]¶
Convert an N-dimensional NIfTI image to a 2D Qt pixmap.
Extracts a 2D slice from multi-dimensional medical imaging data and converts it to a Qt pixmap for display. The extraction strategy depends on dimensionality:
3D images: Extract slice at index i along the z-axis
4D images: Extract middle z-slice from the 3D volume at time index i
- 5D images: Extract middle z-slice from the 3D volume at time index 1
of the 4D volume at the 5th dimension index i
- Parameters:
im – NIfTI image object with a dataobj attribute
i – Index for slice/volume selection along the outermost variable dimension
- Return (QPixmap):
Qt pixmap ready for display, or pixmap from empty array if dimensionality is unsupported
- indexImage(idx)[source]¶
Update the displayed 2D image slice and adjust slider ranges according to the dimensionality of the selected image.
The current values of the 3D, 4D, and 5D sliders are used to extract the corresponding slice from the image data. Sliders that exceed the image dimensionality are reset to a maximum value of 0.
- Parameters:
idx – Index of the selected image
- mem_release()[source]¶
Release memory by clearing all internal lists holding images, sliders, labels, and related UI elements.
This method empties the existing lists in place (without reassigning them) to ensure that all references are removed and memory can be reclaimed.
Display the 2D image corresponding to the given index.
This method updates the navigation state, applies image-specific modifications, converts the image to a Qt pixmap, and displays it in the associated label.
- Parameters:
(int) (idx) – Index of the image to display
- openTagsPopUp()[source]¶
Open a modal dialog allowing the user to select the tag used as the thumbnail legend.
If the dialog is accepted, slice verification is triggered for the current file paths.
Notes: The dialog instance is stored on
self.popUpto allow access from unit tests.
- setThumbnail(file_path_db, idx)[source]¶
Set the thumbnail description label for a given image index.
Retrieves the value of the configured thumbnail tag from the database and displays it under the image frame. If the value is not defined, a default placeholder is used. The tooltip shows the tag name.
- Parameters:
(str) (file_path_db) – Path of selected image in database format (ex. data/raw_data/mymri.nii’)
(int) (idx) – Index of the image in the UI.
- show_slices(file_paths)[source]¶
Display thumbnail previews of neuroimaging files with interactive controls.
Creates a thumbnail viewer showing either cursor-controlled slices or multiple slices from the selected neuroimaging files. On first call, makes the MiniViewer visible. Does nothing if the viewer is hidden by the user.
The viewer supports two display modes: - Cursor mode (default): Shows one slice per image with interactive
3D/4D/5D sliders
All slices mode: Displays multiple consecutive slices from each image
- Parameters:
file_paths – List of paths to neuroimaging files (NIfTI format) to display. Invalid or non-existent files are automatically filtered out with warnings.
- Side effects:
Modifies self.file_paths by removing invalid entries
Updates self.img list with loaded image objects
Creates and configures numerous Qt widgets for the thumbnail display
Logs warnings for files that cannot be loaded or displayed
- Note:
Maximum thumbnails displayed is controlled by self.config.get_max_thumbnails() in cursor mode, and by self.line_edit_nb_slices.text() in all slices mode.
- update_nb_slices()[source]¶
Update slice configuration and refresh thumbnails.
Triggered when the user modifies the number of slices to visualize. Updates the configuration with the new slice count and re-validates the current file paths to regenerate thumbnails accordingly.
Notes: The slice count is retrieved from the UI line edit widget and applied to all loaded files.
- update_visualization()[source]¶
Update visualization settings and refresh thumbnails.
Synchronizes the slice visualization preference (show all slices vs. single slice) based on the checkbox state, updates the configuration, and regenerates thumbnails for the current file paths.
This method is triggered when the user toggles the “show all slices” checkbox.
- verify_slices(file_paths)[source]¶
Update slice display settings based on the number of selected files.
When multiple files are selected, the “Show all slices” checkbox is disabled and unchecked to prevent viewing slices from multiple files simultaneously. For single file selection, the checkbox remains enabled.
- Parameters:
file_paths – List or collection of selected document file paths.
populse_mia.user_interface.data_browser.modify_table module¶
Database cell editor module for list-type values.
This module provides dialog interfaces for editing complex data types in the Mia data browser. It specifically handles the editing of list-type values such as arrays of numbers, strings, or dates.
The ModifyTable dialog creates an interactive table representation of lists, allowing users to add, edit, or remove items while ensuring type safety and database consistency.
- Contains:
- Class:
ModifyTable
- class populse_mia.user_interface.data_browser.modify_table.ModifyTable(project, value, types, scans, tags)[source]¶
Bases:
QDialogDialog to modify cell contents containing lists in the data browser tab.
This dialog provides a user interface to edit cells that contain list values. It displays the list elements in a table and allows users to add or remove elements.
- __init__(project, value, types, scans, tags)[source]¶
Initialize the ModifyTable dialog.
- Parameters:
project – Instance of the current project
value – List of values in the cell to be modified
types – Allowed value types for validation
scans – Scan identifiers corresponding to rows
tags – Tag identifiers corresponding to columns
- fill_table()[source]¶
Populate the table with the current list elements.
Configures the table dimensions, populates cells with values, and adjusts table size to fit content within reasonable bounds.
populse_mia.user_interface.data_browser.rapid_search module¶
Rapid Search Widget Module
This module provides the RapidSearch widget, a specialized QLineEdit component for performing quick searches across visualized tags in the data browser table.
The RapidSearch widget enables users to filter DataBrowser using various search patterns and wildcards. It supports searching for specific text patterns as well as finding entries with undefined or missing values.
- Contains:
- Class:
RapidSearch
- class populse_mia.user_interface.data_browser.rapid_search.RapidSearch(databrowser)[source]¶
Bases:
QLineEditWidget for pattern searching in table data across visualized tags.
Supports special search syntax: - ‘%’: Wildcard for any string - ‘_’: Wildcard for any single character - ‘Not Defined’: Matches scans with missing values
Dates should be formatted as: yyyy-mm-dd hh:mm:ss.fff
- __init__(databrowser)[source]¶
Initialize the RapidSearch widget.
- Parameters:
databrowser – Parent data browser widget
- static prepare_filter(search, tags, scans)[source]¶
Create a filter for searching text across specified tags.
- Parameters:
(str) (search) – Search pattern to look for
(list) (scans) – List of tags to search within
(list) – List of scans to restrict the search to
- Return (str):
SQL-like filter expression for the search