""" CamiTK Python Bindings ======================== This module provides Python bindings for CamiTK core functionalities. It allows one to access core classes and methods from Action Python scripts. **NOTE** This module is intended to be used within CamiTK Application context. It is meant to be used in Action Python scripts from inside a CamiTK application Python interpreter, and not as a standalone library. **Available classes and functions** - Action: Action class is an abstract class that enables you to build a action (generally an algorithm that works on specific data, i. - Application: The generic/default application. - Component: A Component represents something that could be included in the explorer view, the interactive 3D viewer, and that could have or not a contextual popup menu (open by a right click in the explorer), a property dialog (to change some properties) Thus, a Component inherits from many abstract classes. - ComponentExtension: This class describes what is a generic Component extension. - Core: Core class specifies the basic static information for the CamiTK API. - ExtensionManager: This class is used to manage all plugins loaded by the application. - FrameOfReference: FrameOfReference is only a label for an abstract coordinate system. - HotPlugAction: An Action that can be created on the fly. - ImageComponent: The manager of the Image Volume data. - InterfaceBitMap: This class describes what are the methods to implement for a BitMap. - InterfaceFrame: This class describes the methods to implement in order to manage a Component position in space. - InterfaceGeometry: This class describes what are the methods to implement for a Geometry (rendering parameters, input/output, filters, picking parameters. - InterfaceNode: This class describe what are the methods to implement for a hierarchical tree node. - InterfacePersistence: Interface for all objects that should be serialized by the PersistenceManager. - InterfaceProperty: This class describes what are the methods to implement in order to manage dynamic properties. - Log: This class is a log utility. - MeshComponent: Basic component to manage any kind of mesh. - Property: This class describes a property that can be used in components and actions or any class that needs to be passed to ObjectController. - Transformation: Transformation represents a geometrical transformation between two FrameOfReferences It supports linear and non-linear transforms stored in a vtkTransform (linear) or any vtkAbstractTransform (non-linear) It has a direction (from a FrameOfReference to another FrameOfReference) Its constructor is private as Transformation objects must only be created through TransformationManager::getTransformationManager() (although it is possible to instantiate your own TransformationManager if you know what you're doing!) . - TransformationManager: TransformationManager manages frames of reference and transformations for a CamiTK Application This class is the entry point to using FrameOfReference and Transformation system. """ from __future__ import annotations import numpy import typing __all__: list[str] = ['Action', 'Application', 'Component', 'ComponentExtension', 'Core', 'ExtensionManager', 'FrameOfReference', 'HotPlugAction', 'ImageComponent', 'InterfaceBitMap', 'InterfaceFrame', 'InterfaceGeometry', 'InterfaceNode', 'InterfacePersistence', 'InterfaceProperty', 'Log', 'MeshComponent', 'Property', 'PythonHotPlugAction', 'Transformation', 'TransformationManager', 'error', 'getDebugInfo', 'getPythonVersion', 'info', 'newImageComponentFromNumpy', 'newMeshComponentFromNumpy', 'pythonConsoleRedirect', 'redirectStandardStreams', 'refresh', 'show', 'startApplication', 'trace', 'warning'] class Action: """ Action class is an abstract class that enables you to build a action (generally an algorithm that works on specific data, i.e. a specific component). To write an new action extension, at least two classes have to be reimplemented to enable the action: ActionExtension + Action. All the plugin mechanism is simplified thanks to CamiTK extension files (a JSON file containing all the information to generate the glue between your code and CamiTK). ## Overview This is the list of attributes you need to consider when creating a new action - name: name of the action; - description: tag used to describe the action (also used for tooltip and whatsThis of the corresponding QAction); - componentClassName: the name of the component class on which this action can be applied or "" (default) for generic actions. It determines on which type of component your action can be applied. Generic actions are action that have an empty component class name. Therefore generic actions can be called to generate/synthetize data or initialize resources. - family: families of actions allows one to group different actions of the same kind under one name; - tags: tags is a list of words used to define an action. These words can be used to find an action. - gui: either "Default Action GUI" (the action uses a default widget, instance of ActionWidget), "No GUI" or "Custom GUI" (you need to create the action's gui widget) - notEmbedded: this boolean defines if the gui widget is embedded in a given parent widget / action widget container (true by default) or not - icon: the icon used for the visually distinguish the action (used by the corresponding QAction) .. note:: An Action has a corresponding QAction, see getQAction(), that makes it easy to trigger an action from any Qt GUI (menus, toolbar, push buttons...). You can also call your action programmatically from any other code. If the component class name is not empty, the action is using the currently selected components of the given type (class name). If the component class name is empty, the action does not need any input. ## Using CamiTK extension file Using CamiTK extension file simplifies the creation and modification of actions. When using a CamiTK extension file, the extension generator will generate a initial .cpp file that you just have to fill in with your source code. These are the five methods you need to consider for customization: - `init()` is called when the action is loaded by the extension manager (i.e., when the action is instantiated). This is where all instance wide initialization should be done - `process()` is called when the user presses the "Apply" button. This is the main code for the action, where things are done - `targetDefined()` is called when the target of the action are defined (i.e., when the action is triggered). It is generally used to update the action GUI - `parameterChanged()` is called when a parameter value has changed. Similarly to `targetDefined()` it can be used to update the action GUI - (optional) `getUI()` if the developer wants to have a custom GUI, this is where she/he should instantiate the corresponding widget(s) You can call refreshApplication() in order to force the viewers to refresh. ## Action Parameters Action parameters are automatically created from the CamiTK extension files. Each parameter is defined as a Qt dynamic property. In your C++ code it is strongly recommended to use: - getParameterValue("My Parameter") to get the value as a QVariant (you can they use toString(), toBool(), toDouble()... depending on the type of "My Parameter") - setParameterValue("My Parameter", newValue) to set the value of a parameter programmatically (newValue must be a QVariant or of type that can be converted to a QVariant) - getParameterValueAsString("My Parameter") to get a string representation of the value of "My Parameter" ## Default GUI, Custom GUI or no GUI? An Action generally is used to wrap an algorithm in CamiTK. If this algorithm has parameters, it is very easy to get these parameters accessible to the user through the ActionWidget. These parameters are in fact defined as Qt dynamic properties. The default widget is an instance of ActionWidget. If ActionWidget does not correspond to what you need, just declare your action as having a Custom Widget You will then need to create a new class inheriting from QWidget, or directly from ActionWidget. These are the use cases for using the default behaviour (i.e. an instance of ActionWidget): - your action has some parameters and you need the user to review the default or modify their values before the action is applied, - or your action has no parameters but you still want the user to be applied only if/when the user click on an apply button. ActionWidget should be good enough in most of the cases. The default widget contains a description, a reminder of the current target component names, and an ObjectController with an Apply/Revert buttons that allows you to edit/modify properties. Use setDefaultWidgetButtonVisibility() to change the visibility of the Apply/Revert buttons and setDefaultWidgetApplyButtonText() to change the apply button text. When an action has no GUI triggering the action will directly call process() .. note:: The recommended architecture is for the action widget to call the action's apply method. The widget should only manage user interaction. ## Underlying triggering and applying an action mechanism Two steps have to be considered when using an action: - Step 1, trigger(): the action is either directly applied (if it does not have any GUI) or it's GUI is shown (using getWidget()) - Step 2, apply(): only the action algorithm is applied, i.e., the data are processed The targets can have changed between the time the action is first triggered and the time the action is applied. getWidget() is always called when the targets are updated. Therefore whenever getWidget() is called, you should make sure to update the the action GUI consequently. getTargets() is always updated in trigger() and available. .. note:: trigger() and apply() are public slots. They can be called either directly (classic C++ method invocation) or by connecting them to a QWidget signal. When an action is triggered (e.g., by right clicking in the context menu), the following algorithm applies, see trigger(): - 1. Prepare targetComponents (available with getTargets()): only select the compatible components from the selected components - 2. If the action is embedded, get the widget and show it in a parent/container (if parent is not specified, show it in the action viewer) - 3. If the action in not embedded, show it as a dialog - 4. If the action does not have any widget, directly call apply() This means that, if there is a widget, the action algorithm is controlled by the action widget, i.e. apply() is not called by trigger() but should be called by one of the action widget's button. If ActionWidget is not what your need, a typical getUI() method should use the lazy instantiation pattern to instantiate MyVerySpecialActionWidget the first time it is called, and call the MyVerySpecialActionWidget instance's updateTargets() method for any subsequent calls. Something like: ``` QWidget *MyAction::getUI() { // build or update the widget if (!myWidget) myWidget = new MyVerySpecialActionWidget(this); else // MyVerySpecialActionWidget should have an update() method myWidget->update(); return myWidget; } ``` But of course you can also use any kind of widget you like. ActionWidget is just defining a default widget for an action. If your action does not have any GUI/parameters, add a getWidget() and return nullptr. By default the properties/parameters are automatically updated when the user change the default widget, they are updated only when the user click on the apply button of the default widget. The setAutoUpdateProperties(true) to automatically called. Use parameterChanged() to perform some action when a parameter was changed byt the user. By default the action's widget is embedded. If you do not want to embed your action's widget, modify the "notEmbedded" parameter. When embedded, the parent widget has to be given at triggered time (i.e. getUI() is called during trigger). If there is no parent given for an embedded action, then the action is embedded in the ActionViewer by default. The method apply() must be implemented in your Action. .. note:: at any moment, the selected components on which the action needs to be applied are available by getTargets(). targetComponents is filtered so that it only contains compatible components (i.e., instances of getComponent()). .. note:: About registering your action in the history of the application. Consider registering your action within the application's history once applied. The history of action features a stack of processed action. The application's history of actions allows one to export the saved actions as an XML file for scripting or replaying it. To do so, implement the apply() method in your code, then launch the method applyAndRegister(), which simply wraps the apply() method with the preProcess() and postProcess() methods. You may also connect a SIGNAL to it, as the applyAndRegister() method is a Qt SLOT. ## Creating a pipeline of actions A pipeline of actions is a state machine where each state stands for an action with inputs and output components. The transitions between the states are done by processing the state's action (i.e. by calling the corresponding action's apply() method). Interpreting an pipeline of action is simpler than simply executing the action since the user doesn't need to manually set the inputs and outputs of each action (it is done automatically). If you are willing to write such a pipeline, simply implements the apply() method of each of your action and called the applyInPipeline() (instead of simply apply()). The method applyInPipeline() performs some pre- and post-processing around the method apply(). It has to be used within a pipeline (a chain of actions) where setInputComponents() and getOutputComponents() are needed. preProcessInPipeline() only selects the right components, and postProcess() sets output components and record history. See also: RenderingOption For a simple example of an embedded action See also: RigidTransform For a simple example of a non-embedded action See also: ChangeColor For a simple example of an action with no widget (but with a GUI) """ class ApplyStatus: """ \\enum ApplyStatus describes what happened during the application of an algorithm (i.e. results of the apply method) Members: SUCCESS ERROR WARNING ABORTED TRIGGERED """ ABORTED: typing.ClassVar[Action.ApplyStatus] # value = ERROR: typing.ClassVar[Action.ApplyStatus] # value = SUCCESS: typing.ClassVar[Action.ApplyStatus] # value = TRIGGERED: typing.ClassVar[Action.ApplyStatus] # value = WARNING: typing.ClassVar[Action.ApplyStatus] # value = __members__: typing.ClassVar[dict[str, Action.ApplyStatus]] # value = {'SUCCESS': , 'ERROR': , 'WARNING': , 'ABORTED': , 'TRIGGERED': } def __eq__(self, other: typing.Any) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: typing.Any) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... def __str__(self) -> str: ... @property def name(self) -> str: ... @property def value(self) -> int: ... ABORTED: typing.ClassVar[Action.ApplyStatus] # value = ERROR: typing.ClassVar[Action.ApplyStatus] # value = SUCCESS: typing.ClassVar[Action.ApplyStatus] # value = TRIGGERED: typing.ClassVar[Action.ApplyStatus] # value = WARNING: typing.ClassVar[Action.ApplyStatus] # value = def addParameter(self, arg0: Property) -> None: """ Add a new parameter to the action, using the CamiTK property class. If the parameter already exist, it will just change its value. .. note:: The action takes ownership of the Property instance. Returns: false if the Qt Meta Object property was added by this method (otherwise the property was already defined and true is returned if it was successfully updated) """ def getName(self) -> str: """ get the name of the action """ def getOutputComponent(self) -> Component: """ Returns the top-level output Component of this Action, or None if there is no output. """ def getParameterValue(self, arg0: str) -> typing.Any: """ get the parameter QVariant (same as property(const char*)) but check if it exists first. If the parameter was not declared using addParameter, this methods prints an error message and returns an invalid QVariant """ def getProperty(self, arg0: str) -> Property: """ Get a Property given its name Parameter ``name``: the property name Returns: nullptr if the name does not match any property name See also: Property """ def getTargets(self) -> list[Component]: """ the currently selected and valid (regarding the component property) components, for which this action is called """ def refreshApplication(self) -> None: """ convenient method to call from the user code to refresh all the application This is equivalent to call Application::refresh() """ def saveState(self) -> None: """ Saves the current state of this Action, including its parameters. This will backup the current state of the __dict__ of the python object associated with the action """ def setApplyButtonText(self, arg0: str) -> None: """ modify the "Apply" button text """ def setInputComponent(self, arg0: Component) -> None: """ Assigns the given Component as input to this Action. Note that the Action's widget is also initialized upon this call. """ def setParameterValue(self, arg0: str, arg1: typing.Any) -> bool: """ set the parameter QVariant value (same as setProperty(const char*, newValue)) but check if it exists first. If the parameter was not declared using addParameter, this methods prints an error message and returns false """ def updateWidget(self) -> None: """ Updates the Action's default widget, if any. """ class Application: """ The generic/default application. Once this class is instantiated in the main, everything is setup. The constructor can take the command line arguments. It can also be asked not to load the extensions automatically,see Application(). If you do not have a specific MainWindow extension, then the default CamiTK MainWindow is used, see setMainWindow(). This class manages all application-level instances, structures and all. This explains the number of _static_ methods in this class. It manages: - the registered/loaded action extensions and all the actions - the registered/loaded component extensions and all the component instances - the registered/loaded viewer extensions and all the viewer instances - the refresh mechanism - the current selection (selected components) - the recently opened documents - the application language/internationalization settings - the opening/closing/saving of components - the main window - the history of applied actions (including saving it as a CamitK SCXML document) - some application level settings """ @staticmethod @typing.overload def applyAction(arg0: str) -> Component: """ Applies the action of the given name and returns the top-level output Component created by it if any or None if there is no output component. The given action must require no input component """ @staticmethod @typing.overload def applyAction(arg0: str, arg1: Component) -> Component: """ Applies the action of the given name that takes the given component as input and returns the top-level output Component created by it if any or None if there is no output component. The given action must require one and only one input component """ @staticmethod @typing.overload def applyAction(arg0: str, arg1: list[Component]) -> Component: """ Applies the action of the given name that takes the given list of components as input and returns the top-level output Component created by it if any or None if there is no output component. The given action must require a list of input components """ @staticmethod def close(arg0: Component, arg1: bool) -> None: """ Close a Component: if it has been changed, ask the user for more information, then if everything is ok, delete it. Parameter ``component``: the Component to close. Parameter ``blockRefresh``: do not refresh the main window after closing the component Returns: true if the closing was made, false if the user cancelled the operation or a saving problem occurs """ @staticmethod def closeAll() -> bool: """ Closes all opened Components, prompting the user to save modified ones. This method uses the 'Close All' Action to close all opened Components. """ @staticmethod def connectViewerSelectionChanged(viewerName: str, callback: typing.Callable) -> bool: """ Connects a Python callback to a Viewer's selectionChanged() signal by name (if not already connected). """ @staticmethod def disconnectViewerSelectionChanged(viewerName: str, callback: typing.Callable) -> bool: """ Disconnects a Python callback from a Viewer's selectionChanged() signal by name (if already connected). """ @staticmethod def getAction(arg0: str) -> Action: """ get a registered action given its name """ @staticmethod def getActions() -> list[Action]: """ get all the actions registered in the application (note: the returned ActionList is guaranteed to be sorted by action name and to contain no duplicates) """ @staticmethod def getTopLevelComponents() -> list[Component]: """ get the current application wide list of instantiated top-level Components. This is the public method (return a const, the top-level component list is private and cannot be modified externally). """ @staticmethod @typing.overload def isAlive(component: Component) -> bool: """ does this Component still exist? (components can be deleted) """ @staticmethod @typing.overload def isAlive(action: Action) -> bool: """ does this Action still exist? (HotPlugAction can be unloaded) """ @staticmethod def open(fileName: str, blockRefresh: bool = False) -> Component: """ load the filename and returns the corresponding top level Component (returns nullptr if an error occurs) .. note:: this method opens the filename and created the associated TOP LEVEL component If you wish to open a subcomponent (not top level then), prefer directly calling its public constructor. Parameter ``fileName``: file that contains the component Parameter ``blockRefresh``: do not refresh the main window after closing the component """ @staticmethod def save(arg0: Component) -> None: """ save a component to its file (as given by component->getFileName()). .. note:: the component's file name has to be set prior to call this method. This method look for the proper loaded ComponentExtension, and call its save(Component*) method """ @staticmethod def saveAs(arg0: Component) -> None: """ Saves the given Component by prompting the user for a file name. This method uses the 'Save As' Action to save the given Component, which will prompt the user for a file name. """ @staticmethod def update3DClippingPlanes() -> None: """ Updates the clipping planes of the default 3D Viewer. This might be required when the working space volume changes rapidly, for instance in navigation system where the tracker moves some mesh in real 3D space or for RV application). """ class Component(InterfaceProperty, InterfaceNode, InterfaceGeometry, InterfaceBitMap, InterfaceFrame, InterfacePersistence): """ A Component represents something that could be included in the explorer view, the interactive 3D viewer, and that could have or not a contextual popup menu (open by a right click in the explorer), a property dialog (to change some properties) Thus, a Component inherits from many abstract classes. A Component can only have one implemented representation. For CAMITK core developers: This class uses the Object Adapter Design Pattern (aka delegate pattern) to delegates all InterfaceGeometry and InterfaceBitMap to respectively myGeometry:Geometry and mySlice:InterfaceBitMap It handles the InterfaceNode without delegation. Considering this Design Pattern, Component is the Adaptor and Geometry and InterfaceBitMap are the Adaptee classes. This class has some static member to manage all the currently instantiated Components as well as the currently selected Components. Actions generally use setPointSet() (for InterfaceGeometry) and setOriginalVolume (for InterfaceBitMap) to do some data processing and directly modify the low-level Vtk data. It is thus very **important** to rewrite these methods in your Component subclass to takes the actions' modification into account in your low-level data. Dynamic properties: if your Component defines some dynamic properties, you might want to override propertyValueChanged() in order to update the internal state of your object when a dynamic property's value has been changed. See also: ObjComponent for a good example It extensively uses Qt Meta-Object system (concepts and implementation). see http://doc.qt.nokia.com/latest/metaobjects.html """ def __init__(self, arg0: str, arg1: str) -> None: """ Component constructor for top-level component (please use the other constructor for sub-level components). parentComponent is set to nullptr (=> isTopLevel() will return true). Parameter ``file``: the file to get the data from Parameter ``name``: the Component name Parameter ``rep``: the representation concretely implemented by this Component (default=NO_REPRESENTATION) Parameter ``createDefaultFrame``: Whether the component should create its frame (should be set to false only if the frame is created/set in another way) """ def addChild(self, arg0: InterfaceNode) -> None: """ add a child Component (sub item in the hierarchy), and modify the child's parent to be equal to this instance This is to be used with care. The preferred method to add a child component is to use the Component's constructor with the parent parameter: Component(Component *, const QString &, Representation rep) . See also: attachChild() """ def getChildren(self) -> list[Component]: """ get the list of the InterfaceNode children (sub items in the hierarchy) """ def getFileName(self) -> str: """ get the file name where the data have to be stored/were stored """ def getFrame(self) -> ...: """ Get the pointer to this object's FrameOfReference. \\note Please use TransformationManager::getFrameOfReferenceOwnership(FrameOfReference*) """ def getName(self) -> str: """ get the name to be displayed """ def getParent(self) -> InterfaceNode: """ get the parent Component """ def getPropertyValue(self, arg0: str) -> typing.Any: """ get the property QVariant (same as property(const char*)) but check if it exists first. If the property was not declared using addProperty, this methods prints an error message and returns an invalid QVariant """ def isSelected(self) -> bool: """ Check if this data component is selected """ def isTopLevel(self) -> bool: """ return true if this component is a top-level component """ def refresh(self) -> None: """ refresh all the viewer that are currently displaying this Component At the end the InterfaceNode modification flag is reset. """ def setFrame(self, arg0: ...) -> None: """ Set the FrameOfReference of this object. Note that this methods will take ownership of the given frame thanks to the shared_ptr. """ def setFrameFrom(self, arg0: InterfaceFrame) -> None: """ Modify this object's frame using the given object's frame. .. note:: you can reimplement this method if you need to manage more than this frame of reference ( See also: ImageComponent::setFrameFrom()) """ def setModified(self, arg0: bool) -> None: """ set the modified flag """ def setName(self, arg0: str) -> None: """ set the name to be displayed """ def setPropertyValue(self, arg0: str, arg1: typing.Any) -> bool: """ set the property QVariant value (same as setProperty(const char*, newValue)) but check if it exists first. If the property was not declared using addProperty, this methods prints an error message and returns false """ def setSelected(self, b: bool, recursive: bool = True) -> None: """ Update the selection flag. Parameter ``b``: the value of the flag (true means "is selected") Parameter ``recursive``: if true (default), also updates the children Component selection flags. """ class ComponentExtension: """ This class describes what is a generic Component extension. To add a ComponentExtension to CamiTK core, write a new class that inherits from this class. There are two types of component extension: the classical one manages (mime type) file extension, the other one manages all files in a given directory (e.g. Dicom images). For the latter you have to redefine hasDataDirectory(). The following methods HAVE to be redefined in your subclass: - getName - getDescription - getFileExtensions - open The following methods can be redefined: - save: saving from a Component to one of the managed format - hasDataDirectory: for directory type extension """ def __init__(self) -> None: """ protected constructor, \\note never directly instantiate a ComponentExtension, use loadExtension(...) instead! """ def getDescription(self) -> str: """ get the plugin description """ def getFileExtensions(self) -> list[str]: """ get the list of managed extensions (each file with an extension in the list can be loaded by this Component) """ def getName(self) -> str: """ @name ComponentExtension plugin interface methods @{ get the plugin name """ def hasDataDirectory(self) -> bool: """ return true if this component manages directory instead of individual files (e.g. Dicom series are stored in directories, not files) """ def open(self, arg0: str) -> Component: """ get a new instance from data stored in a file (this is the most important method to redefine in your subclass) This method may throw an AbortException if a problem occurs. .. note:: The parameter is a filename with an absolute path (from Qt's QFileInfo::absoluteFilePath method): On Unix (including Mac OS) this will always begin with the root, '/', directory. On Windows this will always begin 'D:/' where D is a drive letter, except for network shares that are not mapped to a drive letter, in which case the path will begin '//sharename/' """ def save(self, arg0: Component) -> bool: """ save a given Component (does not have to be top-level) into one of the currently managed format (check the component QFileInfo(component->getFileName()).completeSuffix(). Redefine this method to extract all needed data/information from the Geometry or BitMap representation in order to export a given component to one of the file extension managed by this component extension. .. note:: this will enable to export to one of the managed filename extension at the CamiTK level (i.e. if you write this method, any compatible component can be saved to your managed format! .. note:: this method is called by CamiTK only if the filename extension is managed by this component extension. There should be no need to check it in the method. The default behaviour is a "not implemented yet" message box. Returns: false if the operation was not performed properly or not performed at all. """ class Core: @staticmethod def getConfig() -> str: ... @staticmethod def getPaths() -> str: ... @staticmethod def getTestDataDir() -> str: ... @staticmethod def shortVersion() -> str: ... @staticmethod def version() -> str: ... class ExtensionManager: """ This class is used to manage all plugins loaded by the application. The current version is able to load dynamic library for - ComponentExtension - ActionExtension This class is a contained for all the loaded extension. It contains only static members. """ @staticmethod def getDataDirectoryExtNames() -> list[str]: """ get the list of all the name of the registered Component data directory """ @staticmethod def getFileExtensions() -> list[str]: """ get the list of all the suffixes managed by registered component extensions (all possible file suffix) """ @staticmethod def registerNewComponentExtension(arg0: ..., arg1: str) -> bool: """ Register the given ComponentExtension. If the given ComponentExtension is managing file extensions that are already registered, it will not be registered, and this method will return false and a info message will be printed with more information. Parameter ``ce``: valid ComponentExtension pointer (loaded from a shared library plugin (.dll/.so/.dylib) or instantiated programmatically) Parameter ``filename``: (optional) if the extension was loaded from a shared library (.dll/.so/.dylib), path to this file Returns: true if the extension was registered without error """ class FrameOfReference: """ FrameOfReference is only a label for an abstract coordinate system. It is used as origins and destinations of transformations. There is no information stored in a FrameOfReference except - an ID, - a name and description - a number of dimensions (between 1 and 5, default is 3) and units ("mm" for the first 3 dimensions) - a AnatomicalOrientation that can describe whether there is a known anatomical orientation associated to each axis ( See also: AnatomicalOrientation) - a color (used in the transformation graph visualisation) All constructors are protected, use TransformationManager to create a new instance. See also: Transformation, TransformationManager, AnatomicalOrientation """ def getName(self) -> str: """ Get the FrameOfReference name """ def getUuid(self) -> QUuid: """ Get the unique identifier of the Frame """ class HotPlugAction(Action): """ An Action that can be created on the fly """ class ImageComponent(Component): """ The manager of the Image Volume data. An image volume data has no concrete 3D representation, as its representation is provided by its sub-components (axial, sagittal, coronal and arbitrary slices as well as volume rendering). It builds a complete/ready-to-use VTK pipeline: See also: Slice .. note:: You can use the following properties to change the visualization of an ImageComponent and children components: - "Display Image in 3D Viewer" type boolean, controls what is displayed in the default 3D viewer Every time a property is changed using setProperty(QString propertyName, QVariant value), the ImageComponent will automatically update, thanks to the propertyValueChanged(..) method. """ def __init__(self, arg0: str, arg1: str) -> None: """ Creates an ImageComponent from a file. This method is called from a ComponentExtension derived class that support the given file format. This method may throw an AbortException if a problem occurs. Parameter ``file``: the complete path to the image file Parameter ``name``: name to be given to the Component (this name will appear in the explorer) """ def clone(self) -> ImageComponent: """ Clone this original image. Note that the image data is not copied, only referenced from the clone, and that the frame of the clone is set to the original image component's frame. """ def getArbitrarySliceFrame(self) -> ...: """ Returns the FrameOfReference used for the arbitrary slice. """ def getDataFrame(self) -> ...: """ get the data FrameOfReference (i.e., the vtkImageData frame) """ def getDimensions(self) -> tuple: """ Returns the image dimensions as a tuple of 3 integers (dimX, dimY, dimZ). """ def getImageDataAsNumpy(self) -> numpy.ndarray: """ Returns the image data as a numpy ndarray. """ def getLastPixelPicked(self) -> tuple: """ Get the last pixel picked using CTRL + LEFT/RIGHT CLICK in voxel index (i, j, k) indicates the voxel index (no notion of voxel size) """ def getLastPointPickedDataFrame(self) -> tuple: """ Get the last point picked using CTRL + LEFT/RIGHT CLICK in the data frame coordinates (this takes into account voxel size) """ def getLastPointPickedWorldFrame(self) -> tuple: """ Get Get the last point picked using CTRL + LEFT/RIGHT CLICK in the world coordinates This takes into account voxel size and image origin (and possible image rigid transforms). """ def getSpacing(self) -> numpy.ndarray: """ Returns the image spacing as a tuple of 3 floats (spacingX, spacingY, spacingZ). """ def replaceImageData(self, arg0: numpy.ndarray) -> None: """ Replaces the image data with the given numpy ndarray. """ class InterfaceBitMap: """ This class describes what are the methods to implement for a BitMap. An InterfaceBitMap is a kind of simplifier/wrapper for vtkImageData. This class defines an "interface" (in the OOP/java meaning of the term). See the introduction of GoF: "Program to an interface, not an implementation." To see what Erich Gamma has to say about it: http://www.artima.com/lejava/articles/designprinciplesP.html To see what Bjarne Stroustrup has to say about it: http://www.artima.com/intv/modern.html See also: Slice """ class InterfaceFrame: """ This class describes the methods to implement in order to manage a Component position in space. Each Component has a frame of reference which is used to define its relation to other objects. You can define new frames and transformations between frames as required, but all FrameOfReference and Transformation objects must be managed by the TransformationManager. See also: TransformationManager """ class InterfaceGeometry: """ This class describes what are the methods to implement for a Geometry (rendering parameters, input/output, filters, picking parameters...) An InterfaceGeometry is a kind of simplifier/wrapper for vtkPointSet. This class defines an "interface" (in the OOP/java meaning of the term). See the introduction of GoF: "Program to an interface, not an implementation." To see what Erich Gamma has to say about it: http://www.artima.com/lejava/articles/designprinciplesP.html To see what Bjarne Stroustrup has to say about it: http://www.artima.com/intv/modern.html See also: Geometry """ class RenderingMode: """ @enum RenderingMode (and QFlags RenderingModes) handle actor rendering options (render this InterfaceGeometry as a surface, a wireframe and set of points). Members: NoRenderingMode Surface Wireframe Points """ NoRenderingMode: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = Points: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = Surface: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = Wireframe: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = __members__: typing.ClassVar[dict[str, InterfaceGeometry.RenderingMode]] # value = {'NoRenderingMode': , 'Surface': , 'Wireframe': , 'Points': } def __and__(self, other: typing.Any) -> typing.Any: ... def __eq__(self, other: typing.Any) -> bool: ... def __ge__(self, other: typing.Any) -> bool: ... def __getstate__(self) -> int: ... def __gt__(self, other: typing.Any) -> bool: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __invert__(self) -> typing.Any: ... def __le__(self, other: typing.Any) -> bool: ... def __lt__(self, other: typing.Any) -> bool: ... def __ne__(self, other: typing.Any) -> bool: ... def __or__(self, other: typing.Any) -> typing.Any: ... def __rand__(self, other: typing.Any) -> typing.Any: ... def __repr__(self) -> str: ... def __ror__(self, other: typing.Any) -> typing.Any: ... def __rxor__(self, other: typing.Any) -> typing.Any: ... def __setstate__(self, state: int) -> None: ... def __str__(self) -> str: ... def __xor__(self, other: typing.Any) -> typing.Any: ... @property def name(self) -> str: ... @property def value(self) -> int: ... NoRenderingMode: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = Points: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = Surface: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = Wireframe: typing.ClassVar[InterfaceGeometry.RenderingMode] # value = class InterfaceNode: """ This class describe what are the methods to implement for a hierarchical tree node. An InterfaceNode can only have one parent, even if it is a child of more than one InterfaceNodes. Consequence: an InterfaceNode can be present many times in the hierarchy, but can only depends from one parent. To add an InterfaceNode as a child and change its parent to this use addChild(). To add an InterfaceNode as a child without modifying its parent, use attachChild(). This class defines an "interface" (in the OOP/java meaning of the term). See the introduction of GoF: "Program to an interface, not an implementation." To see what Erich Gamma has to say about it: http://www.artima.com/lejava/articles/designprinciplesP.html To see what Bjarne Stroustrup has to say about it: http://www.artima.com/intv/modern.html """ class InterfacePersistence: """ Interface for all objects that should be serialized by the PersistenceManager """ class InterfaceProperty: """ This class describes what are the methods to implement in order to manage dynamic properties. InterfaceProperty is one of the interfaces implemented by the camitk::Component "Component" class. """ class Log: class LogLevel: """ Members: NONE ERROR WARNING INFO TRACE """ ERROR: typing.ClassVar[Log.LogLevel] # value = INFO: typing.ClassVar[Log.LogLevel] # value = NONE: typing.ClassVar[Log.LogLevel] # value = TRACE: typing.ClassVar[Log.LogLevel] # value = WARNING: typing.ClassVar[Log.LogLevel] # value = __members__: typing.ClassVar[dict[str, Log.LogLevel]] # value = {'NONE': , 'ERROR': , 'WARNING': , 'INFO': , 'TRACE': } def __eq__(self, other: typing.Any) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: typing.Any) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... def __str__(self) -> str: ... @property def name(self) -> str: ... @property def value(self) -> int: ... ERROR: typing.ClassVar[Log.LogLevel] # value = INFO: typing.ClassVar[Log.LogLevel] # value = NONE: typing.ClassVar[Log.LogLevel] # value = TRACE: typing.ClassVar[Log.LogLevel] # value = WARNING: typing.ClassVar[Log.LogLevel] # value = def setDebugInformation(self: bool) -> None: ... def setLogLevel(self: Log.LogLevel) -> None: ... def setMessageBoxLevel(self: Log.LogLevel) -> None: ... def setTimeStampInformation(self: bool) -> None: ... class MeshComponent(Component): """ Basic component to manage any kind of mesh. """ class FieldType: """ @enum FieldType Data fields can be applied to one of this Members: POINTS CELLS MESH """ CELLS: typing.ClassVar[MeshComponent.FieldType] # value = MESH: typing.ClassVar[MeshComponent.FieldType] # value = POINTS: typing.ClassVar[MeshComponent.FieldType] # value = __members__: typing.ClassVar[dict[str, MeshComponent.FieldType]] # value = {'POINTS': , 'CELLS': , 'MESH': } def __eq__(self, other: typing.Any) -> bool: ... def __getstate__(self) -> int: ... def __hash__(self) -> int: ... def __index__(self) -> int: ... def __init__(self, value: int) -> None: ... def __int__(self) -> int: ... def __ne__(self, other: typing.Any) -> bool: ... def __repr__(self) -> str: ... def __setstate__(self, state: int) -> None: ... def __str__(self) -> str: ... @property def name(self) -> str: ... @property def value(self) -> int: ... CELLS: typing.ClassVar[MeshComponent.FieldType] # value = MESH: typing.ClassVar[MeshComponent.FieldType] # value = POINTS: typing.ClassVar[MeshComponent.FieldType] # value = def addCellData(self, arg0: str, arg1: numpy.ndarray) -> None: """ Adds a cell data array using the given numpy ndarray. """ def addDataArray(self, arg0: MeshComponent.FieldType, arg1: str, arg2: numpy.ndarray) -> None: """ Add a data array using the given a numpy ndarray. """ def addPointData(self, arg0: str, arg1: numpy.ndarray) -> None: """ Adds a point data array using the given numpy ndarray. """ def clone(self) -> MeshComponent: """ Clone this original mesh. Note that the point set is not copied, only referenced from the clone, and that the frame of the clone is set to the original mesh component's frame. """ def getColor(self) -> tuple[float, ...] | list[float]: """ Get the color of given representation modes in the second parameter. Parameter ``color``: the 4-sized double tab of color (r,g,b,a) of the actor. Parameter ``ignoreEnhancedModes``: Return the color without considering the changes that may be due to enhanced modes (highlight) @warning color must points a 4 double-sized tab minimum. """ def getDataArray(self, arg0: MeshComponent.FieldType, arg1: int) -> numpy.ndarray: """ Get the data array of specified field type and index as a numpy ndarray. """ def getNumberOfDataArray(self, arg0: int) -> int: """ Get the number of data arrays of a given type without taking the specific representation into account. This method does not take into account: - the field arrays - the specific representation of 3D data (i.e., representation of 3D data as norm or component#i values) Parameter ``fieldFlag``: is a FieldType or a combinaison of field types. Returns: the number of arrays corresponding to the field flag """ def getPickedCellId(self) -> int: """ get the last pick point id, Returns: -1 if no point where picked """ def getPickedPointId(self) -> int: """ get the last pick point id, Returns: -1 if no point where picked """ def getPickedPointPosition(self) -> tuple: """ Returns the position of the picked point as a tuple of 3 floats (x, y, z) in this mesh component frame. If no point is picked, returns (0.0, 0.0, 0.0). """ def getPointSetAsNumpy(self) -> numpy.ndarray: """ Returns the point set as a numpy ndarray of shape (N, 3) where N is the number of points. """ def removeDataArray(self, arg0: MeshComponent.FieldType, arg1: str) -> None: """ Remove a data array. Parameter ``fieldType``: field type Parameter ``name``: name of the array to remove """ def replacePointSet(self, arg0: numpy.ndarray) -> None: """ Replaces the point set with the given numpy ndarray of shape (N, 3) where N is the number of points. If there is no Cell/polygons, this will be interpreted as a point cloud (it will create one cell containing all the points). """ def setColor(self, arg0: tuple[float, ...] | list[float]) -> None: """ Set the color of given representation modes. Parameter ``color``: the 4-sized double tab of color (r,g,b,a) of the actor. @warning color must points a 4 double-sized tab minimum. """ def setDataRepresentationOff(self, dataType: int = 7, blockRefresh: bool = False) -> None: """ hide all the data representation of a given data type (hide all by default) By default this->refresh() is called unless blockRefresh is set to true """ def setLinesAsTubes(self, isTubes: bool = True, radiusFromLength: bool = True, radiusFactor: float = 0.025, numberOfSides: int = 5) -> None: """ Set the lines as tubes (**works only for vtkDataSet representation that contains lines**) Parameter ``isTubes``: activate tube representation of lines Parameter ``radiusFromLength``: radius of tubes is computed as a proportion of line length Parameter ``radiusFactor``: radius of tubes will be : radiusFactor*lineLength if radiusFromLength is true, radiusFactor if it is false Parameter ``numberOfSides``: Number of sides of the tubes """ def setRenderingModes(self, arg0: int) -> None: """ @name rendering mode settings @{ Set the actor associated to a rendering mode visible or not. """ class Property: """ This class describes a property that can be used in components and actions or any class that needs to be passed to ObjectController. A property has a type, a description (to be displayed for example as a tooltip, can be rich-text, see https://doc.qt.io/qt-5/richtext-html- subset.html for supported html tags), a value, a unit of measurement (SI unit if possible), and some specific attributes (that depends on the type, e.g. minimal and maximal values, single steps, number of decimals, regular expression...). An enum type can also be used for properties. Properties can be grouped in subgroups, see Property::setGroupName(). Basically this is a way to overcome the Qt Meta Object properties limitations. A camitk::Property enriches a Qt Meta Object property (a very simplified Decorator Design Pattern). Using camitk::Property instead of directly using Qt Meta Object property helps to build a better interactive GUI (in the property explorer for components and in the ActionWidget for actions). Note that a camitk::Property is represented as a regular Qt Meta Object property as well (the value of the camitk::Property is in fact stored by the Qt Meta Object property) Here are some examples to get started with: ``` Demonstrates how rich text can be used in description addParameter(new Property("Bool Prop", false, "This a normal bool property.
**Note:** Rich text description!
See also: CamiTK web page", "")); beware: the action takes ownership of the Property pointer This means that the line above does not generate memory leak. Demonstrates how properties can be set as read-only Demonstrates how properties can be grouped. Here all read-only properties are assemble in the same eponymic group Property *readOnlyBool = new Property("Read Only Bool", true, "This a read-only boolean", ""); readOnlyBool->setReadOnly(true); readOnlyBool->setGroupName("Read Only Properties"); addParameter(readOnlyBool); beware: the action takes ownership of the Property pointer This means that you should NOT delete readOnlyBool in the action destructor Demonstrates how integer properties can be bounded Property *boundedInt = new Property("Bounded Int", 12, "An integer bounded between 0 and 20", ""); boundedInt->setAttribute("minimum", 0); boundedInt->setAttribute("maximum", 20); boundedInt->setGroupName("Numeric Properties"); addParameter(boundedInt); Demonstrates how double properties can be half-bounded Property *doubleWithMax = new Property("Double With Max", -10.0, "A double with a max value of -4.2", ""); doubleWithMax->setAttribute("maximum", -4.2); doubleWithMax->setGroupName("Numeric Properties"); addParameter(doubleWithMax); Property *intWithSingleStep = new Property("Int With Single Step", -10, "An integer with a single step of 5", ""); intWithSingleStep->setAttribute("singleStep", 5); intWithSingleStep->setGroupName("Numeric Properties"); addParameter(intWithSingleStep); Property *doubleWithStepAndDecimal = new Property("Double With Single Step And Precision", 3.14159, "A double with 5 decimals and a single step of 1.10-5", ""); doubleWithStepAndDecimal->setAttribute("singleStep", 10e-6); doubleWithStepAndDecimal->setAttribute("decimals", 5); doubleWithStepAndDecimal->setGroupName("Numeric Properties"); addParameter(doubleWithStepAndDecimal); Property *intWithDecimal = new Property("Int With Precision", 4, "An integer with a precision set to 5 decimals: this should not affect it.", ""); intWithDecimal->setAttribute("decimals", 5); intWithDecimal->setGroupName("Numeric Properties"); addParameter(intWithDecimal); Property *readOnlyQVector3D = new Property("Read Only QVector3D", QVector3D(-4.0, 2.0, 0.1), "A read-only QVector3D", ""); readOnlyQVector3D->setReadOnly(true); readOnlyQVector3D->setGroupName("Read Only Properties"); addParameter(readOnlyQVector3D); Property *stringWithRegExp = new Property("QString Constrained by RegExp", QString("loweronly"), "A QString constrained to lowercase characters only (no separators, numbers...)", ""); stringWithRegExp->setAttribute("regExp", QRegularExpression("[a-z]*")); addParameter(stringWithRegExp); Property *constrainedQRect = new Property("Constrained QRect", QRect(10,10,20,20), "A QRect constrained to (0,0,50,50)", ""); constrainedQRect->setAttribute("constraint", QRect(0,0,50,50)); addParameter(constrainedQRect); Property *constrainedQVector3D = new Property("Constrained QVector3D", QVector3D(1.1, 2.2, 3.3), "A constrained QVector3D (not yet implemented)", ""); constrainedQVector3D->setAttribute("constraint", QVector3D(10.0, 10.0, 10.0)); addParameter(constrainedQVector3D); ``` .. note:: To create a new Property, prefer using Property. To check if a Property has been added to your Component / Action, use either Component::getProperty() or Action::getProperty() methods. To modify an existing Property's value, check if it exists: - if not, create a new instance of Property - if yes, directly modify its value by using QObject::setProperty() method.e The GUI interaction is automatically build and managed by the class ObjectController. An example for adding properties to an action can be seen in tutorials/actions/properties. More specifically see the EnumPropertyExample action to learn about how to use enum properties. The class PropComponent and PropAction in the tutorials demonstrates how to use camitk::Property instead of Qt Meta Object Property. The available property types are: Property Type | Property Type Id ------------- | ----------------- int | QVariant::Int double | QVariant::Double bool | QVariant::Bool QString | QVariant::String QVector3D | QVariant::QVector3D QColor | QVariant::Color QDate | QVariant::Date QTime | QVariant::Time QChar | QVariant::Char QDateTime | QVariant::DateTime QPoint | QVariant::Point QPointF | QVariant::PointF QKeySequence | QVariant::KeySequence QLocale | QVariant::Locale QSize | QVariant::Size QSizeF | QVariant::SizeF QRect | QVariant::Rect QRectF | QVariant::RectF QSizePolicy | QVariant::SizePolicy QFont | QVariant::Font QCursor | QVariant::Cursor enum | enumTypeId() flag | flagTypeId() group | groupTypeId() Possible attributes depends on the property type, mostly (see also QtVariantPropertyManager API doc): Property Type | Attribute Name | Attribute Type ------------- | :------------: | :------------: ``int`` | minimum | QVariant::Int ``int`` | maximum | QVariant::Int ``int`` | singleStep | QVariant::Int ``double`` | minimum | QVariant::Double ``double`` | maximum | QVariant::Double ``double`` | singleStep | QVariant::Double ``double`` | decimals | QVariant::Int QString | regExp | QVariant::RegExp QDate | minimum | QVariant::Date QDate | maximum | QVariant::Date QPointF | decimals | QVariant::Int QSize | minimum | QVariant::Size QSize | maximum | QVariant::Size QSizeF | minimum | QVariant::SizeF QSizeF | maximum | QVariant::SizeF QSizeF | decimals | QVariant::Int QRect | constraint | QVariant::Rect QRectF | constraint | QVariant::RectF QRectF | decimals | QVariant::Int ``enum`` | enumNames | QVariant::StringList (note that this can be build automatically) ``flag`` | flagNames (NOT IMPLEMENTED YET) | QVariant::StringList .. note:: Anywhere in your code use the property(..).toInt() method to get the classical enum value of the property, and use Property::getEnumValueAsString() to get the enum value as a string. If you declared your enum using Q_ENUM (Qt>=5.5), you can also use directly QMetaEnum::fromType to retrieve the enum value as strings (see below). .. note:: If your property is an action parameter, it is safer to use the dedicated methods getParameterValue(..), setParameterValue(..), getParameterValueAsString(..) as they will first check that the given parameter name is a declared parameter. For component properties, it is safer to use the dedicated methods getPropertyValue(..) and setPropertyValue(..) as they will also first check that the given property name is a declared property. .. note:: For enums, you need to do few things in the C++ class that has a enum typed property: - add Q_underscore_OBJECT macro in your class declaration - either setup a new enum (option 1) or just fill in strings in the enum names (option 2) For option 1, you need - add the enum type in your class declaration - register your enum name using the Q_ENUM macro in your class declaration - register the enum type name to the property using the Property::setEnumTypeName (see example below) For option 2 (recommended), just - create a QStringList with the GUI strings - use the Property::setAttribute("enumNames", yourQStringList) .. note:: Using option 2 is recommended as it will allow you to dynamically update the enum names at any time (for instance if you want to select a component, you can update the enum names using the currently opened components). You can change the enum value names in the GUI using the "enumNames" attributes. There is also a way to automatically build nicer enumNames (see below). Enum icons might be set using Property::setEnumIcons. For instance in the header: ``` class MyAction : public camitk::Action { Really needed! (replace ‗ by _ in your code if you copy-paste this snippet) Q‗OBJECT -- option 1 declare the C++ enum enum MyEnum { PossibleValue1, PossibleValue2 }; register the enum (Qt >= 5.5) Q_ENUM(MyEnum) -- option 2 (recommended) -> nothing to declare in the header ... }; ``` And then in the code: ``` MyAction::MyAction(ActionExtension * extension) : Action(extension) { ... -- option 1 build the dynamic prop based on the enumeration Property *enumProp = new Property("My Enumeration", MyAction::PossibleValue2, "Enumeration support example",""); register the enum type name for automatically manage the enum as a popup list enumProp->setEnumTypeName("MyEnum",this); The Property class automatically build the enum names presented to the user in the GUI (it will changed the enum literals to get a cleaner look, e.g. PossibleValue1 becomes "Possible Value 1") OR -- option 2 (recommended) build the dynamic prop based on a custom string list Property *enumProp = new Property("My Enumeration", 0 /-* index of the initial value in the string list *-/, "Enumeration support example",""); Set the enum names of your choice, using the enumNames property: enumProp->setEnumTypeName("MyEnum"); add strings to populate the GUI QStringList enumValues; enumValues << "Possible Value #1" << "Possible Value #2"; enumProp->setAttribute("enumNames", enumValues); -- after either option 1 or 2: register the new prop as an action parameter addParameter(enumProp); } ... -- option 1 usage option 1.1: get the value as classical C++ enum MyEnum enumPropCurrentValue = (MyEnum) getParameterValue("My Enumeration").toInt(); option 1.2: get the value as a QString (either "PossibleValue1" or "PossibleValue2", beware: this is different from the GUI names), you need the enumProp pointer QString enumPropAsString = enumProp->getEnumValueAsString(this); option 1.3: using the Q_ENUM declaration in the header, get the value using Qt meta object QMetaEnum metaEnum = QMetaEnum::fromType(); QString enumPropAsStringDirect = metaEnum.valueToKey(enumPropCurrentValue); -- option 2 usage (recommended) QString QString enumPropAsString = enumValues.value(getParameterValue("My Enumeration").toInt() ``` .. note:: This is not exactly a decorator design pattern, as the Property class is not abstract. The Qt Meta Object is still held by the QtObject inherited class (e.g. Component or Action). The camitk::Property class adds description, readOnly status and specific attributes to a QObject dynamic property. """ @staticmethod def setEnumTypeName(*args, **kwargs) -> None: ... def __init__(self, name: str, value: typing.Any, description: str, unit: str) -> None: """ Constructor. The variant parameters also allows you to initialize the value of the property. By default a Property is enabled and editable (i.e. by default it is not read-only) Parameter ``name``: property name (unique identifier of your class property Parameter ``variant``: specify the property type (QVariant) and initial value Parameter ``description``: a sentence or two to describe the property (and its unit if any), can be Rich Text Parameter ``unit``: a unit of measurement (in SI unit), use symbols from https://en.wikipedia.org/wiki/SI_base_unit or https://en.wikipedia.org/wiki/SI_derived_unit when possible """ def getAttribute(self, arg0: str) -> typing.Any: ... def getDescription(self) -> str: ... def getName(self) -> str: ... def getReadOnly(self) -> bool: ... def getUnit(self) -> str: ... def setAttribute(self, attribute: str, value: typing.Any) -> None: ... def setReadOnly(self, arg0: bool) -> None: ... class PythonHotPlugAction(HotPlugAction): """ An Action that is implemented using a Python CamiTK script. """ class Transformation: """ Transformation represents a geometrical transformation between two FrameOfReferences It supports linear and non-linear transforms stored in a vtkTransform (linear) or any vtkAbstractTransform (non-linear) It has a direction (from a FrameOfReference to another FrameOfReference) Its constructor is private as Transformation objects must only be created through TransformationManager::getTransformationManager() (although it is possible to instantiate your own TransformationManager if you know what you're doing!) .. warning:: Transformation are instantiated/stored/managed/destroyed by TransformationManager::getTransformationManager(), therefore you should not keep a pointer to any Transformation, just call TransformationManager::getTransformationOwnership(..) when you need to access it. This guarantees the coherence of the complete reference system and avoid dangling pointers and memory leaks. ``` {.cpp} ... FrameOfReference* from = TransformationManager::addFrameOfReference("Source Frame"); FrameOfReference* to = TransformationManager::addFrameOfReference("Destination Frame"); Transformation* t = TransformationManager::addTransformation(from, to); ... t->setMatrix(...); note: t MUST not be a member call TransformationManager::getTransformationOwnership(from, to) to access it later on ``` See also: TransformationManager """ def getFrom(self) -> FrameOfReference: """ Get the FrameOfReference the Transformation starts from (origin) """ def getName(self) -> str: """ Get the name of the Transformation """ def getTo(self) -> FrameOfReference: """ Get the FrameOfReference that the Transformation goes to (destination) """ def getTransform(self) -> numpy.ndarray: """ Get the internal vtkTransform (linear transformation) or a nullptr Note: this method should return a vtkSmartPointer to a const vtkTransform Unfortunately, at some stage in some part of your VTK pipeline, you might need a non-const vtkTransform. .. warning:: You should only use this method to send the vtkTransform to a vtk method. \\warning **NEVER** use this method to modify the content of the matrix directly, as it might generate inconsistencies in the transformation management. If you need to change the values you **MUST** use TransformationManager::updateTransformation(..) """ class TransformationManager: """ TransformationManager manages frames of reference and transformations for a CamiTK Application This class is the entry point to using FrameOfReference and Transformation system. Every Component that is displayable contains data which are located in space using coordinates. But two Components may not use the same origin in space, or the same axes. To manage that, the notion of Frame specifies an origin and axes, this is modeled by camitk::FrameOfReference. Each component has a FrameOfReference accessed by Component::getFrame() Two Components may share a common Frame, for example two meshes of two organs computed from the same image. In this case both components' getFrame() should return the same FrameOfReference. TransformationManager stores and manages all the FrameOfReference objects used in a CamiTK Application. When you need to display two Components, or to apply an Action that uses multiple Components, it is necessary to be able to transform the coordinates of one Component's data to another. These geometrical transformations are stored in the camitk::Transformation class. A Transformation stores the frame of origin, the frame of destination and the geometrical transformation itself. Currently it supports linear transformations (represented in a 4x4 homogeneous matrices). All Transformation objects are also stored and managed in the TransformationManager. The TransformationManager provides and manages a specific and unique "world frame". This is the frame used by VTK and the default for 3D viewers. Having a world frame simplifies the usage of frames. Alongside Component, Viewers also have a FrameOfReference, which determines the "point of view" they are using for the visualization. More precisely, it is used to set the camera and orient the vtkActors. The default frame of the 2D and 3D viewers is the world frame. Their is only one TransformationManager (all public methods are static). .. note:: on shared and raw pointers Transformation and Frames can be manipulated locally using their raw pointer. Use the shared pointer only if you need to own the object as well, that if the Transformation or Frame is part of your class members and need to be kept alive for your code to work. Using a shared pointer ensures that the Frame or Transformation won't be removed from the system by the TransformationManager. If you only need to access or modify information on a frame or transformation, only use the raw pointer. \\section TransformationManager API The TransformationManager provides the following utilities: - addFrameOfReference(...) methods add FrameOfReference objects - addTransformation(...) methods add Transformation objects - getTransformationOwnership(..) methods returns the shared_ptr to a Transformation - getTransformation(...) method computes a Transformation between two Frames, if any path exists between them - updateTransformation(...) methods modify the transformation matrix values Two methods are provided for the manipulation of world frame: - getWorldFrame() returns the unique world frame, to which all frames should have a path to (composed of 1 or more transformations). - ensurePathToWorld() to add a default identity Transformation between the provided Frame and the worldFrame if no Transformation was defined. \\section Transformation A Transformation can either be: - directly defined by the user using addTransformation() -> it holds a user defined 4x4 matrix. It has 0 sources. - an inverse of another Transformation. Inverse Transformation are automatically generated by the TransformationManager. It therefore has 1 source (the direct Transformation it is the inverse of). - a composite transformation defined automatically by the TransformationManager to pass from one source to another one over more than one frame. It is composed by a list of other transformations. It therefore has more than one sources. Information about a Transformation t can be obtained from the TransformationManager using: - hasSources(t) and getSources(t) - isCompositeTransformation(t) - isInverseTransformation(t) - isDefaultIdentityToWorld(t) There is three cases where TransformationManager will automatically create a transformation: - when a linear transformation is added using addTransformation(), the inverse transformation is automatically generated and stored in the system. The new transformation will therefore only have 1 source. - when getTransformation() is called and finds a new path of transformations between the two given frames, it will generate a new composed transformation (for optimization) from those transformations. The new transformation will therefore have all those transformations as sources. - when ensurePathToWorld(f) is called, and no path can be found between f and the world frame, then a new identity transformation from f to world frame is created. This new transformation has no source (note that TransformationManager will also create its inverse, which has 1 source). Use isDefaultIdentityToWorld() to check if a transformation was generated this way. Note that TransformationManager always generates an inverse transformation for any existing linear transformation if it does not exist already. \\section Transformation Sources The lists of Transformation sources are managed by the TransformationManager. Sources are the transformations that are used (composed) to compute a Transformation t. If any of the sources are modified, t is guaranteed to reflect this update, i.e., it is recomputed from its sources. If t has only one source, this means t is the inverse of this source. See also: hasSources() getSources() \\section FrameOfReference A FrameOfReference represents a specific system of coordinates in which component data's coordinates are expressed. It can have a name, a description, and anatomical labels associated to its axes: for example, the X axis may have label L on the lower values, and R on the higher values (for Left/Right anatomical orientation). You can add new Frames of reference using addFrameOfReference methods when creating a new Component (even though Component constructor creates a default one for you), or if you need to manage multiple frames in your component (e.g. for an articulated robot). If you need to get ownership of a specific FrameOfReference (e.g. you want your Component to store the same Frame as another Component), use getFrameOfReferenceOwnership() To edit anatomical information, name or description, refer to FrameOfReference class. \\section Path management When you need a Transformation from one Frame to another, the method to call is getTransformation() This method first looks if a Transformation was added using addTransformation between those Frames, then if there is already a cached composite Transformation linking both Frames, and finally, it checks whether there is a path in the graph of Frames and Transformations linking those Frames using intermediary Frames. Private methods hasPath() and getPath() are used to search the graph for a suitable path. If there is one, a new cached composite Transformation is stored (it combines the path of Transformations into one). If there is no path, these methods return nullptr. When the user wants to ensure that a specific Frame has a Transformation to the WorldFrame, she/he should call ensurePathToWorld(). This will create a default identity Transformation to the WorldFrame if there is no existing path between the Frame and the WorldFrame. All default identity Transformations are marked, so that if a new Transformation is added using addTransformation, these Transformations can be automatically removed. This is needed to avoid creation of multiple path between Frames (there will therefore never be any cycle in the Frame/Transformation graph). \\section Memory management and cleaning up As FrameOfReference and Transformation constructors are private, all Frames and Transformations must be created through the TransformationManager. Internally, Transformation and FrameOfReference objects are stored using std::shared_ptr This means that ownership of these objects is shared between the TransformationManager and custom objects used in CamiTK such as Component (which owns its FrameOfReference), ImageComponent (which also owns its internal Transformation from raw to main). Most methods of this class return or use raw pointers, meaning they do not return or get ownership of the FrameOfReference or Transformation object. The raw pointers are meant to be used for immediate processing (e.g. getting the name of a Frame, transforming the coordinates of a point using a Transformation) but not to store the pointer. If you need to store the object, you must use getFrameOfReferenceOwnership() and getTransformationOwnership() This makes explicit who is owning Transformations and Frames. Note that you may not get ownership of a composite Transformation (computed from others) or a default Transformation, as those must be removable at all times. TransformationManager may delete any Transformation that is not owned outside its internal data structure (which mean they are not used anymore apart from internally). See also: cleanupFramesAndTransformation(), removeDefaultPaths(), removeTransformation(). To determine whether a Transformation or Frame is owned outside the TransformationManager, std::shared_ptr usage counter is used. \\section Using TransformationManager in your extensions: TransformationManager use cases Most common use cases for CamiTK extension developers: - adding a new Component: use the default Component constructor which creates a new default FrameOfReference for the Component - adding a new Component created from another one: - if the new Component is using the same Frame, just set its Frame to the original component's frame using InterfaceFrame::setFrameFrom() - if you need to ensure a Component has its own independent frame, use InterfaceFrame::resetFrame() - Special cases for ImageComponent: ImageComponents have a data frame and a main transformation (from their data to their main frame) that needs to be taken care of. Be aware that ImageComponent::setFrameFrom() and ImageComponent::resetFrame() are reimplemented to take care of the data frame and main transformation. For instance: - your action creates an image outImage from an image inImage, just call `out->setFrameFrom(in)` - your action creates an mesh outMesh from an image inImage, call `outMesh- >setFrame(TransformationManager::getFrameOfReferenceOwnership(inImage- >getDataFrame()));` as the mesh is computed from the image data, the mesh is defined in the image component data frame - Registering a Component to another: for example, compute the registration between two meshes, then use addTransformation() between the frames of the two meshes. .. warning:: : if there is already a Transformation path between the meshes and the world frame is not in this path, addTransformation() will return nullptr. This means that computed transformation (for example after previous registration) already gives a transformation between the two meshes. If you want to update previous registration, you should use updateTransformation() instead. If updateTransformation() also returns nullptr, this means you are trying to create a cycle in the transformation graph. - You can use multiple Frames and Transformation inside your own Component, use the TransformationExplorer to check if it is working as expected. In the case of an articulated robot, each part may have its own FrameOfReference, and each articulation its own Transformation. You can use methods addFrameOfReference, addTransformation, updateTransformation to create and update frames and transformations in your Action and Component extensions. """ @staticmethod def addFrameOfReference(name: str, description: str = '') -> ...: """ Add a FrameOfReference with a name and description This is the standard way to create a new FrameOfReference Returns: the corresponding shared_ptr (save it to keep ownership, ignore if ownership is not needed) """ @staticmethod def addTransformation(arg0: ..., arg1: ...) -> ...: """ Create and register a new identity Transformation between two frames if there is no existing transformation between those frames. Returns: a pointer to the new Transformation or nullptr if a transformation between those frames already exist (use getTransformation()) """ @staticmethod def getFramesOfReference() -> list[FrameOfReference]: """ Get a list of all stored FrameOfReference """ @staticmethod def getTransformation(arg0: ..., arg1: ...) -> ...: """ Get a transformation if it exists or compute it if a path exists between the frames. """ @staticmethod def getTransformations() -> list[FrameOfReference]: """ Returns the list of all transformations managed in the system, independents or not. """ @staticmethod def getWorldFrame() -> ...: """ Get the WorldFrame This is the Frame that links all Frames so that there is a common space If a Component's frame is not linked by a Transformation to any other Frame, a default identity Transformation should be created between it and this worldFrame This is done by calling ensurePathToWorld """ @staticmethod def preferredDefaultIdentityToWorldLink(arg0: ...) -> bool: """ Call this method when you prefer (for visualization purpose only) to have a direct link to world from the given frame instead of any other path. If another path to world exists from the frame and include a default identity transformation to world, it will be delete in favor of a new default identity transformation that directly links the given frame to world. Returns: false if there is a path to world that contains no default identity transformation """ @staticmethod @typing.overload def removeTransformation(arg0: ...) -> bool: """ Remove an existing transformation between the two frames. This method checks that the given shared_ptr has no other owner than the caller (i.e., only the caller of this method has ownership of the given shared_ptr). If this is true, then the shared_ptr will be set to nullptr, which will result in the deletion of the Transformation. If there is another owner, the shared_ptr is not modified, and the Transformation will not be removed. If the given shared_ptr is equal to nullptr (for instance when calling removeTransformation(getTransformationOwnership(t)) with t being a composite transformation), this method returns false. .. warning:: if successful, the shared_ptr must not be used anymore (as it is set to nullptr). Returns: true if the Transformation was removed from the transformation system, false otherwise. """ @staticmethod @typing.overload def removeTransformation(arg0: ..., arg1: ...) -> bool: """ Remove an existing transformation between the two frames. See also: removeTransformation(std::shared_ptr&) .. warning:: if successful, the shared_ptr must not be used anymore (as it is set to nullptr) after that. """ @staticmethod @typing.overload def updateTransformation(arg0: ..., arg1: ..., arg2: numpy.ndarray) -> None: """ Modify the Transformation between the two frames by setting its vtkTransform @warning only the vtkMatrix of the given vtkTransform is duplicated (later modification of vtkTr will not update the transformations) """ @staticmethod @typing.overload def updateTransformation(arg0: ..., arg1: ..., arg2: numpy.ndarray) -> None: """ Modify the Transformation between the two frames by setting its vtkMatrix Note that the vtkMatrix must is given as a 4x4 numpy array. """ @staticmethod @typing.overload def updateTransformation(arg0: ..., arg1: numpy.ndarray) -> None: """ Modify the Transformation by setting its vtkTransform @warning only the vtkMatrix of the given vtkTransform is duplicated (later modification of vtkTr will not update the transformations) """ @staticmethod @typing.overload def updateTransformation(arg0: ..., arg1: numpy.ndarray) -> None: """ Modify the Transformation by setting its matrix Note that the vtkMatrix must is given as a 4x4 numpy array. """ class pythonConsoleRedirect: @staticmethod def flush() -> None: ... @staticmethod def write(arg0: typing.Any) -> None: ... def error(arg0: str) -> None: """ Logs an error message. """ def getDebugInfo() -> str: ... def getPythonVersion() -> str: ... def info(arg0: str) -> None: """ Logs an info message. """ def newImageComponentFromNumpy(array: numpy.ndarray, name: str = 'image', spacing: typing.Any = None) -> ImageComponent: """ Create an Image Component by creating a new vtkImageData from the given array of voxel and spacing, if provided) """ def newMeshComponentFromNumpy(name: str = 'mesh', points_array: numpy.ndarray[numpy.float64], polys_array: numpy.ndarray[numpy.int64] = ...) -> MeshComponent: """ Creates a Mesh Component by creating a new vtkPointSet made of the given point array and poly array(only vtkPolyData and point clouds are supported for now) """ def redirectStandardStreams() -> None: ... def refresh() -> None: """ Refreshes the application, including the transformation manager and all registered viewers. """ def show() -> None: """ Starts a default CamiTK Application with the default main window and event loop, and shows the main window. This function is experimental and is still not entirely functional nor stable. Use at your own risks and only if you know what your doing. You have been warned! """ def startApplication() -> None: """ Starts a default CamiTK Application with the default main window and event loop. This function is experimental and is still not entirely functional nor stable. Use at your own risks and only if you know what your doing. You have been warned! """ def trace(arg0: str) -> None: """ Logs a trace message. """ def warning(arg0: str) -> None: """ Logs a warning message. """ __version__: str = 'CamiTK 6.0.0'