### Installing qudi-core from PyPI (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command installs the `qudi-core` package directly from the Python Package Index (PyPI). It's the recommended method for most users who do not intend to actively develop the `qudi-core` source code, providing a stable and easily maintainable version via `pip`. ```console python -m pip install qudi-core ``` -------------------------------- ### Installing qudi-core from Source in Development Mode (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command installs the `qudi-core` package from a local source directory in 'editable' or 'development' mode. The `-e` flag allows changes to the source code to take effect without reinstallation, making it ideal for active development of `qudi-core` or, more commonly, for measurement module addons. ```console python -m pip install -e . ``` -------------------------------- ### Verifying Python 3.10 Version on Windows Console Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command is used on a Windows console to verify the installed Python version. It's a prerequisite step to ensure Python 3.10.x is available before proceeding with the `qudi` environment setup. The output confirms the active Python interpreter's version. ```console C:\> python -V Python 3.10.11 ``` -------------------------------- ### Creating Python Virtual Environment on Windows Console Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command initiates the creation of a new Python virtual environment named `qudi-env` using the `venv` module on Windows. It isolates `qudi`'s specific package dependencies, preventing conflicts with other Python installations and enabling easy uninstallation by deleting the environment folder. ```console C:\Software\qudi> python -m venv qudi-env ``` -------------------------------- ### Activating venv Environment on Windows Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md These commands navigate into the 'Scripts' directory of a 'venv' environment and then execute the 'activate' script to activate the Python environment on Windows. The command prompt will show the environment name as a prefix upon successful activation. ```Console C:\Software\qudi> cd qudi-env\Scripts\ C:\Software\qudi\qudi-env\Scripts> .\activate ``` -------------------------------- ### Activating venv Environment on Unix Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md These commands navigate into the 'Scripts' directory of a 'venv' environment and then source the 'activate' script to activate the Python environment on Unix-like systems. This makes the environment's Python and scripts available in the current shell session. ```Bash foo@bar:/opt/qudi$ cd qudi-env/Scripts foo@bar:/opt/qudi/qudi-env/Scripts$ source activate ``` -------------------------------- ### Starting qudi via Direct Command (Shell) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/startup.md This command initiates the qudi application directly from the command line after activating the Python environment. It's the simplest and recommended way to run qudi for general use. ```shell > qudi ``` -------------------------------- ### Verifying Python 3.10 Version on Unix Bash Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command is executed in a Unix bash shell to check the current Python version. It serves as a crucial preliminary step to confirm that Python 3.10.x is being used for the `qudi` installation. The output displays the version of the Python interpreter found on the system's PATH. ```bash foo@bar:~$ python3 -V Python 3.10.11 ``` -------------------------------- ### Starting JupyterLab Server (Console) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/jupyter.md This command launches the JupyterLab server, which provides the web-based interface for creating and running Jupyter Notebooks. Ensure the qudi environment is activated before executing this command to access the qudi kernel. ```console jupyter lab ``` -------------------------------- ### Starting Qudi Configuration Editor via Python Module (Shell) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This command starts the standalone graphical Qudi configuration editor by running its main module `config_editor` from the `qudi.tools` package using the Python interpreter. This method requires navigating to the module's directory first. ```Shell (qudi-venv) C:\Software\qudi-core\src\qudi\tools\> python -m config_editor ``` -------------------------------- ### Starting qudi Application (Console) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/jupyter.md This command starts the qudi application from the console. The qudi application must be running for the Jupyter Notebook to connect and interact with its modules and functionalities. ```console qudi ``` -------------------------------- ### Activating Conda Environment Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command activates a Conda environment named 'qudi-env'. Once activated, all subsequent Python commands will use the packages and interpreter from this specific environment. ```Console conda activate qudi-env ``` -------------------------------- ### Configuring Startup Modules - YAML Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This example demonstrates how to configure the 'startup_modules' property within the 'global' section to automatically load a specific GUI module ('my_gui_module') upon qudi startup. It highlights that only the highest-level module needs to be specified, simplifying the configuration by not requiring all dependencies to be listed. ```YAML global: startup_modules: - 'my_gui_module' gui: my_gui_module: ... ``` -------------------------------- ### Starting Qudi Configuration Editor via Executable (Shell) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This command launches the standalone graphical Qudi configuration editor by executing the `qudi-config-editor` script within the active Python virtual environment. It's a direct and convenient way to open the editor. ```Shell (qudi-venv) C:\> qudi-config-editor ``` -------------------------------- ### Creating Python Virtual Environment on Unix Bash Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command creates a new Python virtual environment named `qudi-env` using the `venv` module within a Unix bash shell. This method ensures that `qudi`'s dependencies are self-contained, preventing system-wide package conflicts and allowing for straightforward removal of the environment. ```bash foo@bar:/opt/qudi$ python3 -m venv qudi-env ``` -------------------------------- ### Creating Conda Environment on Unix Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command creates a new Python 3.10 environment named 'qudi-env' using Conda on a Unix-like system. The environment will be created in a default Anaconda/Miniconda directory. ```Bash foo@bar:~$ conda create --name qudi-env python=3.10 ``` -------------------------------- ### Running qudi as a Python Module (Shell) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/startup.md This command executes qudi as a Python module. It's an alternative method to start the application, useful when managing Python environments or integrating with other Python scripts. ```shell > python -m qudi.core ``` -------------------------------- ### Installing qudi Kernel for Jupyter (Console) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/jupyter.md This command installs the qudi IPython kernel, making it available for use in Jupyter Notebooks. It typically needs to be run only once after qudi installation, but re-installation is required if a different qudi environment is used. ```console qudi-install-kernel ``` -------------------------------- ### Initializing TextDataStorage Object - Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This example demonstrates how to instantiate and configure a `TextDataStorage` object from `qudi.util.datastorage`. It sets various parameters like the `root_dir` for file storage, `comments` prefix, `delimiter`, `file_extension`, `column_formats` for data formatting, a flag to `include_global_metadata`, and the `image_format` for saving thumbnails. ```Python from qudi.util.datastorage import TextDataStorage, ImageFormat # Instantiate text storage object and configure it data_storage = TextDataStorage(root_dir='C:\\Data\\MyMeasurementCategory', comments='# ', delimiter='\t', file_extension='.dat', column_formats=('.8f', '.15e'), include_global_metadata=True, image_format=ImageFormat.PNG) ``` -------------------------------- ### Creating Conda Environment on Windows Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command creates a new Python 3.10 environment named 'qudi-env' using Conda on a Windows system. The environment will be created in a default Anaconda/Miniconda directory. ```Console C:\> conda create --name qudi-env python=3.10 ``` -------------------------------- ### Importing Matplotlib and Pyplot in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/matplotlib.ipynb This snippet demonstrates the standard way to import the Matplotlib library and its pyplot module, which is essential for creating most types of plots. The 'as plt' alias is a common convention for brevity. ```python import matplotlib import matplotlib.pyplot as plt ``` -------------------------------- ### Initializing Logger for General Python Modules Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/logging.md This example shows the standard Python approach to obtaining a logger instance for any general Python module, as described in the official `logging` documentation. It uses `getLogger` from the standard `logging` module, typically initialized with the module's `__name__` for context. ```Python from logging import getLogger logger = getLogger(__name__) logger.info('Module initialized') # create example log record ``` -------------------------------- ### Deleting Conda Environment Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command removes an existing Conda environment named 'qudi-env'. It should be executed from any command line, and the environment will be completely deleted. ```Console conda env remove --name qudi-env ``` -------------------------------- ### Generating and Plotting a Histogram with Matplotlib Pyplot in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/matplotlib.ipynb This example illustrates how to generate random data following a normal distribution and visualize its frequency distribution using a histogram. It includes adding axis labels, a title, text annotations, setting axis limits, and enabling a grid. ```python mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60, .025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True) plt.show() ``` -------------------------------- ### Creating a Simple Line Plot with Matplotlib Pyplot in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/matplotlib.ipynb This code illustrates how to generate a basic line plot from a list of numerical data. It also shows how to add a label to the y-axis and display the plot using `plt.show()`. ```python plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() ``` -------------------------------- ### Deactivating Conda Environment Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/installation.md This command deactivates the currently active Conda environment, returning the command line to the base or previous environment. This is used to switch between environments or exit an environment session. ```Console conda deactivate ``` -------------------------------- ### Logging Exceptions with Traceback in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/logging.md This example illustrates how to log an exception, including its full traceback, using the `exception()` method of a logger instance within an `except` block. This is crucial for capturing detailed error information that aids in debugging and problem resolution. ```Python try: 0/0 except ZeroDivisionError: # This will include the traceback in the log record: .exception('There was an exception while trying to divide two numbers') ``` -------------------------------- ### Controlling Measurement Modules in Jupyter (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/jupyter.md This example shows how to programmatically interact with an active qudi measurement module, such as 'red_laser', from a Jupyter Notebook. It demonstrates calling a method ('turn_on_emission') and accessing an attribute ('is_running') of the module. ```python red_laser.turn_on_emission() red_laser.is_running ``` -------------------------------- ### Plotting Multiple Lines with Different Styles in Matplotlib Pyplot in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/matplotlib.ipynb This example demonstrates plotting multiple data series on the same axes. It uses NumPy to generate evenly spaced data and specifies different line styles ('r--', 'bs', 'g^') for each series to distinguish them visually. ```python # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') plt.show() ``` -------------------------------- ### Saving Data with Generic Filename using qudi-core (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This snippet illustrates how to prepare numerical data and associated metadata, notes, and column headers, then save them to a file using the `data_storage.save_data` method. It shows the creation of example data using NumPy, explicit timestamping, and the inclusion of optional `nametag` and `column_headers` for a generically constructed filename. The method returns the saved file path, the actual timestamp used, and the dimensions of the saved data. ```Python import numpy as np from datetime import datetime # Create example data x = np.linspace(0, 1, 1000) # 1 sec time interval y = np.sin(2 * np.pi * 2 * x) # 2 Hz sine wave data = np.asarray([x, y]).transpose() # Format data into a single 2D array with x being the first # column and y being the second column # Prepare a dict containing metadata to be saved in the file header metadata = {'sample_number': 42, 'batch' : 'xyz-123'} # Create an explicit timestamp. timestamp = datetime(2021, 5, 6, 11, 11, 11) # 06.05.2021 at 11h:11m:11s # timestamp = datetime.now() # Usually you would use this # Create a nametag to include in the file name (optional) nametag = 'amplitude_measurement' # Create an iterable of data column header strings (optional) column_headers = ('time (s)', 'amplitude (V)') # Create an arbitrary string of informal "lab notes" that is included in the file header notes = 'This measurement was performed under the influence of 10 mugs of coffee and no sleep.' # Save data to file file_path, timestamp, (rows, columns) = data_storage.save_data(data, timestamp=timestamp, metadata=metadata, notes=notes, nametag=nametag, column_headers=column_headers, column_dtypes=(float, float)) ``` -------------------------------- ### Connecting a Local Qudi Module to Other Modules (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This example shows how to establish connections between a local Qudi module and other modules using 'Connector' meta-objects. The 'connect' property maps a custom connector name to the unique name of another module configured within the same Qudi instance, facilitating inter-module communication. ```yaml logic: my_module: module.Class: 'my_module.MyModuleClass' connect: my_connector_name: 'my_other_module' ``` -------------------------------- ### Using Connector for Overloaded Interface Methods in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/programming_guidelines/hardware_with_multiple_interfaces.md This Python snippet demonstrates how a `LogicBase` module utilizes `qudi.core.connector.Connector` to interact with hardware modules that have overloaded interface methods. By instantiating `Connector` objects for specific interfaces, the logic module can call methods like 'start()' without needing to differentiate between separate devices or a single device with overloaded methods, as the Connector (via OverloadProxy) handles the resolution. ```python from qudi.core.connector import Connector from qudi.core.module import LogicBase class MyLogicModule(LogicBase): """ Fictional logic module illustrating the use of the Connector object with overloaded interface methods. """ # Instantiate connectors _data_reader = Connector(name='data_reader', interface='DataReaderInterface') _data_output = Connector(name='data_output', interface='DataOutputInterface') # Declare other class-level stuff ... # define qudi module on_activate/on_deactivate ... # example method with calls to hardware module(s) def do_stuff(self): self._data_reader().start() # Will call "start" implementation for "DataReaderInterface" self._data_output().start() # Will call "start" implementation for "DataOutputInterface" ``` -------------------------------- ### Reading Global Metadata from Data Storage (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This example shows how to retrieve a shallow copy of the global metadata dictionary using `data_storage.get_global_metadata()`. The returned dictionary allows inspection of the current global metadata. Users are cautioned against mutating the returned dictionary directly, as it is only a shallow copy and direct modifications might lead to unintended side effects. ```Python metadata = data_storage.get_global_metadata() ``` -------------------------------- ### Creating Subplots and Custom Functions in Matplotlib Pyplot in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/matplotlib.ipynb This snippet shows how to define a custom mathematical function and plot its output. It further demonstrates the use of `plt.subplot()` to create multiple plots within a single figure, arranging them in a 2x1 grid. ```python def f(t): return np.exp(-t) * np.cos(2*np.pi*t) t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) plt.figure(1) plt.subplot(211) plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') plt.subplot(212) plt.plot(t2, np.cos(2*np.pi*t2), 'r--') plt.show() ``` -------------------------------- ### Enabling Remote Access for a Local Qudi Module (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This configuration extends a local Qudi module to be accessible by remote Qudi instances. By setting the 'allow_remote' property to 'True', the module becomes available for remote connections, enabling distributed Qudi setups. ```yaml logic: my_module: # unique custom name for this module module.Class: 'my_module.MyModuleClass' allow_remote: True ``` -------------------------------- ### Defining DataReader and DataOutput Interfaces in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/programming_guidelines/hardware_with_multiple_interfaces.md This snippet defines two abstract base classes, DataReaderInterface and DataOutputInterface, both inheriting from qudi.core.module.Base. Each interface includes common abstract methods like start and a constraints property, along with unique methods (get_data and set_data), illustrating the source of potential namespace collisions when combined in a single hardware module. ```Python from abc import abstractmethod from qudi.core.module import Base class DataReaderInterface(Base): """ This is a fictional data reader interface. """ @property @abstractmethod def constraints(self): """ A read-only data structure containing all hardware parameter limitations. """ raise NotImplementedError @abstractmethod def get_data(self): """ Get the read data array. @return iterable: Data array """ raise NotImplementedError @abstractmethod def start(self): """ Start the data acquisition. """ raise NotImplementedError class DataOutputInterface(Base): """ This is a fictional data output interface. """ @property @abstractmethod def constraints(self): """ A read-only data structure containing all hardware parameter limitations. """ raise NotImplementedError @abstractmethod def set_data(self, data): """ Set the data array to output. @param iterable data: The data array to output """ raise NotImplementedError @abstractmethod def start(self): """ Start the data output. """ raise NotImplementedError ``` -------------------------------- ### Defining Overloaded Attributes in Python with OverloadedAttribute Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/programming_guidelines/hardware_with_multiple_interfaces.md This snippet defines a `MyHardwareModule` class that inherits from `DataReaderInterface` and `DataOutputInterface`. It demonstrates how to use `OverloadedAttribute` to flag attributes like `start` (method) and `constraints` (property) as overloaded, registering multiple implementations for each using decorators associated with specific interface names. ```Python from qudi.interface.data_reader import DataReaderInterface from qudi.interface.data_output import DataOutputInterface from qudi.util.overload import OverloadedAttribute class MyHardwareModule(DataReaderInterface, DataOutputInterface): """ This will become my new fancy hardware module to combine DataReaderInterface and DataOutputInterface functionality. """ # Define qudi module activation/deactivation ... # Do other stuff ... def get_data(self): # Do something return tuple(range(42)) def set_data(self, data): # Do something pass # Flag "start" attribute as overloaded attribute start = OverloadedAttribute() # Register multiple implementations for "start" via convenient decorator # The key words under which the implementations are registered must be the corresponding # interface class names. # Make sure to use "start" as attribute name for all implementations. @start.overload('DataReaderInterface') def start(self): # Start the data reader print('Data reader started through "DataReaderInterface" interface method') @start.overload('DataOutputInterface') def start(self): # Start the data output print('Data output started through "DataOutputInterface" interface method') # You can do the same for properties. Just make sure to apply the @property decorator first. constraints = OverloadedAttribute() @constraints.overload('DataReaderInterface') @property def constraints(self): # Return data reader constraints print('Data reader constraints requested through "DataReaderInterface" interface.') return dict() @constraints.overload('DataOutputInterface') @property def constraints(self): # Return data output constraints print('Data output constraints requested through "DataOutputInterface" interface.') return dict() ``` -------------------------------- ### Plotting with Various Y-Axis Scales in Matplotlib Pyplot in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/matplotlib.ipynb This snippet demonstrates how to apply different y-axis scaling options (linear, log, symmetric log, and logit) to a plot. It uses subplots to display the same data with each scale, highlighting their effects on data visualization. ```python # make up some data in the interval ]0, 1[ y = np.random.normal(loc=0.5, scale=0.4, size=1000) y = y[(y > 0) & (y < 1)] y.sort() x = np.arange(len(y)) # plot with various axes scales plt.figure(1) # linear plt.subplot(221) plt.plot(x, y) plt.yscale('linear') plt.title('linear') plt.grid(True) # log plt.subplot(222) plt.plot(x, y) plt.yscale('log') plt.title('log') plt.grid(True) # symmetric log plt.subplot(223) plt.plot(x, y - y.mean()) plt.yscale('symlog', linthreshy=0.05) plt.title('symlog') plt.grid(True) # logit plt.subplot(224) plt.plot(x, y) plt.yscale('logit') plt.title('logit') plt.grid(True) plt.show() ``` -------------------------------- ### Adding Global Metadata to Data Storage (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This example illustrates how to add global metadata to all data storage objects using `add_global_metadata`. Metadata can be added as a dictionary or a single key-value pair. The `overwrite=False` parameter prevents overwriting existing keys, raising a `KeyError` if a conflict occurs, promoting robust and thread-safe metadata management across different modules. ```Python # Create global metadata to ADD to the global metadata dict global_meta = {'user': 'Batman'} # Add metadata in a thread-safe way to ALL data storage objects data_storage.add_global_metadata(global_meta, overwrite=False) # This would have the same effect from qudi.util.datastorage import DataStorageBase DataStorageBase.add_global_metadata(global_meta) # ...or this from qudi.util.datastorage import NpyDataStorage NpyDataStorage.add_global_metadata(global_meta) # You can also add a single key-value pair like this: data_storage.add_global_metadata('frustration_level', 9000, overwrite=False) ``` -------------------------------- ### Defining a Multi-Interface Hardware Module in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/programming_guidelines/hardware_with_multiple_interfaces.md This snippet demonstrates how to define a Python hardware module that inherits from multiple qudi interface classes, DataReaderInterface and DataOutputInterface. It serves as the base for a module combining data reading and output functionalities, highlighting the initial setup before addressing attribute name collisions. ```Python from qudi.interface.data_reader import DataReaderInterface from qudi.interface.data_output import DataOutputInterface class MyHardwareModule(DataReaderInterface, DataOutputInterface): """ This will become my new fancy hardware module to combine DataReaderInterface and DataOutputInterface functionality """ pass ``` -------------------------------- ### Removing Global Metadata from Data Storage (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This snippet demonstrates how to remove global metadata using `remove_global_metadata`. It shows examples for removing a single key-value pair by specifying the key as a string, or removing multiple key-value pairs by providing a list of keys. This ensures proper cleanup of global metadata when it is no longer relevant, typically in module deactivation routines. ```Python # to remove a single key-value pair data_storage.remove_global_metadata('user') # or if you want to remove multiple key-value pairs with one call data_storage.remove_global_metadata(['user', 'frustration_level']) ``` -------------------------------- ### Displaying qudi Command Line Arguments Help (Shell) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/startup.md This output shows the available command-line arguments for running qudi, obtained by executing `qudi -h` or `python -m qudi.core -h`. It details options like `--help`, `--no-gui`, `--debug`, `--config`, and `--logdir`, explaining their purpose and usage for customizing qudi's startup behavior. ```shell usage: python -m qudi.core [-h] [-g] [-d] [-c CONFIG] [-l LOGDIR] optional arguments: -h, --help show this help message and exit -g, --no-gui Run qudi "headless", i.e. without GUI. User interaction only possible via IPython kernel. -d, --debug Run qudi in debug mode to log all debug messages. Can affect performance. -c CONFIG, --config CONFIG Path to the configuration file to use for for this qudi session. -l LOGDIR, --logdir LOGDIR Absolute path to log directory to use instead of the default one "/qudi/log/" ``` -------------------------------- ### Defining a Basic Qudi Logic Module in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/getting_started.md This snippet illustrates the fundamental structure of a `qudi` logic module, inheriting from `LogicBase`. It demonstrates how to declare signals (`QtCore.Signal`) for inter-module communication, define configuration options (`ConfigOption`), manage persistent status variables (`StatusVar`), and establish connections to other modules or hardware (`Connector`). The `on_activate` and `on_deactivate` methods are placeholders for module lifecycle events. ```Python class TemplateLogic(LogicBase): # Declare signals to send events to other modules connecting to this module sigCounterUpdated = QtCore.Signal(int) # update signal for the current integer counter value # Declare static parameters that can/must be declared in the qudi configuration _increment_interval = ConfigOption(name='increment_interval', default=1, missing='warn') # Declare status variables that are saved in the AppStatus upon deactivation of the module and # are initialized to the saved value again upon activation. _counter_value = StatusVar(name='counter_value', default=0) # Declare connectors to other logic modules or hardware modules to interact with _template_hardware = Connector(name='template_hardware', interface='TemplateInterface', optional=True) def on_activate(self) -> None: ... def on_deactivate(self) -> None: ... ``` -------------------------------- ### Executing qudi via Startup Script (Shell) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/setup/startup.md This command runs qudi by directly executing the `runnable.py` script located in the qudi main directory. This method is particularly beneficial for developers working within an IDE like PyCharm, allowing for easier debugging and development. ```shell > python runnable.py ``` -------------------------------- ### Implementing a qudi Hardware Module (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/hardware_interface.md This snippet demonstrates `MySimpleInstrument`, a concrete hardware module that implements the `MySimpleInterface`. It provides concrete implementations for `read_value`, `some_setting` (getter and setter), and also `on_activate` and `on_deactivate` methods inherited from the `Base` class, fulfilling the interface contract and enabling module initialization and cleanup. ```Python from qudi.interface.my_simple_interface import MySimpleInterface class MySimpleInstrument(MySimpleInterface): """ Hardware module description and license/copyright header goes here """ def on_activate(self): """ Initialize module upon activation """ # Perform any module initialization here, e.g. establish a connection to the instrument etc. ... def on_deactivate(self): """ Perform module cleanup upon deactivation """ # Clean up your module and free all resources, e.g. terminate the instrument connection ... def read_value(self) -> float: """ Reads a value from the instrument and returns it """ value = ... # Read a value from the instrument return value @property def some_setting(self) -> int: """ Property holding some integer type setting in the instrument """ value = ... # Retrieve the setting value from the instrument return value @some_setting.setter def some_setting(self, value: int) -> None: """ Setter for property """ ... # Perform some sanity checking apply the new setting value to the instrument ``` -------------------------------- ### Implementing Core DataStorage API Methods - Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This snippet shows the abstract API methods `save_data` and `load_data` that all specialized data storage classes in `qudi.util.datastorage` must implement. These methods define the core functionality for saving and loading data, metadata, and notes, with specific keyword-only arguments for `save_data` and flexible arguments for `load_data`. ```Python def save_data(self, data, *, metadata=None, notes=None, nametag=None, timestamp=None, **kwargs): # Save data to appropriate format pass def load_data(self, *args, **kwargs): # Load data and metadata and return it pass ``` -------------------------------- ### Default Global Configuration - YAML Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This snippet illustrates the default structure and values for the 'global' section of the qudi configuration file. It includes settings for startup modules, remote server details, UI behavior, and data directory management. These properties are automatically populated if not explicitly defined in the user's configuration file. ```YAML global: startup_modules: [] remote_modules_server: null namespace_server_port: 18861 force_remote_calls_by_value: True hide_manager_window: False stylesheet: 'qdark.qss' default_data_dir: null daily_data_dirs: True extension_paths: [] ``` -------------------------------- ### Implementing Custom Linear Fit Model in Qudi (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/programming_guidelines/data_fitting_integration.md This snippet demonstrates how to create a custom fit model in Qudi by inheriting from `FitModelBase`. It shows the `__init__` method for setting parameter hints with default values and bounds, the static `_model_function` which defines the actual mathematical model, and an optional `estimate` method decorated with `@estimator('default')` to provide an initial guess for the fit parameters based on input data. ```Python from qudi.util.fit_models.model import FitModelBase, estimator class CustomLinearFit(FitModelBase): """ """ def __init__(self, **kwargs): super().__init__(**kwargs) self.set_param_hint('slope', value=1., min=-np.inf, max=np.inf) @staticmethod def _model_function(x, slope): return slope* x # optional, make a good initial guess for the optimize @estimator('default') # provide different estimators specified by name string def estimate(self, data, x): y_span = max(data) - min(data) x_span = max(x) - min(x) estimate = self.make_params() estimate['slope'] = y_span/x_span return estimate ``` -------------------------------- ### Preparing Matplotlib Figure for Thumbnail Saving (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This snippet shows the initial steps for creating a `matplotlib` figure and plotting data, which can then be used as a thumbnail. It demonstrates how to initialize a figure and an axes object, plot the data, and set axis labels. This prepared figure object would subsequently be passed to the `data_storage.save_thumbnail` method to save it alongside the main data file. ```Python import matplotlib.pyplot as plt # Create figure and plot data fig = plt.figure() ax = fig.add_subplot() ax.plot(x, y) ax.set_xlabel('time (s)') ax.set_ylabel('amplitude (V)') ``` -------------------------------- ### Configuring a Remote Hardware Module in Qudi (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This configuration defines a remote hardware module, allowing a Qudi instance to connect to a module running on a different host. It specifies the 'native_module_name' on the remote host, its network 'address' and 'port', and optionally includes 'certfile' and 'keyfile' paths for SSL-secured connections. ```yaml hardware: my_remote_module: native_module_name: 'module_name_on_remote_host' address: '192.168.1.100' port: 12345 certfile: '/path/to/certfile.cert' # omit for unsecured keyfile: '/path/to/keyfile.key' # omit for unsecured ``` -------------------------------- ### Logging Data by Appending to File (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/core_elements/data_storage.md This snippet demonstrates how to log data incrementally using `new_file` to create a file with a header and `append_file` to add rows. `new_file` initializes the file with metadata and column headers, while `append_file` efficiently adds individual data rows to the created file. This pattern is useful for data logging where data is generated and saved in chunks. ```Python # Create data file with the same variables as in the save_data example above file_path, timestamp = data_storage.new_file(timestamp=timestamp, metadata=metadata, notes=notes, nametag=nametag, column_headers=column_headers, column_dtypes=(float, float)) # Append each row of the previously created data array one after the other for data_row in data: data_storage.append_file(data_row, file_path) ``` -------------------------------- ### Asynchronous GUI-Logic Communication using Signals and Slots - Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/measurement_modules.md This snippet demonstrates asynchronous communication between a GUI module and a logic module using Qt signals and slots. The GUI module triggers a long-running logic method via a signal, remaining responsive, and receives a completion notification via another signal. It utilizes `qudi.core.connector.Connector` to establish the connection. ```Python from PySide2.QtCore import Signal from qudi.core.module import Base, LogicBase from qudi.core.connector import Connector # GUI module declaration in e.g. qudi/gui/my_gui_module.py class MyGuiModule(Base): """ Description goes here """ # Qt signal triggering the start of the measurement sigStartMeasurement = Signal() # Connector to get a reference to the measurement logic module _logic_connector = Connector(interface='MyLogicModule', name='my_logic') ... def on_activate(self): self.sigStartMeasurement.connect(self._logic_connector().start_measurement) self._logic_connector().sigMeasurementFinished.connect(self._measurement_finished) def trigger_measurement_start(self): """ Will just emit the sigStartMeasurement signal """ self.sigStartMeasurement.emit() def _measurement_finished(self): """ Callback for measurement finished signal from logic module """ print('Logic has finished the measurement') ... # Logic module declaration in e.g. qudi/logic/my_logic_module.py class MyLogicModule(LogicBase): """ Description goes here """ # Qt signal notifying all connected "listeners" about a finished measurement sigMeasurementFinished = Signal() ... def start_measurement(self): """ API method to start a measurement """ # Actually perform your measurement here and emit notification signal upon finishing self.sigMeasurementFinished.emit() ... ``` -------------------------------- ### Updating Changelog for New Release (Markdown) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/programming_guidelines/creating_releases.md This snippet shows the required structure for updating the 'changelog.md' file during a new release. It involves renaming the 'Pre-Release' section to the new version number, adding the release date, and creating a new empty 'Pre-Release' section at the top for future changes. ```Markdown # Changelog ## Pre-Release ### Breaking Changes None ### Bugfixes None ### New Features None ### Other None ## Version x.y.z Released on DD.MM.YYYY ... ``` -------------------------------- ### Initializing Logger for Qudi Internal Modules (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/logging.md This snippet demonstrates the recommended way to obtain a logger instance for modules that are part of the `qudi` package namespace but are not measurement modules. It utilizes `get_logger` from `qudi.core.logger`, initialized with the module's `__name__` attribute for proper hierarchical logging. ```Python from qudi.core.logger import get_logger logger = get_logger(__name__) logger.info('Module initialized') # create example log record ``` -------------------------------- ### Configuring a Minimum Local Logic Module in Qudi (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This snippet demonstrates the basic configuration for a local Qudi logic module. It assigns a unique custom name to the module and specifies the Python class path where the 'qudi.core.module.LogicBase' subclass, 'MyModuleClass', can be imported from 'qudi.logic.my_module'. ```yaml logic: my_module: # unique custom name for this module module.Class: 'my_module.MyModuleClass' ``` -------------------------------- ### YAML Configuration for a Measurement Module Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/config_options.md This YAML snippet illustrates the corresponding configuration structure for a measurement module. It shows how to define the `my_config_option` within the `options` property, allowing it to be read and used by the `ConfigOption` declared in the Python measurement module. ```YAML global: ... gui: ... hardware: ... logic: example_logic_identifier_name: module.Class: my_example_logic.MyExampleLogic options: my_config_option: 'I am a string from the qudi configuration' connect: ... ... ``` -------------------------------- ### Configuring Qudi Server for Remote Modules (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/remote_modules.md This YAML configuration snippet demonstrates how to set up a Qudi server to expose its hardware modules for remote access. It specifies the server's network address and port, and crucially, sets `allow_remote: True` for the desired hardware module to enable remote connections. This allows other Qudi instances to connect and interact with this module. ```YAML global: remote_modules_server: address: "ip.address.of.this.machine" port: port_of_the_server(int) hardware: name_of_hardware: module.class: "hardwarefile.classname" allow_remote: True options: ... ``` -------------------------------- ### Logging Messages with Different Levels in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/logging.md This snippet demonstrates the basic usage of a `logging.Logger` instance to create log records at various predefined levels. Each method call corresponds to a specific log level, allowing developers to categorize messages by their severity or importance. ```Python .debug('my debug message') .info('my info message') .warn('my warning message') .error('my error message') .critical('my critical message') ``` -------------------------------- ### Defining a Hardware Interface in qudi (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/hardware_interface.md This snippet defines `MySimpleInterface`, an abstract class inheriting from `qudi.core.Base`. It declares an abstract method `read_value` and an abstract read/write property `some_setting`, serving as a contract for concrete hardware module implementations. It highlights the proper use of `@abstractmethod` and `@property` decorators for defining abstract properties. ```Python from abc import abstractmethod from qudi.core import Base class MySimpleInterface(Base): """ Interface description and license/copyright header goes here """ @abstractmethod def read_value(self) -> float: """ Reads a value from the instrument and returns it """ pass @property @abstractmethod def some_setting(self) -> int: """ Property holding some integer type setting in the instrument """ pass @some_setting.setter def some_setting(self, value: int) -> None: """ Setter for property "some_setting" """ pass ``` -------------------------------- ### Declaring a Configuration Option in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/config_options.md This Python snippet demonstrates how to declare a configuration option within a measurement module using `qudi.core.configoption.ConfigOption`. It shows how to define a class variable that will be automatically initialized from the qudi configuration, including optional `name`, `default`, and `missing` arguments for flexible behavior. ```Python from qudi.core.configoption import ConfigOption from qudi.core.module import LogicBase class MyExampleLogic(LogicBase): """ Module description goes here """ _my_config_option = ConfigOption(name='my_config_option', default='Not configured', missing='warn') ... def print_my_config_option(self): print(self._my_config_option) ... ``` -------------------------------- ### Executing a Qudi Module Function from Console in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/getting_started.md This snippet shows how to invoke a function on a loaded `qudi` module directly from the manager console. After a custom logic module is successfully loaded, its public methods can be called by referencing the module instance (e.g., `example_logic`) and the desired function (e.g., `reset_counter()`). This is useful for interactive debugging or manual control. ```Python example_logic.reset_counter() ``` -------------------------------- ### Registering Custom Type Constructors in QUDI Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/config_options.md This snippet demonstrates two methods for providing a constructor function to a `ConfigOption` in QUDI. It shows how to use a lambda function directly in the `ConfigOption` definition or register a method as a constructor using the `@_my_config_option.constructor` decorator, enabling conversion of YAML data into custom `FancyDataType` objects. ```Python from qudi.core.configoption import ConfigOption from qudi.core.module import LogicBase class FancyDataType: def __init__(self, a, b): self.a = a self.b = b class MyExampleLogic(LogicBase): """ Module description goes here """ _my_config_option = ConfigOption(name='my_config_option') _my_other_config_option = ConfigOption(name='my_other_config_option', constructor=lambda yaml_data: FancyDataType(*yaml_data)) ... @_my_config_option.constructor def my_config_option_constructor(self, yaml_data): return FancyDataType(*yaml_data) ... ``` -------------------------------- ### Configuring Static Variables for a Local Qudi Module (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This snippet illustrates how to define static configuration options for a local Qudi module using 'ConfigOption' meta-objects. The 'options' property allows setting various data types (strings, numbers, lists) for module-specific variables, whose names are determined by attributes in the module's Python class. ```yaml logic: my_module: module.Class: 'my_module.MyModuleClass' connect: my_connector_name: 'my_other_module' options: my_first_config_option: 'hello world' my_second_config_option: - 42 - 123.456 - ['a', 'b', 'c'] ``` -------------------------------- ### Displaying a Basic Matplotlib Plot - Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/mpl_crash.ipynb This snippet creates a new Matplotlib figure, plots the data from arrays 'a' and 'b' (presumably x and y coordinates), displays the plot, and then closes the figure. It depends on `matplotlib.pyplot` being imported and `a`, `b` arrays being defined. ```python plt.figure() plt.plot(a,b) plt.show() plt.close() ``` -------------------------------- ### Configuring Remote Modules Server in Qudi-Core (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/configuration.md This YAML snippet demonstrates how to configure the `remote_modules_server` property within the `global` section of `qudi-core` settings. It specifies the server's network `address` and `port`, and optionally provides paths to `certfile` and `keyfile` for SSL encryption. Omitting certificate files results in an unsecured connection, which is not recommended for public networks. ```yaml global: remote_modules_server: address: '192.168.1.100' port: 12345 certfile: '/path/to/certfile.cert' # omit for unsecured keyfile: '/path/to/keyfile.key' # omit for unsecured ``` -------------------------------- ### Importing Matplotlib for Plotting - Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/tests/notebooks/mpl_crash.ipynb This snippet imports the `pyplot` module from the `matplotlib` library, commonly aliased as `plt`. This is a prerequisite for creating and displaying plots. It requires the Matplotlib library. ```python import matplotlib.pyplot as plt ``` -------------------------------- ### Processing Remote Data with netobtain (Python) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/remote_modules.md This Python snippet demonstrates the use of `netobtain` from `qudi.util.network` to properly handle Python objects received from remote hardware. When objects are passed 'per reference' over the network, `netobtain` ensures that the client-side logic can correctly process them by converting remote references into local, usable objects. This is crucial for subsequent data manipulation. ```Python from qudi.util.network import netobtain ... data = ...get_data_from_remote_hardware() data = netobatin(data) ``` -------------------------------- ### Using Qudi Module Logging in Python Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/design_concepts/measurement_modules.md This snippet demonstrates how to use the `log` property available to all qudi measurement modules for logging messages at various levels (debug, info, warn, error, critical). It highlights the different behaviors of each log level, such as debug messages being ignored unless in debug mode, and error/critical messages prompting the user unless in headless mode. ```Python .log.debug('debug message') # ignored by logger unless running in debug mode .log.info('info message') .log.warn('warning message') .log.error('error message') # user prompt unless running in headless mode .log.critical('critical message') # user prompt unless running in headless mode and # qudi shutdown attempt ``` -------------------------------- ### Adding New Release Version to Bug Report Template (YAML) Source: https://github.com/ulm-iqo/qudi-core/blob/main/docs/programming_guidelines/creating_releases.md This YAML snippet illustrates how to update the 'bug_report.yml' file by inserting the new release version into the 'version' dropdown options. The new version should be placed just below 'Development' and above the newest previous release version to ensure proper tracking of reported bugs. ```YAML name: Bug Report description: File a new bug report title: "[Bug] " labels: ["bug"] body: - type: markdown attributes: value: | Please fill out this bug report form as thorough as possible! Thank you for taking the time. - type: dropdown id: version attributes: label: Version description: What version of our software are you running? options: - Development - Release vX.Y.Z <---------------------------------------------- HERE!!! - Release v1.1.0 - Release v1.0.1 - Release v1.0.0 validations: required: true - type: textarea ... ```