### Create Installed Code from Config File Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst Example of creating an installed code using a YAML configuration file. ```console $ verdi code create core.code.installed --config code.yml ``` -------------------------------- ### Docker Code Setup Example Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Configuration example for setting up a Quantum ESPRESSO pw.x code to run via Docker. Requires AiiDA v2.3.0 or higher. Ensure the associated computer has 'use_double_quotes = False'. ```yaml label: qe-pw-on-docker computer: localhost engine_command: docker run -i -v $PWD:/workdir:rw -w /workdir {image_name} sh -c image_name: haya4kun/quantum_espresso filepath_executable: pw.x default_calc_job_plugin: quantumespresso.pw use_double_quotes: false wrap_cmdline_params: true ``` -------------------------------- ### Get Computer Setup Options Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst View available options for setting up a computer configuration. Remember to remove the '--' prefix and replace dashes with underscores for keys. ```console $ verdi computer setup --help ``` -------------------------------- ### Install Tools for 2FA Authentication Script Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/ssh.rst Install necessary tools for creating an authentication script for two-factor authentication with SSH. This example shows installation for Debian/Ubuntu and macOS. ```console # On Debian/Ubuntu $ sudo apt-get install oathtool expect # On macOS $ brew install oath-toolkit expect ``` -------------------------------- ### Install and Start RabbitMQ with Homebrew on macOS Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_complete.rst Install RabbitMQ using Homebrew on macOS and start it as a service. Note that the service may need to be manually started after each reboot. ```console brew install rabbitmq brew services start rabbitmq ``` -------------------------------- ### Installed Code YAML Configuration Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst Example YAML configuration for an installed code, including prepend text for module loading. ```yaml --- label: 'qe-6.3-pw' description: 'quantum_espresso v6.3' default_calc_job_plugin: 'quantumespresso.pw' filepath_executable: '/path/to/code/pw.x' computer: 'localhost' prepend_text: | module load module1 module load module2 append_text: ' ' ``` -------------------------------- ### Verdi Command with Old Scheduler Entry Points Source: https://github.com/aiidateam/aiida-core/wiki/AiiDA-2.0-plugin-migration-guide Example of using the `verdi computer setup` command with old, non-prefixed scheduler entry points. This will trigger deprecation warnings. ```bash verdi computer setup -L localhost -T local -S direct ``` -------------------------------- ### Install RabbitMQ Server on Ubuntu Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_complete.rst Install the RabbitMQ server package on Ubuntu using the apt package manager. This typically sets up the server to start automatically on boot. ```console sudo apt install rabbitmq-server ``` -------------------------------- ### Setup Localhost Computer with Verdi Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/tutorials/basic.md Configures a local computer for AiiDA calculations using the 'verdi computer setup' and 'verdi computer configure' commands. Use the '-n' flag for non-interactive setup. ```bash $ verdi computer setup -L tutor -H localhost -T core.local -S core.direct -w `echo $PWD/work` -n $ verdi computer configure core.local tutor --safe-interval 1 -n ``` -------------------------------- ### Setup a new computer instance Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst Use this command to initiate the setup of a new computer in AiiDA. It prompts for necessary details and can be extended with pre- and post-execution scripts. ```console $ verdi computer setup ``` -------------------------------- ### Example pre-execution script commands Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst These bash commands can be added to the 'Pre-execution script' section during computer setup to prepare the environment on the compute resource before a job runs. ```bash export NEWVAR=1 source some/file ``` -------------------------------- ### Example of prepare_for_submission method Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/plugin_codes.rst This is an example of the prepare_for_submission method from a CalcJob. It demonstrates creating input files and returning a CalcInfo object. ```python def prepare_for_submission(self, temporary_directory, input_files): """Create the input files and return the CalcInfo object.""" code_info = CodeInfo() code_info.code_uuid = self.inputs.code.uuid code_info.withmpi = self.inputs.code.withmpi # Command line parameters code_info.cmdline_params = self.inputs.cmdline_params # Input files code_info.local_copy_list = [ (self.inputs.file1, os.path.basename(self.inputs.file1.filename)), (self.inputs.file2, os.path.basename(self.inputs.file2.filename)), ] # Output files code_info.retrieve_list = ['diff.patch'] calc_info = CalcInfo() calc_info.codes_info = [code_info] calc_info.retrieve_list = ['diff.patch'] return calc_info ``` -------------------------------- ### Setup computer with a configuration file Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst Configure a computer by providing a YAML configuration file to the 'verdi computer setup' command. This allows for pre-defined settings and avoids interactive prompts. ```console $ verdi computer setup --config computer.yml ``` -------------------------------- ### Prepend Text Example Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst Example of using prepend text to load modules before code execution. ```bash module load intelmpi ``` -------------------------------- ### Install aiida-core from source Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_complete.rst Clone the aiida-core repository and install it in editable mode using pip. This is recommended for development. ```console git clone https://github.com/aiidateam/aiida-core ``` ```console cd aiida-core pip install -e . ``` -------------------------------- ### Install aiida-core package Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_quick.rst Use pip to install the aiida-core package. This is the first step for any AiiDA installation. ```console pip install aiida-core ``` -------------------------------- ### Public API Import Examples Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/reference/api/public.rst Examples demonstrating how to import resources that are part of the public Python API. ```APIDOC ## Public API Import Examples ### Description This section provides examples of how to correctly import modules and functions that are part of the public Python API of `aiida-core`. Resources imported directly from the top-level `aiida` package or from its second-level sub-packages are considered public and stable. ### Code Examples ```python # Importing from the top-level package (OK) from aiida import load_profile # Importing from a second-level package (OK) from aiida.orm import QueryBuilder # Importing from a deeper level (NOT PUBLIC API - use with caution) # from aiida.tools.importexport import Archive ``` ### Note Resources nested deeper than second-level packages are considered internal and their interface may change without notice between minor releases. Relying on these internal resources can lead to unexpected script breakages. ``` -------------------------------- ### Execute REST API Script Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/internals/rest_api.rst Commands to make the API script executable and run it on a specified port. This is a basic example of how to start the server. ```console $ chmod +x api.py $ ./api.py --port=6000 ``` -------------------------------- ### Install Ubuntu PostgreSQL Development Headers Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/troubleshooting.rst On some Ubuntu versions, installing libpq-dev is necessary for AiiDA to interact with PostgreSQL. ```console $ apt-get install libpq-dev ``` -------------------------------- ### Start the Daemon Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/tutorials/basic.md Use this command to start the AiiDA daemon, enabling it to pick up and run submitted calculations. ```console $ verdi daemon start ``` -------------------------------- ### Example Calculation Output Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/plugin_codes.rst This is an example of the output you might see after a successful calculation run via the 'verdi run launch.py' command, showing a computed diff between files. ```console $ verdi run launch.py Computed diff between files: 2c2 < content1 --- > content2 ``` -------------------------------- ### Verdi Daemon Start Command Structure Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/internals/broker.rst Illustrates the process and thread architecture launched by 'verdi daemon start' with a ZMQ-configured profile. Shows the supervisor, broker process, and worker processes. ```text verdi daemon start └── circus (daemon supervisor) ├── verdi devel zmq-broker ← broker process (1 instance) │ └── ZmqBrokerService │ └── ZmqBrokerServer (single-threaded, zmq.Poller event loop) │ └── PersistentQueue (file-based task durability) │ └── verdi daemon worker ← worker process(es) (1..N instances) └── Runner └── ZmqBroker └── ZmqCommunicator ├── main thread (public API: task_send, rpc_send, ...) └── loop thread (private asyncio loop with ZMQ DEALER socket) ``` -------------------------------- ### Install aiida-core using conda Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_complete.rst Create a conda environment and install aiida-core from the conda-forge channel. ```console conda create -n aiida -c conda-forge aiida-core ``` -------------------------------- ### Install python-gtk2 on Ubuntu Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/troubleshooting.rst Install the python-gtk2 package required for the ASE visualizer on Ubuntu. ```bash $ sudo apt-get install python-gtk2 ``` -------------------------------- ### Install AiiDA with Notebook Support Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/interact.rst Install the 'aiida-core' package with the 'notebook' extra to enable Jupyter notebook integration. ```console pip install aiida-core[notebook] ``` -------------------------------- ### Start Jupyter Notebook Server Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/troubleshooting.rst Start the Jupyter notebook server after setting up the AiiDA kernel. You can then select the AiiDA kernel from the Jupyter interface. ```console $ jupyter notebook ``` -------------------------------- ### Install AiiDA plugin from PyPI Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/plugins_install.rst Use this command to install an AiiDA plugin package if it is available on the Python Package Index (PyPI). ```console $ pip install aiida-plugin-name ``` -------------------------------- ### List Installed Pseudopotential Families Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Lists the pseudopotential families installed in the current AiiDA profile using the verdi CLI. ```console $ verdi data core.upf listfamilies Success: * SSSP_v1.1_precision_PBE [85 pseudos] Success: * SSSP_v1.1_efficiency_PBE [85 pseudos] ``` -------------------------------- ### Singularity Engine Command Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Example of the engine command for setting up a code to run with Singularity. ```bash singularity exec --bind $PWD:$PWD {image_name} ``` -------------------------------- ### Full ICSD Importer Example Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/import_export/dbimporters/icsd.rst A comprehensive example demonstrating the instantiation of the ICSD importer, querying by a list of IDs, and processing the results to extract AiiDA structures. ```python from aiida.tools.dbimporters.plugins.icsd import IcsdDbImporter cif_nr_list = [ "50542", "617290", "35538 ", "165226", "158366" ] importer = IcsdDbImporter(server="http://ICSDSERVER.com/", host= "127.0.0.1") query_results = importer.query(id=cif_nr_list) for result in query_results: print(result.source['db_id']) aiida_structure = result.get_aiida_structure() # do something with the structure ``` -------------------------------- ### Install optional requirements with pip Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_complete.rst Install aiida-core with specific optional requirements by listing them in brackets. For example, to install requirements for atomic tools and documentation: ```console pip install aiida-core[atomic_tools,docs] ``` -------------------------------- ### Run process using launcher shortcuts Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/processes/usage.rst Demonstrates using the `get_node` and `get_pk` attributes of the `run` launcher for convenience. This allows choosing between returning outputs, the node, or the PK with a single import. ```python from aiida.engine import run from aiida.orm.nodes.data.int import Int x = Int(1) y = Int(2) # Using the get_node shortcut process_node, outputs = run.get_node(ArithmeticAddCalculation, x=x, y=y) # Using the get_pk shortcut process_pk, outputs = run.get_pk(ArithmeticAddCalculation, x=x, y=y) ``` -------------------------------- ### Create a ContainerizedCode via CLI Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Set up a ContainerizedCode using the Verdi CLI. This example configures running '/bin/sh' within an Alpine Linux Docker image using Singularity on a computer named 'some-computer'. ```console verdi code create core.code.containerized \ --non-interactive \ --label containerized-code \ --default-calc-job-plugin core.arithmetic.add \ --computer some-computer \ --filepath-executable "/bin/sh" \ --image-name "docker://alpine:3" \ --engine-command "singularity exec --bind $PWD:$PWD {image_name}" ``` -------------------------------- ### Start Jupyter Notebook Server Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/interact.rst Launch the Jupyter notebook server from your terminal. ```console jupyter notebook ``` -------------------------------- ### MPI with Singularity Example Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Illustrates how MPI command line arguments are prepended to the Singularity runtime command when MPI is enabled for a containerized calculation. ```bash "mpirun" "-np" "1" "singularity" "exec" "--bind" "$PWD:$PWD" "ubuntu" '/bin/bash' '--version' '-c' < "aiida.in" > "aiida.out" 2> "aiida.err" ``` -------------------------------- ### Install AiiDA Core Services with Conda Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_complete.rst Create a new Conda environment and install the 'aiida-core.services' package, which includes RabbitMQ support. This package ensures RabbitMQ is installed but not automatically started. ```console conda create -n aiida -c conda-forge aiida-core.services ``` -------------------------------- ### Sarus Engine Command Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Example of the engine command for setting up a code to run with Sarus. ```bash sarus run --mount=src=$PWD,dst=/workdir,type=bind --workdir=/workdir {image_name} ``` -------------------------------- ### Install AiiDA plugin from source code Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/plugins_install.rst Install an AiiDA plugin package from its source code, for example, when cloning from a Git repository. ```console $ git clone https://github.com/aiidateam/aiida-diff $ cd aiida-diff $ pip install . ``` -------------------------------- ### Setup core.sqlite_dos storage Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/storage.rst Use this command to set up a profile with SQLite and disk-objectstore storage. This is suitable for tests and demos as it's easy to set up and requires no running services. ```console verdi profile setup core.sqlite_dos -n --profile-name --email ``` -------------------------------- ### Setup and Configure Local Computer (IPython) Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/tutorials/basic.md An IPython version of the commands to set up and configure a local computer for AiiDA. It uses '%verdi' magic commands for interactive execution. ```ipython3 %verdi computer setup -L tutor -H localhost -T core.local -S core.direct -w /tmp -n %verdi computer configure core.local tutor --safe-interval 0 -n %verdi code create core.code.installed --label add --computer=tutor --default-calc-job-plugin core.arithmetic.add --filepath-executable=/bin/bash -n ``` -------------------------------- ### MySQL Database Credentials Example Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/import_export/dbimporters/icsd.rst Example of MySQL database connection parameters. Default values may work with a standard ICSD intranet installation. ```python user = "dba", pass_wd = "sql", db = "icsd", port = 3306 ``` -------------------------------- ### Verdi Quicksetup Command (Deprecated) Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/reference/command_line.rst The `verdi quicksetup` command is a deprecated method for setting up a new AiiDA profile in an automated fashion. For a fully automated alternative, users are advised to use `verdi presto --use-postgres`. ```console Usage: [OPTIONS] Setup a new profile in a fully automated fashion. (DEPRECATED: This command is deprecated. For a fully automated alternative, use `verdi presto --use-postgres` ``` -------------------------------- ### Curl GET Request to REST API Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/internals/rest_api.rst Example using curl to make a GET request to a specific endpoint of the REST API. This demonstrates how to fetch data from the API. ```bash curl http://127.0.0.2:6000/api/v4/new-endpoint/ -X GET ``` -------------------------------- ### Get a List of Users by First Name Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/reference/rest_api.rst Retrieves a list of User objects whose first name starts with a specified string, case-insensitively. ```APIDOC ## GET /api/v4/users/?first_name=ilike="{prefix}%" ### Description Returns a list of User objects whose first name starts with the specified prefix, ignoring case. ### Method GET ### Endpoint /api/v4/users/ ### Query Parameters - **first_name** (string) - Required - A pattern to match the beginning of the first name (e.g., 'aii%'). The `ilike` operator performs a case-insensitive pattern match. ### Response #### Success Response (200) - **data.users** (array) - A list of user objects matching the criteria. - **id** (null) - This field is null for this endpoint. - **method** (string) - The HTTP method used. - **path** (string) - The API path. - **query_string** (string) - The query string parameters. - **resource_type** (string) - The type of resource. - **url** (string) - The full URL of the request. - **url_root** (string) - The root URL of the API. ### Response Example ```json { "data": { "users": [ { "first_name": "AiiDA", "id": 1, "institution": "", "last_name": "Daemon" } ] }, "id": null, "method": "GET", "path": "/api/v4/users/", "query_string": "first_name=ilike=\"aii%\"", "resource_type": "users", "url": "http://localhost:5000/api/v4/users/?first_name=ilike=\"aii%\"", "url_root": "http://localhost:5000/" } ``` ``` -------------------------------- ### Verdi Command with New Scheduler Entry Points Source: https://github.com/aiidateam/aiida-core/wiki/AiiDA-2.0-plugin-migration-guide Illustrates the updated `verdi computer setup` command using the new, prefixed scheduler entry points ('core.local', 'core.direct') for AiiDA v2.0. ```bash verdi computer setup -L localhost -T core.local -S core.direct ``` -------------------------------- ### Unstash Files Example Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/calculations/usage.rst Demonstrates how to initiate an unstashing operation using the `core.unstash` calculation. This requires loading the stashed data node from a previous stash operation. ```python from aiida.common.datastructures import UnstashTargetMode from aiida.orm import load_node, load_computer UnstashCalculation = CalculationFactory('core.unstash') # Get the stashed data node from a previous stash operation ``` -------------------------------- ### Bash Command Line Example Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/plugin_codes.rst Illustrates how command-line options, including those with regular expression arguments, can be represented. ```bash diff --ignore-case --ignore-matching-lines='.*ABC.*' ``` -------------------------------- ### Set up an AiiDA profile Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_quick.rst Run the 'verdi presto' command to quickly set up a new AiiDA profile. This command configures a basic profile suitable for getting started. ```console verdi presto ``` -------------------------------- ### Setup AiiDA IPython Kernel Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/troubleshooting.rst Install the IPython kernel and set up a custom kernel for AiiDA within your virtual environment. This allows Jupyter to recognize and use the AiiDA environment. ```console $ pip install ipykernel $ python -m ipykernel install --user --name= ``` -------------------------------- ### Create BandsData Instance Manually Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Import BandsData using DataFactory and create an instance. This is the starting point for working with the BandsData type. ```python from aiida.plugins import DataFactory BandsData = DataFactory('core.array.bands') bands_data = BandsData() ``` -------------------------------- ### Create and Get Content of TextFileData Node Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Shows how to instantiate the 'TextFileData' custom data type and retrieve the content of the stored file. ```python node = TextFileData(filepath='/some/absolute/path/to/file.txt') node.get_content() # This will return the content of the file ``` -------------------------------- ### Create a PortableCode instance Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Instantiate a PortableCode object, specifying the label, the local path to the code directory, and the name of the executable file within that directory. This is used for executables not installed on the target machine but available locally. ```python from pathlib import Path from aiida.orm import PortableCode code = PortableCode( label='some-label', filepath_files=Path('/some/path/code'), filepath_executable='executable.exe' ) ``` -------------------------------- ### Create a ContainerizedCode via API Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Instantiate a ContainerizedCode object using the AiiDA API. This example sets up running '/bin/sh' within a Docker image via Singularity, linking it to a specific computer. ```python from aiida.orm import ContainerizedCode, load_computer code = ContainerizedCode( computer=load_computer('some-computer') filepath_executable='/bin/sh' image_name='docker://alpine:3', engine_command='singularity exec --bind $PWD:$PWD {image_name}' ).store() ``` -------------------------------- ### Query Nodes with Pagination and Ordering Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/reference/rest_api.rst Retrieve a list of Node objects with specified pagination and ordering. This example fetches two nodes starting from the 9th row, ordered by ID in descending order. ```http http://localhost:5000/api/v4/nodes?limit=2&offset=8&orderby=-id ``` ```json { "data": { "nodes ": [ { "ctime": "Sun, 21 Jul 2019 11:45:52 GMT", "full_type": "data.core.dict.Dict.|", "id": 102618, "label": "", "mtime": "Sun, 21 Jul 2019 11:45:52 GMT", "node_type": "data.core.dict.Dict.", "process_type": null, "user_id": 4, "uuid": "a43596fe-3d95-4d9b-b34a-acabc21d7a1e" }, { "ctime": "Sun, 21 Jul 2019 18:18:26 GMT", "full_type": "data.core.remote.RemoteData.|", "id": 102617, "label": "", "mtime": "Sun, 21 Jul 2019 18:18:26 GMT", "node_type": "data.core.remote.RemoteData.", "process_type": null, "user_id": 4, "uuid": "12f95e1c-69df-4a4b-9b06-8e69072e6108" } ] }, "id": null, "method": "GET", "path": "/api/v4/nodes", "query_string": "limit=2&offset=8&orderby=-id", "resource_type": "nodes", "url": "http://localhost:5000/api/v4/nodes?limit=2&offset=8&orderby=-id", "url_root": "http://localhost:5000/" } ``` -------------------------------- ### Set up Profile with PostgreSQL Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_quick.rst Run this command to set up a new profile that uses a PostgreSQL database instead of SQLite. It attempts to automatically configure the database connection. ```bash verdi presto --use-postgres ``` -------------------------------- ### Submit Containerized Code Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Example of submitting a containerized code using AiiDA's engine. Ensure the code is loaded correctly before building and submitting. ```python from aiida.engine import submit from aiida.orm import load_code code = load_code('containerized-code') builder = code.get_builder() # Define the rest of the inputs submit(builder) ``` -------------------------------- ### Open SinglefileData as a File-Like Handle Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Use the open method to get a file-like handle to the SinglefileData object in the repository. This allows reading content as a stream, which is efficient for large files. Files are opened in binary mode by default to ensure identical copying. ```ipython In [4]: import shutil with single_file.open(mode='rb') as source: with open('copy.txt', mode='wb') as target: shutil.copyfileobj(source, target) ``` -------------------------------- ### Usage example for 'archive create' command Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/cli.rst Illustrates the usage of the 'verdi archive create' command, showing how to specify multiple codes, computers, groups, and nodes using multi-value options. ```bash Usage: verdi archive create [OPTIONS] [--] OUTPUT_FILE Export various entities, such as Codes, Computers, Groups and Nodes, to an archive file for backup or sharing purposes. Options: -X, --codes CODE... one or multiple codes identified by their ID, UUID or label -Y, --computers COMPUTER... one or multiple computers identified by their ID, UUID or label -G, --groups GROUP... one or multiple groups identified by their ID, UUID or name -N, --nodes NODE... one or multiple nodes identified by their ID or UUID ... ``` -------------------------------- ### Test a calculation using an installed code Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/plugins_develop.rst Example test function demonstrating how to use AiiDA's fixtures to set up a code node and run a calculation. The `aiida_code_installed` fixture helps in creating a code entry for testing. ```python def test_calculation(aiida_code_installed): """Test running a calculation using a ``CalcJob`` plugin.""" from aiida.engine import run code = aiida_code_installed(default_calc_job_plugin='core.arithmetic.add', filepath_executable='/bin/bash') builder = code.get_builder() builder.x = orm.Int(1) builder.y = orm.Int(2) results, node = run.get_node(builder) assert node.is_finished_ok assert results['sum'] == 3 ``` -------------------------------- ### List Available Calculation Plugins Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/tricks_real_world_runs.rst Run this command in a standard terminal to list all available calculation plugins for a specific entry point, like 'aiida.calculations quantumespresso.pw'. This helps in identifying the correct plugin names. ```bash verdi plugin list aiida.calculations quantumespresso.pw ``` -------------------------------- ### Create an InstalledCode Instance Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Instantiate an InstalledCode for executables pre-installed on a remote computer. Specify the label, computer, and the executable's filepath. ```python from aiida.orm import InstalledCode code = InstalledCode( label='some-label', computer=load_computer('localhost'), filepath_executable='/usr/bin/bash' ) ``` -------------------------------- ### Install AiiDA REST Component Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/reference/rest_api.rst Install the necessary component for the AiiDA REST API during AiiDA installation. This command ensures all dependencies for the REST service are included. ```console $ pip install aiida-core[rest] ``` -------------------------------- ### Export StructureData to XSF format using verdi CLI Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Exports a StructureData node to the XSF format using the verdi command-line interface. The output is redirected to a file, for example, 'Li.xsf'. ```console $ verdi data core.structure export --format xsf > Li.xsf ``` -------------------------------- ### Start RabbitMQ Server Detached Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/guide_complete.rst Manually start the RabbitMQ server in detached mode. This command needs to be run after each machine reboot if RabbitMQ is not configured to start automatically. ```console rabbitmq-server -detached ``` -------------------------------- ### Get Database Size Source: https://github.com/aiidateam/aiida-core/wiki/Modifying-the-database-schema Query the database to get its human-readable size. ```sql SELECT pg_size_pretty(pg_database_size('aiida_clone')); ``` -------------------------------- ### Accessing Specific Object as Local Filesystem Path Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Use 'as_path' with an object name to get a local filesystem path pointing to a specific file or directory within the repository. This is useful for libraries like numpy.loadtxt that require a filepath. ```ipython In [11]: with folder.as_path('some_data_file.dat') as filepath: numpy.loadtxt(filepath) ``` -------------------------------- ### Example computer configuration in YAML Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/run_codes.rst A sample YAML file for configuring a computer in AiiDA. It specifies connection details, scheduler, working directory, and pre-execution commands. ```yaml --- label: "localhost" hostname: "localhost" transport: "core.local" scheduler: "core.direct" work_dir: "/home/max/.aiida_run" mpirun_command: "mpirun -np {tot_num_mpiprocs}" mpiprocs_per_machine: "2" prepend_text: | module load mymodule export NEWVAR=1 ``` -------------------------------- ### Get Pymatgen Structure from StructureData Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Retrieves the structure in the Pymatgen Structure format from a StructureData node. This allows for seamless integration with Pymatgen's analysis and manipulation tools. ```ipython In [9]: structure.get_pymatgen() Out[9]: Structure Summary Lattice abc : 3.5 3.5 3.5 angles : 90.0 90.0 90.0 volume : 42.875 A : 3.5 0.0 0.0 B : 0.0 3.5 0.0 C : 0.0 0.0 3.5 PeriodicSite: Li (0.0000, 0.0000, 0.0000) [0.0000, 0.0000, 0.0000] PeriodicSite: Li (1.5000, 1.5000, 1.5000) [0.4286, 0.4286, 0.4286] ``` -------------------------------- ### Get Database Node Count Source: https://github.com/aiidateam/aiida-core/wiki/Modifying-the-database-schema Query the database to get the total count of nodes. ```sql SELECT count(*) FROM db_dbnode; ``` -------------------------------- ### Setup AiiDA Profile Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/reference/command_line.rst Initializes and sets up a new AiiDA profile. Requires detailed configuration for database and message broker connections. ```console verdi profile setup core.psql_dos --profile my_profile --email test@example.com --first-name John --last-name Doe --institution "Example University" --db-host localhost --db-port 5432 --db-name aiida_db --db-username aiida_user --db-password secret --broker-host rabbitmq.example.com --broker-port 5672 --broker-virtual-host /aiida ``` -------------------------------- ### Getting Object Content from FolderData Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Retrieve the content of a specific file stored within the FolderData node using its path. ```ipython In [5]: folder.get_object_content('file1.txt') Out[5]: 'File 1 content\n' ``` -------------------------------- ### Get Internal Storage Names vs. User-Provided Names Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst The get_arraynames method returns internal storage names, while a list comprehension with get_y extracts user-provided names. Use get_y to access the names as they were defined by the user. ```ipython In [12]: xy.get_arraynames() # Internal storage names Out[12]: ['x_array', 'y_array_0'] In [13]: [name for name, _, _ in xy.get_y()] # User-provided names Out[13]: ['Volume Expansion'] ``` -------------------------------- ### Get Content of a SinglefileData Object Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst The get_content method retrieves the entire content of a SinglefileData object as a string. This is suitable for smaller files where loading the entire content into memory is acceptable. ```ipython In [3]: single_file.get_content() Out[3]: 'The file content' ``` -------------------------------- ### Launch Process with Dictionary Input Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/processes/usage.rst Demonstrates launching an AiiDA process using a dictionary for inputs. Ensure all required inputs are provided. ```python from aiida.engine import submit from aiida.orm import Code, Data # Load the code and data nodes code = Code.get_code_from_uuid('...') data = Data.get_node_from_uuid('...') # Define the inputs as a dictionary inputs = { 'code': code, 'parameters': {'value': 10}, 'input_data': data, 'metadata': { 'label': 'my_process_label', 'description': 'This is a sample process', } } # Submit the process future = submit(inputs) ``` -------------------------------- ### Get ASE Structure from StructureData Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Retrieves the structure in the Atomic Simulation Environment (ASE) Atoms format from a StructureData node. This is useful for leveraging ASE's extensive functionalities. ```ipython In [8]: structure.get_ase() Out[8]: Atoms(symbols='Li2', pbc=True, cell=[3.5, 3.5, 3.5], masses=...) ``` -------------------------------- ### Override Constructor to Accept Custom Value Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst This example demonstrates how to override the constructor of a custom Data subclass to accept and process a specific keyword argument, 'value'. The base class constructor must be called, and the custom argument must be removed from kwargs before the call. ```python from aiida.orm import Data class NewData(Data): """A new data type that wraps a single value.""" def __init__(self, **kwargs): value = kwargs.pop('value') super().__init__(**kwargs) self.base.attributes.set('value', value) ``` -------------------------------- ### Define Custom Data Type for Text File Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/data_types.rst Example of a custom Aiida data type 'TextFileData' that wraps a single text file, storing it in the repository and its filename in attributes. ```python import os from aiida.orm import Data class TextFileData(Data): """Data class that can be used to wrap a single text file by storing it in its file repository.""" def __init__(self, filepath, **kwargs): """Construct a new instance and set the contents to that of the file. :param file: an absolute filepath of the file to wrap """ super().__init__(**kwargs) filename = os.path.basename(filepath) # Get the filename from the absolute path self.base.repository.put_object_from_file(filepath, filename) # Store the file in the repository under the given filename self.base.attributes.set('filename', filename) # Store in the attributes what the filename is def get_content(self): """Return the content of the single file stored for this data node. :return: the content of the file as a string """ filename = self.base.attributes.get('filename') return self.get_object_content(filename) ``` -------------------------------- ### Create a file in the sandbox folder Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/plugin_codes.rst This snippet shows how to create a new file on the fly within the sandbox folder provided by the prepare_for_submission method. Files created here will be transferred to the compute resource. ```python with folder.open("filename", 'w') as handle: handle.write("file content") ``` -------------------------------- ### Setup Unconfigured Localhost with SSH Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/plugins.rst Create a localhost computer with SSH transport without configuring it. Useful when the configuration step is not needed for the test. ```python def test(aiida_computer_ssh): localhost = aiida_computer_ssh(configure=False) assert not localhost.is_configured ``` -------------------------------- ### Setup core.sqlite_zip Profile Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/topics/storage.rst Use this command to set up a profile with the core.sqlite_zip storage plugin, which creates an export archive. Replace and with your desired values. ```console verdi profile setup core.sqlite_zip -n --profile-name --filepath ``` -------------------------------- ### Start RabbitMQ Server in Non-Detached Mode Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/installation/troubleshooting.rst If RabbitMQ is not connecting, try starting it in the foreground to observe any startup errors. ```console $ rabbitmq-server ``` -------------------------------- ### Define Workchain Inputs in Setup Source: https://github.com/aiidateam/aiida-core/blob/main/docs/source/howto/workchains_restart.rst Reuses the `setup` method of `BaseRestartWorkChain` to define the inputs dictionary `self.ctx.inputs` for the subprocess. ```python def setup(self): """Call the `setup` of the `BaseRestartWorkChain` and then create the inputs dictionary in `self.ctx.inputs`. This `self.ctx.inputs` dictionary will be used by the `BaseRestartWorkChain` to submit the process in the internal loop. """ super().setup() self.ctx.inputs = {'x': self.inputs.x, 'y': self.inputs.y, 'code': self.inputs.code} ```