### Colima Setup for Mac Users Source: https://github.com/qiskit/qiskit-serverless/blob/main/CONTRIBUTING.md Instructions for Mac users to install and start Colima, a tool for running Docker and Kubernetes container environments. This includes commands to install Colima and Docker, start Colima with specified resources, and check its status. ```bash brew install colima brew install docker colima start --cpu 4 --memory 8 ``` ```bash colima status ``` ```bash nerdctl ps -a ``` ```bash nerdctl images ``` -------------------------------- ### Check Tool Installations Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/cloud.rst Verifies the installation of Docker and Helm by displaying their version information. This is a prerequisite for deploying Qiskit Serverless. ```bash $ docker --version $ > Docker version X, build Y $ $ helm version $ > version.BuildInfo{Version:"X", GitCommit:"Y", GitTreeState:"Z", GoVersion:"T"} ``` -------------------------------- ### Run Docker Compose Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst Command to start the Qiskit Serverless environment using Docker Compose. ```bash docker-compose up ``` -------------------------------- ### Install Qiskit Serverless Client Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/client_configuration.rst Installs the Qiskit Serverless client library using pip. This is the first step to setting up the client for communication with the server. ```bash pip install qiskit-serverless ``` -------------------------------- ### Install Qiskit Serverless Client Source: https://github.com/qiskit/qiskit-serverless/blob/main/client/README.md Installs the latest release of the Qiskit Serverless client using pip. Also provides instructions for installing from source, including development requirements. ```shell pip install qiskit-serverless ``` ```shell pip install -r requirements.txt -r requirements-dev.txt pip install -e . ``` -------------------------------- ### Install Released Version with Helm Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/cloud.rst Installs a released version of Qiskit Serverless onto a Kubernetes cluster using Helm. Replace with your target namespace and vx.y.z with the release version. ```bash $ helm -n install qiskit-serverless --create-namespace https://github.com/Qiskit/qiskit-serverless/releases/download/vx.y.z/qiskit-serverless-x.y.z.tgz ``` -------------------------------- ### Initiate Local Test Environment with Docker Compose Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/local.rst Starts the local test infrastructure using Docker Compose. The `--profile ` argument can be used to include specific profiles, such as `full` for all core services including logging and monitoring. ```bash $ docker compose [--profile ] up ``` -------------------------------- ### Clone Qiskit Serverless Repository Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/local.rst Clones the Qiskit Serverless repository from GitHub to your local machine. This command requires Git to be installed and configured. ```bash cd /path/to/workspace/ git clone git@github.com:Qiskit/qiskit-serverless.git ``` -------------------------------- ### Install qiskit-serverless Source: https://github.com/qiskit/qiskit-serverless/blob/main/README.md Installs the qiskit-serverless package using pip. It is recommended to use a virtual environment. ```shell pip install qiskit-serverless ``` -------------------------------- ### Install qiskit_serverless via pip Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/installation/index.rst Installs or upgrades the pip package manager and then installs the qiskit_serverless package. This is the primary method for setting up the library. ```bash pip install --upgrade pip pip install qiskit_serverless ``` -------------------------------- ### Local Development with Docker Compose Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/cloud.rst Deploys Qiskit Serverless infrastructure locally using Docker Compose. This command starts the necessary services and makes the Ray dashboard accessible at http://localhost:8265. ```bash $ docker compose up ``` -------------------------------- ### Deploy Kind Kubernetes Cluster Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/local.rst Initializes a local Kubernetes cluster using Kind. This command is part of the testing setup and simplifies the process of creating a Kubernetes environment locally. ```bash $ tox -e cluster-deploy ``` -------------------------------- ### Install Qiskit Serverless Observability with Helm Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/cloud.rst This command installs the Qiskit Serverless observability component using Helm. Replace `` with your desired Kubernetes namespace and `x.y.z` with the specific release version (e.g., 0.25.3). ```shell $ helm -n install qs-observability https://github.com/Qiskit/qiskit-serverless/releases/download/vx.y.z/qs-observability-x.y.z.tgz ``` -------------------------------- ### Local Cluster Deployment and Image Loading Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst Commands for deploying a local Kubernetes cluster using Kind and loading the custom Docker image into it. ```bash tox -e cluster-deploy kind load docker-image test-local-provider-function:latest ``` -------------------------------- ### Qiskit Runtime Program Example Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/migration/migration_from_qiskit_runtime_programs.ipynb An example of a Qiskit Runtime Program that generates random circuits and submits them for execution. It includes a `main` function that takes `backend`, `user_messenger`, and `**kwargs`. ```python """A sample runtime program that submits random circuits for user-specified iterations.""" import random from qiskit import transpile from qiskit.circuit.random import random_circuit def prepare_circuits(backend): circuit = random_circuit( num_qubits=5, depth=4, measure=True, seed=random.randint(0, 1000) ) return transpile(circuit, backend) def main(backend, user_messenger, **kwargs): """Main entry point of the program. Args: backend: Backend to submit the circuits to. user_messenger: Used to communicate with the program consumer. kwargs: User inputs. """ iterations = kwargs.pop("iterations", 5) for it in range(iterations): qc = prepare_circuits(backend) result = backend.run(qc).result() user_messenger.publish({"iteration": it, "counts": result.get_counts()}) return "Hello, World!" ``` -------------------------------- ### Dockerfile for Custom Image Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst This Dockerfile specifies the base image and dependencies required for the custom Qiskit Serverless function. It installs necessary Python packages and copies the function code into the image. ```dockerfile FROM icr.io/quantum-public/qiskit-serverless/ray-node:0.25.3 # install all necessary dependencies for your custom image # copy our function implementation in `/runner/runner.py` of the docker image USER 0 RUN pip install qiskit_aer WORKDIR /runner COPY ./runner.py /runner WORKDIR / USER 1000 ``` -------------------------------- ### Configure Colima for Increased Resources Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/local.rst Starts the Colima container runtime with specified resources (CPU, memory, disk). This is recommended for users on MacOS with ARM processors to ensure sufficient resources for Docker operations. ```shell $ colima start --cpu 4 --memory 8 --disk 100 ``` -------------------------------- ### Install qiskit-serverless Source: https://github.com/qiskit/qiskit-serverless/blob/main/README.md Installs the qiskit-serverless Python package using pip. It is recommended to perform this installation within a virtual environment for better dependency management. ```shell pip install qiskit-serverless ``` -------------------------------- ### Development Environment Setup with Docker Compose Source: https://github.com/qiskit/qiskit-serverless/blob/main/CONTRIBUTING.md Commands to build and run the Qiskit Serverless development environment using Docker Compose. This includes building all images or specific components and then bringing the services up. ```docker compose docker compose -f docker-compose-dev.yaml build ``` ```docker compose docker compose -f docker-compose-dev.yaml up ``` ```docker compose docker compose -f docker-compose-dev.yaml build gateway ``` -------------------------------- ### Activate Python Virtual Environment Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/local.rst Activates the previously created Python virtual environment. This ensures that subsequent commands use the Python interpreter and packages installed within this environment. ```bash source /path/to/virtual/environment/bin/activate ``` -------------------------------- ### Install Qiskit Serverless (Default Values) Source: https://github.com/qiskit/qiskit-serverless/blob/main/charts/qiskit-serverless/README.md Installs the Qiskit Serverless Helm chart using the default values file in the 'qiskit-serverless' namespace. Creates the namespace if it does not exist. ```shell helm -n qiskit-serverless install qiskit-serverless --create-namespace . ``` -------------------------------- ### Initialize ServerlessClient Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/02_arguments_and_results.ipynb Initializes the ServerlessClient with optional gateway token and host, defaulting to environment variables or local defaults. Includes a note about local infrastructure setup. ```python from qiskit_serverless import ServerlessClient import os client = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), # If you are using the kubernetes approach the URL must be http://localhost ) client ``` -------------------------------- ### Run Qiskit Serverless Infrastructure with Docker Compose Source: https://github.com/qiskit/qiskit-serverless/blob/main/README.md Starts the Qiskit Serverless infrastructure using Docker Compose. This command assumes you are in the cloned repository directory. ```shell cd qiskit-serverless/ sudo docker compose up ``` -------------------------------- ### Install Qiskit Serverless (Custom Values) Source: https://github.com/qiskit/qiskit-serverless/blob/main/charts/qiskit-serverless/README.md Installs the Qiskit Serverless Helm chart using a specified custom values file. The namespace 'qiskit-serverless' is created if it doesn't exist. ```shell helm -n qiskit-serverless install qiskit-serverless -f --create-namespace . ``` -------------------------------- ### Build Container Image Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst Command to build the Docker image using the Dockerfile. This creates a tagged image that can be used by Qiskit Serverless. ```bash docker build -t test-local-provider-function . ``` -------------------------------- ### List Available Functions (list.py) Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst Python script to list all available Qiskit Serverless functions. It connects to the ServerlessClient and iterates through the functions, printing their titles and descriptions. ```python import os from qiskit_serverless import ServerlessClient serverless = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), # If you are using the kubernetes approach the URL must be http://localhost ) my_functions = serverless.list() for function in my_functions: print("Name: " + function.title) print(function.description) print() ``` -------------------------------- ### Run Qiskit Serverless Infrastructure with Jupyter Profile Source: https://github.com/qiskit/qiskit-serverless/blob/main/README.md Starts the Qiskit Serverless infrastructure with the Jupyter profile enabled using Docker Compose. This command assumes you are in the cloned repository directory. ```shell cd qiskit-serverless/ sudo docker compose --profile jupyter up ``` -------------------------------- ### Development Deployment with Docker Compose Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/cloud.rst Deploys Qiskit Serverless using a specific Docker Compose file for development environments. This allows for using the 'main' branch configuration. ```bash $ docker compose -f docker-compose-dev.yaml up ``` -------------------------------- ### Run Local Development Environment Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/deploying_custom_image_function.rst This command starts the local development environment using Docker Compose, which now includes the custom Docker image. This allows for testing the custom Qiskit Serverless function locally. ```bash docker-compose up ``` -------------------------------- ### Execute Function (usage.py) Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst Python script demonstrating how to execute a Qiskit Serverless function. It sets up a quantum circuit and observable, connects to the ServerlessClient, retrieves a specific function, and prepares to execute it. ```python import os from qiskit_serverless import ServerlessClient from qiskit import QuantumCircuit from qiskit.circuit.random import random_circuit from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService # set this True for the real Quantum system use use_service=False service = None if use_service: service = QiskitRuntimeService( token=os.environ.get("YOUR_TOKEN", ""), channel='ibm_quantum', instance='ibm-q/open/main', verify=False, ) circuit = random_circuit(2, 2, seed=1234) observable = SparsePauliOp("IY") serverless = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), # If you are using the kubernetes approach the URL must be http://localhost ) my_function = serverless.get("custom-image-function") ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/local.rst Creates a new Python virtual environment for isolating project dependencies. It's recommended to use Python's built-in `venv` module for this purpose. ```bash python3 -m venv /path/to/virtual/environment ``` -------------------------------- ### Kubernetes Local Cluster Setup Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/deploying_custom_image_function.rst These commands are used when deploying to a Kubernetes cluster. `tox -e cluster-deploy` is used to deploy the cluster, and `kind load docker-image test-local-provider-function:latest` loads the custom Docker image into the Kind cluster for use. ```bash tox -e cluster-deploy kind load docker-image test-local-provider-function:latest ``` -------------------------------- ### Configure Colima for Qiskit Serverless Source: https://github.com/qiskit/qiskit-serverless/blob/main/README.md This snippet shows how to start the Colima container runtime with increased resources (CPU, memory, disk) to accommodate the demands of distributed computing for Qiskit Serverless. It's recommended for users on MacOS with ARM processors. ```shell colima start --cpu 4 --memory 8 --disk 100 ``` -------------------------------- ### VQE Execution Logic Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/examples/01_vqe.ipynb This snippet outlines the core logic for executing the VQE algorithm. It handles conditional setup based on whether an IBM Quantum Runtime service is available, creating an Estimator instance accordingly, and then calling the `run_vqe` function. The results are then saved. ```python import ... def run_vqe( initial_parameters, ansatz, operator, estimator, method ): ... arguments = get_arguments() service = arguments.get("service") ansatz = arguments.get("ansatz") operator = arguments.get("operator") initial_parameters = arguments.get("initial_parameters") optimizer = ... if service is not None: # if we have service we need to open a session and create estimator backend = arguments.get("backend", "ibmq_qasm_simulator") with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) # qiskit_ibm_runtime.Estimator vqe_result = run_vqe( estimator=estimator, ...) else: # if we do not have a service let's use standart local estimator estimator = QiskitEstimator() # qiskit.primitives.Estimator vqe_result, callback_dict = run_vqe( initial_parameters=initial_parameters, ansatz=ansatz, operator=operator, estimator=estimator, method=method ) save_result({ "optimal_point": vqe_result.x.tolist(), "optimal_value": vqe_result.fun, "optimizer_evals": vqe_result.nfev, "optimizer_history": callback_dict.get("cost_history", []), "optimizer_time": callback_dict.get("_total_time", 0) }) ``` -------------------------------- ### Dockerfile for Custom Image Function Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/deploying_custom_image_function.rst This Dockerfile specifies how to build a custom image for Qiskit Serverless. It extends a base Ray Node image, installs dependencies, copies the `runner.py` script into the image, and sets the working directory and user for execution. ```dockerfile FROM icr.io/quantum-public/qiskit-serverless/ray-node:0.25.3 # install all necessary dependencies for your custom image # copy our function implementation in `/runner/runner.py` of the docker image USER 0 WORKDIR /runner COPY ./runner.py /runner WORKDIR / USER 1000 ``` -------------------------------- ### Instantiate QiskitPattern Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/migration/migration_from_qiskit_runtime_programs.ipynb Demonstrates how to instantiate the `QiskitPattern` class, specifying the title, entrypoint file, and working directory for the pattern. ```python from qiskit_serverless import QiskitPattern pattern = QiskitPattern( title="migrated-pattern", entrypoint="migrated_pattern.py", working_dir="./src/" ) ``` -------------------------------- ### Run a Qiskit Function with Serverless Client Source: https://github.com/qiskit/qiskit-serverless/blob/main/client/README.md Shows how to use the `ServerlessClient` to upload a Qiskit function and run it. It covers creating a client instance, defining a `QiskitFunction` with an entrypoint and working directory, uploading the function, preparing input data (a list of random quantum circuits), and initiating the job execution. ```python from qiskit_serverless import ServerlessClient, QiskitFunction from qiskit.circuit.random import random_circuit client = ServerlessClient( token="", host="", ) # create function function = QiskitFunction( title="Quickstart", entrypoint="program.py", working_dir="./src" ) client.upload(function) # create inputs to our program circuits = [] for _ in range(3): circuit = random_circuit(3, 2) circuit.measure_all() circuits.append(circuit) # run program my_function = client.get("Quickstart") job = my_function.run(circuits=circuits) ``` -------------------------------- ### QAOA Pattern Implementation Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/examples/02_qaoa.ipynb This snippet outlines the core logic for the QAOA pattern, including argument parsing, defining the `run_qaoa` function, selecting the appropriate sampler (runtime service or local), and saving the results. It demonstrates how to integrate with Qiskit Runtime Service sessions or use standard Qiskit samplers. ```python # qaoa.py import ... def run_qaoa( ansatz: QuantumCircuit, estimator: BaseEstimator, operator: PauliSumOp, initial_point: np.array, method: str ): return minimize(cost_func, initial_point, args=(ansatz, operator, estimator), method=method) arguments = get_arguments() service = arguments.get("service") operator = arguments.get("operator") initial_point = arguments.get("initial_point") ansatz = arguments.get("ansatz", 1) ... if service is not None: # if we have service we need to open a session and create sampler service = arguments.get("service") backend = arguments.get("backend", "ibmq_qasm_simulator") with Session(service=service, backend=backend) as session: estimator = Estimator(session=session, options=options) else: # if we do not have a service let's use standart local sampler estimator = QiskitEstimator() result = run_qaoa(ansatz, estimator, operator, initial_point, "COBYLA") save_result({ "optimal_point": result.x.tolist(), "optimal_value": result.fun }) ``` -------------------------------- ### Input Arguments Configuration Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/examples/02_qaoa.ipynb This snippet configures the input arguments for the QAOA pattern. It includes options for using QiskitRuntimeService and specifies the backend, operator, ansatz, and initial point. The `USE_RUNTIME_SERVICE` flag controls whether to connect to the IBM Quantum service. ```python USE_RUNTIME_SERVICE = False service = None if USE_RUNTIME_SERVICE: service = QiskitRuntimeService( channel='ibm_quantum', instance='ibm-q/open/main', token='' ) backend = None input_arguments = { "initial_point": None, "ansatz": ansatz, "operator": operator, "service": service, "backend": backend, } input_arguments ``` -------------------------------- ### Monitor Job Status and Retrieve Results Source: https://github.com/qiskit/qiskit-serverless/blob/main/client/README.md Provides examples for monitoring the status of a submitted job and retrieving its results. It shows how to check the job status using `job.status()` and retrieve logs using `job.logs()`. Finally, it demonstrates how to get the computed results from the job using `job.result()`. ```python job.status() # 'DONE' # or get logs job.logs() job.result() # {'quasi_dists': [ # {'101': 902, '011': 66, '110': 2, '111': 37, '100': 17}, # {'100': 626, '101': 267, '001': 49, '000': 82}, # {'010': 145, '100': 126, '011': 127, '001': 89, '110': 173, '111': 166, '000': 94, '101': 104} # ]} ``` -------------------------------- ### Initialize ServerlessProvider Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/migration/migration_from_qiskit_runtime_programs.ipynb Shows how to initialize the `ServerlessProvider` with authentication token and host address, retrieving them from environment variables or using default values. ```python from qiskit_serverless import ServerlessProvider import os serverless = ServerlessProvider( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), ) serverless ``` -------------------------------- ### Run Qiskit Serverless Job and Get Results Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst This snippet shows how to execute a Qiskit function using the serverless backend. It demonstrates passing necessary parameters like the service, circuit, and observable to the run method. It also shows how to retrieve the job's result and logs after execution. ```python job = my_function.run(service=service, circuit=circuit, observable=observable) print(job.result()) print(job.logs()) ``` -------------------------------- ### Initialize ServerlessClient Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/experimental/file_download.ipynb Initializes the ServerlessClient with optional token and host configurations. It allows connecting to the Qiskit Serverless gateway, defaulting to local infrastructure if environment variables are not set. ```python import os from qiskit_serverless import ServerlessClient, QiskitFunction serverless = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost"), # If you are using the kubernetes approach the URL must be http://localhost ) serverless ``` -------------------------------- ### Create and Run a Qiskit Function Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/01_running_program.ipynb This snippet shows the complete process of defining a Qiskit Function, uploading it, running it via the ServerlessClient, and retrieving the job results and logs. ```python from qiskit import QuantumCircuit from qiskit.primitives import Sampler from qiskit_serverless import save_result # all print statement will be available in job logs print("Running function...") # creating circuit circuit = QuantumCircuit(2) circuit.h(0) circuit.cx(0, 1) circuit.measure_all() # running Sampler primitive sampler = Sampler() quasi_dists = sampler.run(circuit).result().quasi_dists # save results of function execution, # which will be accessible by calling `.result()` save_result(quasi_dists) print("Completed running function.") ``` ```python from qiskit_serverless import ServerlessClient import os client = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), # If you are using the kubernetes approach the URL must be http://localhost ) client ``` ```python from qiskit_serverless import QiskitFunction function = QiskitFunction( title="my-first-function", entrypoint="function.py", working_dir="./source_files/" ) client.upload(function) ``` ```python my_first_function = client.get("my-first-function") my_first_function ``` ```python job = my_first_function.run() job ``` ```python job.status() ``` ```python job.result() ``` ```python print(job.logs()) ``` ```python client.widget() ``` -------------------------------- ### Get Job Result Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/experimental/file_download.ipynb Retrieves the result of a completed Qiskit Function job. ```python job.result() ``` -------------------------------- ### Running the QAOA Job Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/examples/02_qaoa.ipynb This code initiates the execution of the uploaded QAOA function on the Qiskit Serverless platform. It passes the prepared input arguments to the job and returns a job object that can be used to monitor the execution status and retrieve results. ```python job = serverless.run("qaoa", arguments=input_arguments) job ``` -------------------------------- ### Get Job Status Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/04_distributed_workloads.ipynb Checks the current status of a submitted Qiskit Serverless job. This allows monitoring the progress of the distributed computation. ```python job.status() ``` -------------------------------- ### Modify Docker Compose Definition Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/example_custom_image_function.rst Configuration snippet for docker-compose.yml to specify the custom Docker image for the Ray head service. ```yaml services: ray-head: container_name: ray-head image: test-local-provider-function:latest ``` -------------------------------- ### Terraform Project Initialization Source: https://github.com/qiskit/qiskit-serverless/blob/main/CONTRIBUTING.md Initializes Terraform projects, preparing them for use. This command downloads necessary providers and modules. ```terraform terraform init ``` -------------------------------- ### Initialize ServerlessClient Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/05_retrieving_past_results.ipynb Creates an instance of the ServerlessClient to interact with the Qiskit Serverless backend. It configures the client with gateway token and host, defaulting to environment variables or local settings. ```python from qiskit_serverless import ServerlessClient import os client = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), # If you are using the kubernetes approach the URL must be http://localhost ) client ``` -------------------------------- ### Get Job Result Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/experimental/manage_data_directory.ipynb Retrieves the result of a completed Qiskit Function job. This is typically called after the job has finished execution. ```python job.result() ``` -------------------------------- ### QAOA Ansatz Preparation Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/examples/02_qaoa.ipynb This code prepares the necessary components for the QAOA algorithm, including defining the Pauli operator and creating and decomposing the QAOA ansatz. It also includes drawing the ansatz circuit for visualization. ```python import numpy as np from qiskit.circuit.library import QAOAAnsatz from qiskit.quantum_info import SparsePauliOp from qiskit_ibm_runtime import QiskitRuntimeService operator = SparsePauliOp.from_list( [("IIIZZ", 1), ("IIZIZ", 1), ("IZIIZ", 1), ("ZIIIZ", 1)] ) ansatz = QAOAAnsatz(operator, reps=2) ansatz = ansatz.decompose(reps=3) ansatz.draw(fold=-1) ``` -------------------------------- ### Qiskit Function Upload Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/examples/02_qaoa.ipynb This snippet defines and uploads a Qiskit Function for the QAOA pattern to the Qiskit Serverless platform. It specifies the function's title, entrypoint, working directory, and dependencies. ```python from qiskit_serverless import QiskitFunction function = QiskitFunction( title="qaoa", entrypoint="qaoa.py", working_dir="./source_files/qaoa/", dependencies=["qiskit_aer"] ) serverless.upload(function) ``` -------------------------------- ### Python Project Dependencies Source: https://github.com/qiskit/qiskit-serverless/blob/main/CONTRIBUTING.md Installs development dependencies for Python projects within the Qiskit Serverless repository. It's recommended to use a virtual environment for managing these dependencies. ```python pip install -r requirements.txt -r requirements-dev.txt ``` -------------------------------- ### Qiskit Serverless Client Initialization Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/examples/02_qaoa.ipynb This code initializes the Qiskit Serverless client, which is used to interact with the Qiskit Serverless platform. It retrieves the gateway token and host from environment variables or uses default values. ```python from qiskit_serverless import ServerlessClient import os serverless = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), ) serverless ``` -------------------------------- ### Documentation Dependencies Source: https://github.com/qiskit/qiskit-serverless/blob/main/client/requirements-dev.txt Lists packages required for generating project documentation, such as Sphinx and related extensions for notebooks and type hints. ```python jupyter-sphinx>=0.5.3 nbsphinx>=0.9.7 sphinx-autodoc-typehints>=1.24.0 ``` -------------------------------- ### Get List of All Jobs Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/05_retrieving_past_results.ipynb Retrieves a list of all previously executed functions using the `get_jobs()` method. This method supports pagination with `limit` and `offset` parameters. ```python client.get_jobs(limit=2, offset=1) ``` -------------------------------- ### Example QiskitFunction with Pendulum Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/03_dependencies.ipynb A Python script demonstrating the use of the 'pendulum' library to calculate the difference in hours between two timezones (Toronto and Vancouver). The result is saved using `save_result`. ```python from qiskit_serverless import save_result import pendulum dt_toronto = pendulum.datetime(2012, 1, 1, tz='America/Toronto') dt_vancouver = pendulum.datetime(2012, 1, 1, tz='America/Vancouver') diff = dt_vancouver.diff(dt_toronto).in_hours() print(diff) save_result({"hours": diff}) ``` -------------------------------- ### Clone Qiskit Serverless Repository Source: https://github.com/qiskit/qiskit-serverless/blob/main/README.md Clones the Qiskit Serverless repository from GitHub to your local machine. ```shell git clone https://github.com/Qiskit/qiskit-serverless.git ``` -------------------------------- ### Activate Python Virtual Environment (Windows PowerShell) Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/local.rst Activates the Python virtual environment on Windows using PowerShell. This command is specific to the Windows operating system and PowerShell environment. ```powershell c:\path\to\virtual\environment\Scripts\Activate.ps1 ``` -------------------------------- ### Reformat Code with Black Source: https://github.com/qiskit/qiskit-serverless/blob/main/client/tests/README.md Invokes the Black environment to automatically reformat all files in the repository according to the Black style guide. This is useful for fixing formatting issues identified by the lint environment. ```sh $ tox -eblack ``` -------------------------------- ### Serverless Client Initialization Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/03_dependencies.ipynb Initializes the ServerlessClient to interact with the Qiskit Serverless platform. It configures the client with gateway token and host, which can be set via environment variables or directly. ```python from qiskit_serverless import ServerlessClient import os client = ServerlessClient( token=os.environ.get("GATEWAY_TOKEN", "awesome_token"), host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"), # If you are using the kubernetes approach the URL must be http://localhost ) client ``` -------------------------------- ### Run Qiskit Functions in Parallel Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/getting_started/basic/05_retrieving_past_results.ipynb Uploads and runs two Qiskit Functions concurrently. It defines a QiskitFunction, uploads it, retrieves it by name, and then executes it twice to get two job instances. ```python from qiskit_serverless import QiskitFunction function = QiskitFunction( title="function-to-fetch-results", entrypoint="function.py", working_dir="./source_files/" ) client.upload(function) my_function = client.get("function-to-fetch-results") job1 = my_function.run() job2 = my_function.run() job1, job2 ``` -------------------------------- ### Port Forwarding for Gateway Service Source: https://github.com/qiskit/qiskit-serverless/blob/main/docs/deployment/cloud.rst Establishes a port-forwarding connection to the gateway service in a Kubernetes cluster. This allows access to cluster services from localhost, mapping local port 3333 to the service's port 8000. ```bash $ kubectl port-forward service/gateway 3333:8000 ```