### Set Up cimod Development Environment Source: https://jij-inc.github.io/cimod/index Guides developers through setting up the cimod project environment using uv for dependency management. Covers cloning the repository, installing uv, and installing development dependencies. ```bash # Clone repository $ git clone https://github.com/Jij-Inc/cimod.git $ cd cimod # Install uv (choose one method) $ curl -LsSf https://astral.sh/uv/install.sh | sh # macOS/Linux # or: brew install uv # Homebrew # or: pip install uv # fallback option # Install with development dependencies (exact versions) $ uv sync --locked --group dev # Verify installation $ uv run python -c "import cimod; print('cimod installed successfully')" $ uv run pytest tests/ -v --tb=short ``` -------------------------------- ### Install cimod for Developers Source: https://jij-inc.github.io/cimod/_sources/index Guides developers on setting up the cimod project using uv for dependency management, including cloning the repository and installing development dependencies. ```Shell # Clone repository $ git clone https://github.com/Jij-Inc/cimod.git $ cd cimod # Install uv (choose one method) $ curl -LsSf https://astral.sh/uv/install.sh | sh # macOS/Linux # or: brew install uv # Homebrew # or: pip install uv # fallback option # Install with development dependencies (exact versions) $ uv sync --locked --group dev # Verify installation $ uv run python -c "import cimod; print('cimod installed successfully')" $ uv run pytest tests/ -v --tb=short ``` -------------------------------- ### Cimod Usage Example Structure Source: https://jij-inc.github.io/cimod/index Illustrates the structure for providing usage examples for the Cimod library. It indicates where C++ and Python code examples would be placed. ```APIDOC Example Usage: - C++: (Code examples for C++ usage) - Python: (Code examples for Python usage) ``` -------------------------------- ### Install cimod Package Source: https://jij-inc.github.io/cimod/index Provides commands for installing the cimod Python package. Includes installation via pip from PyPI (binary and source) and directly from the GitHub repository. ```bash # Binary package (recommended) $ pip install jij-cimod # From source $ pip install --no-binary=jij-cimod jij-cimod # Latest development version $ pip install git+https://github.com/Jij-Inc/cimod.git ``` -------------------------------- ### Install cimod Package Source: https://jij-inc.github.io/cimod/_sources/index Provides commands for installing the cimod Python package, including options for binary packages, from source, and the latest development version. ```Shell # Binary package (recommended) $ pip install jij-cimod # From source $ pip install --no-binary=jij-cimod jij-cimod # Latest development version $ pip install git+https://github.com/Jij-Inc/cimod.git ``` -------------------------------- ### Python Testing with pytest Source: https://jij-inc.github.io/cimod/_sources/index Instructions for installing Python test dependencies and running tests using pytest. Includes options for verbose output and generating coverage reports. ```shell # Install test dependencies (exact versions) $ uv sync --locked --group test # Basic test run $ uv run pytest tests/ -v # With coverage report $ uv run pytest tests/ -v --cov=cimod --cov-report=html $ uv run python -m coverage html ``` -------------------------------- ### Run Python Tests with Coverage Source: https://jij-inc.github.io/cimod/index Instructions for running the test suite for the Python components of cimod. It details installing test dependencies and executing tests with pytest, including generating an HTML coverage report. ```bash # Install test dependencies (exact versions) $ uv sync --locked --group test # Basic test run $ uv run pytest tests/ -v # With coverage report $ uv run pytest tests/ -v --cov=cimod --cov-report=html $ uv run python -m coverage html ``` -------------------------------- ### Code Quality Checks with Ruff Source: https://jij-inc.github.io/cimod/index Details how to use Ruff for code quality management in cimod. Includes commands to install formatting dependencies, perform linting checks, format code, and auto-fix issues. ```bash # Install format dependencies (exact versions) $ uv sync --locked --group format # Check and fix all issues $ uv run ruff check . # Lint check $ uv run ruff format . # Format code $ uv run ruff check . --fix # Auto-fix issues # All-in-one check (recommended) $ uv run ruff check . && uv run ruff format --check . ``` -------------------------------- ### Dependency Management with uv Source: https://jij-inc.github.io/cimod/_sources/index Manages project dependencies using 'uv' based on PEP 735 dependency groups. Includes commands for installing specific groups, lock file usage for reproduction, development, and updating lock files. ```shell # Install development dependencies (build + test + format) $ uv sync --group dev # Install testing tools (pytest, coverage) $ uv sync --group test # Install documentation generation tools $ uv sync --group docs # Install code formatting tools (ruff only) $ uv sync --group format # Install complete environment (dev + docs) $ uv sync --group all # For exact reproduction (CI/CD, verification) $ uv sync --locked --group dev # For development (may update dependencies) $ uv sync --group dev # To update lock file $ uv lock $ uv lock --upgrade ``` -------------------------------- ### C++ Testing with CMake and CTest Source: https://jij-inc.github.io/cimod/_sources/index Guides on building and running C++ tests. Requires a C++17 compatible compiler and CMake 3.20+. Demonstrates building with CMake and executing tests directly or via CTest. ```shell # Build C++ tests (independent of Python environment) $ mkdir build $ cmake -DCMAKE_BUILD_TYPE=Debug -S . -B build $ cmake --build build --parallel # Run C++ tests $ cd build $ ./tests/cimod_test # Alternatively Use CTest $ ctest --extra-verbose --parallel --schedule-random ``` -------------------------------- ### Get Variables Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Retrieves a list of all unique variables present in the BinaryQuadraticModel. ```APIDOC BinaryQuadraticModel::get_variables() - Returns a collection of all variable identifiers currently in the model. - Returns: A list or set of IndexType identifiers. ``` -------------------------------- ### Helper Functions for Model Configuration Source: https://jij-inc.github.io/cimod/reference/cimod/model/binary_quadratic_model/index This section includes utility functions for extracting configuration parameters and determining the appropriate cimod class implementation. These functions assist in the internal workings of model creation and management. ```APIDOC cimod.model.binary_quadratic_model.extract_offset_and_vartype(**args*, ***kwargs*) - Extracts offset and vartype from arguments. cimod.model.binary_quadratic_model.get_cxxcimod_class(*linear*, *quadratic*, *sparse*) - Retrieves the appropriate cimod class based on input parameters. - Parameters: - linear: Linear bias information. - quadratic: Quadratic bias information. - sparse: Boolean indicating whether to use sparse matrix representation. ``` -------------------------------- ### Get C++ cimod Class Source: https://jij-inc.github.io/cimod/_sources/reference/cimod/model/binary_quadratic_model/index Retrieves the appropriate C++ cimod class based on the input linear and quadratic bias structures and sparsity. ```Python def get_cxxcimod_class(linear, quadratic, sparse): # ... implementation details ... pass ``` -------------------------------- ### BinaryQuadraticModel Initialization and Generation Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model Methods for initializing the quadratic matrix and generating linear/quadratic terms. Includes functions for initializing from linear/quadratic terms, dense/sparse matrices, and generating specific components of the model. ```APIDOC cimod::BinaryQuadraticModel::_initialize_quadmat(const Linear&, const Quadratic&, json::dispatch_t) - Initializes the quadratic matrix using linear and quadratic terms for dense matrices. - Parameters: - Linear<...>: Linear terms. - Quadratic<...>: Quadratic terms. - T5Dense: Dispatch type for dense matrices. cimod::BinaryQuadraticModel::_initialize_quadmat(const Linear&, const Quadratic&, json::dispatch_t) - Initializes the quadratic matrix using linear and quadratic terms for sparse matrices. - Parameters: - Linear<...>: Linear terms. - Quadratic<...>: Quadratic terms. - T6Sparse: Dispatch type for sparse matrices. cimod::BinaryQuadraticModel::_add_triangular_elements(const DenseMatrix&, bool, json::dispatch_t) - Adds triangular elements to the matrix from a dense matrix (dense format). - Parameters: - DenseMatrix: The source dense matrix. - bool: Flag for triangular elements. - T5Dense: Dispatch type for dense matrices. cimod::BinaryQuadraticModel::_add_triangular_elements(const DenseMatrix&, bool, json::dispatch_t) - Adds triangular elements to the matrix from a dense matrix (sparse format). - Parameters: - DenseMatrix: The source dense matrix. - bool: Flag for triangular elements. - T6Sparse: Dispatch type for sparse matrices. cimod::BinaryQuadraticModel::_initialize_quadmat(const DenseMatrix&, const std::vector&, bool) - Initializes the quadratic matrix from a dense matrix and label information. - Parameters: - DenseMatrix: The source dense matrix. - std::vector: List of labels. - bool: Flag for initialization. cimod::BinaryQuadraticModel::_generate_linear() - Generates the linear terms of the model. cimod::BinaryQuadraticModel::_generate_quadratic(Quadratic, json::dispatch_t) - Generates quadratic terms for dense matrices. - Parameters: - Quadratic<...>: Placeholder for quadratic terms. - T5Dense: Dispatch type for dense matrices. cimod::BinaryQuadraticModel::_generate_quadratic(Quadratic, json::dispatch_t) - Generates quadratic terms for sparse matrices. - Parameters: - Quadratic<...>: Placeholder for quadratic terms. - T6Sparse: Dispatch type for sparse matrices. cimod::BinaryQuadraticModel::_initialize_quadmat(const SparseMatrix&, const std::vector&) - Initializes the quadratic matrix from a sparse matrix and label information. - Parameters: - SparseMatrix: The source sparse matrix. - std::vector: List of labels. cimod::BinaryQuadraticModel::_spin_to_binary(json::dispatch_t) - Converts spin representation to binary representation (dense format). - Parameters: - T5Dense: Dispatch type for dense matrices. ``` -------------------------------- ### Get Linear Biases Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Retrieves linear biases from the BinaryQuadraticModel. Supports fetching for a specific variable or all variables. ```APIDOC BinaryQuadraticModel::get_linear(IndexType) - Retrieves the linear bias associated with a specific variable. - Parameters: - IndexType: The identifier of the variable. - Returns: The linear bias (FloatType) for the specified variable. BinaryQuadraticModel::get_linear() - Retrieves all linear biases in the model. - Returns: A dictionary-like object mapping variable identifiers to their linear biases. ``` -------------------------------- ### Get Quadratic Biases Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Retrieves quadratic biases from the BinaryQuadraticModel. Supports fetching for a specific interaction pair or all interactions. ```APIDOC BinaryQuadraticModel::get_quadratic(IndexType, IndexType) - Retrieves the quadratic bias for a specific interaction between two variables. - Parameters: - IndexType: The identifier of the first variable. - IndexType: The identifier of the second variable. - Returns: The quadratic bias (FloatType) for the interaction. BinaryQuadraticModel::get_quadratic() - Retrieves all quadratic biases in the model. - Returns: A dictionary-like object mapping pairs of variable identifiers to their quadratic biases. ``` -------------------------------- ### cimod::FormatPolynomialKey Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/utilities Formats an input key based on the specified variable type. For example, it converts {2,1,1} to {1,2} for BINARY variables and {2} for SPIN variables. ```APIDOC template void FormatPolynomialKey(std::vector *key, const cimod::Vartype &vartype) Formats the input key: for example, {2,1,1}–>{1,2} for BINARY variable and {2,1,1}–>{2} for SPIN variable. Template Parameters: IndexType: Used to represent the indices of variables. Parameters: key: This may be formatted. Pointer to a vector of indices. vartype: The model’s type. Expected values are cimod::Vartype::SPIN or cimod::Vartype::BINARY. ``` -------------------------------- ### BinaryQuadraticModel and Factory Functions Source: https://jij-inc.github.io/cimod/reference/cimod/model/legacy/binary_quadratic_model/index Documentation for the BinaryQuadraticModel class and its factory functions, used for creating and initializing BinaryQuadraticModel instances. Includes details on parameters and return types for creation methods. ```APIDOC BinaryQuadraticModel Class and Factory Functions: BinaryQuadraticModel(*linear*, *quadratic*, **args, **kwargs) Represents a Binary Quadratic Model. make_BinaryQuadraticModel(*linear*, *quadratic*) BinaryQuadraticModel factory. Generate BinaryQuadraticModel class with the base class specified by the arguments linear and quadratic. Parameters: linear (dict): linear bias quadratic (dict): quadratic bias Returns: generated BinaryQuadraticModel class make_BinaryQuadraticModel_from_JSON(*obj*) Factory function to create a BinaryQuadraticModel from a JSON object. Parameters: obj: The JSON object or data structure representing the model. Returns: A BinaryQuadraticModel instance. ``` -------------------------------- ### Cimod Legacy Binary Quadratic Model License Source: https://jij-inc.github.io/cimod/_modules/cimod/model/legacy/binary_quadratic_model Contains copyright and licensing information for the cimod.model.legacy.binary_quadratic_model module. ```Python # Copyright 2020-2025 Jij Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` -------------------------------- ### Get Offset and Variable Type Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Retrieves the model's offset value and the type of variables used within the model. ```APIDOC BinaryQuadraticModel::get_offset() - Retrieves the constant offset term of the model. - Returns: The offset value (FloatType). BinaryQuadraticModel::get_vartype() - Retrieves the type of variables (e.g., BINARY, SPIN) used in the model. - Returns: The variable type (Vartype). ``` -------------------------------- ### cimod::BinaryQuadraticModel Member Functions Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Documents essential member functions for interacting with the BinaryQuadraticModel, such as getting its length, number of variables, and checking for variable existence. ```APIDOC size_t length() const Returns the total number of variables in the model. size_t get_num_variables() const Returns the number of variables in the model. bool contains(const IndexType& index) const Checks if a variable with the given index exists in the model. ``` -------------------------------- ### cimod BinaryQuadraticModel Constructors Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model Provides documentation for the various constructors of the cimod::BinaryQuadraticModel class. These constructors allow initialization using linear and quadratic terms, dense matrices with optional offsets, and sparse matrices with optional offsets. A copy constructor is also available. ```APIDOC BinaryQuadraticModel(const cimod::Linear &linear, const cimod::Quadratic &quadratic, const cimod::Vartype vartype) : constructor for BinaryQuadraticModel using linear and quadratic terms. Parameters: linear: cimod::Linear object containing linear terms. quadratic: cimod::Quadratic object containing quadratic terms. vartype: cimod::Vartype specifying the variable type. ``` ```APIDOC BinaryQuadraticModel(const Eigen::Ref &mat, const std::vector &labels_vec, const cimod::BinaryQuadraticModel::FloatType &offset, const cimod::Vartype vartype, bool fix_format = true) : constructor for BinaryQuadraticModel using a dense matrix and an offset. Parameters: mat: Eigen::Ref to a DenseMatrix representing the model coefficients. labels_vec: Vector of IndexType representing variable labels. offset: FloatType value for the model's offset. vartype: cimod::Vartype specifying the variable type. fix_format: Boolean flag to enforce a specific matrix format (default: true). ``` ```APIDOC BinaryQuadraticModel(const Eigen::Ref &mat, const std::vector &labels_vec, const cimod::Vartype vartype, bool fix_format = true) : constructor for BinaryQuadraticModel using a dense matrix without an explicit offset. Parameters: mat: Eigen::Ref to a DenseMatrix representing the model coefficients. labels_vec: Vector of IndexType representing variable labels. vartype: cimod::Vartype specifying the variable type. fix_format: Boolean flag to enforce a specific matrix format (default: true). ``` ```APIDOC BinaryQuadraticModel(const cimod::BinaryQuadraticModel::SparseMatrix &mat, const std::vector &labels_vec, const cimod::BinaryQuadraticModel::FloatType &offset, const cimod::Vartype vartype) : constructor for BinaryQuadraticModel using a sparse matrix and an offset (for developers). Parameters: mat: SparseMatrix object representing the model coefficients. labels_vec: Vector of IndexType representing variable labels. offset: FloatType value for the model's offset. vartype: cimod::Vartype specifying the variable type. ``` ```APIDOC BinaryQuadraticModel(const cimod::BinaryQuadraticModel::SparseMatrix &mat, const std::vector &labels_vec, const cimod::Vartype vartype) : constructor for BinaryQuadraticModel using a sparse matrix without an explicit offset (for developers). Parameters: mat: SparseMatrix object representing the model coefficients. labels_vec: Vector of IndexType representing variable labels. vartype: cimod::Vartype specifying the variable type. ``` ```APIDOC BinaryQuadraticModel(const cimod::BinaryQuadraticModel&) = default : Copy constructor for BinaryQuadraticModel. ``` -------------------------------- ### Initialize BinaryPolynomialModel from Keys/Values Source: https://jij-inc.github.io/cimod/_modules/cimod/model/binary_polynomial_model This Python code snippet demonstrates how to initialize a BinaryPolynomialModel using provided keys and values. It iterates through keys to find a suitable label, then constructs the model, handling cases where no label is found or the label is a list. ```python i = 0 label = None while i < len(keys): if len(keys[i]) > 0: label = keys[i][0] break i += 1 if label is None: return make_BinaryPolynomialModel({(): 1.0}).from_hubo(keys, values) else: if isinstance(label, list): label = tuple(label) mock_polynomial = {(label,): 1.0} return make_BinaryPolynomialModel(mock_polynomial).from_hubo(keys, values) ``` -------------------------------- ### Get state and energy from cimod model Source: https://jij-inc.github.io/cimod/_modules/cimod/utils/response Converts raw spin or binary states to the model's vartype, applying an offset, and calculates the energy. Handles automatic conversion between BINARY and SPIN vartypes. ```python # Copyright 2020-2025 Jij Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import dimod def get_state_and_energy( model, result_state, offset=0, model_variables=[] ) -> tuple[dict, float]: """get converted state and energy. This function receives raw array of spins or binaries. If vartype of model and the vartype of the raw array are different, the raw array is automatically converted to the vartype of model with any offset shift. Args: model: cimod model (BinaryQuadraticModel or BinaryPolynomialModel) result_state (list): states of spins or binaries offset (float): offset added to returned energy model_variables (Optional[list]): list of variables Returns: tuple[dict, float]: labeled states and corresponding energy Examples: """ temp_state = {} if len(model_variables) != 0: variables = model_variables else: variables = model.variables def _convert_data(d): if d == 0 and model.vartype == dimod.SPIN: return -1 elif d == -1 and model.vartype == dimod.BINARY: return 0 else: return d for num in range(len(model.variables)): temp_state[variables[num]] = _convert_data(result_state[num]) return temp_state, model.energy(temp_state) + offset ``` -------------------------------- ### cimod::BinaryQuadraticModel Constructors Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model Various constructors for creating BinaryQuadraticModel objects, supporting initialization from linear/quadratic terms, dense/sparse matrices, and copying. ```APIDOC Constructor: BinaryQuadraticModel(const Linear& linear, const Quadratic& quadratic, const FloatType& offset, const Vartype& vartype) Description: Constructs a BinaryQuadraticModel from linear, quadratic terms, offset, and variable type. Parameters: linear: A Linear object containing linear biases. quadratic: A Quadratic object containing quadratic biases. offset: The energy offset of the model. vartype: The variable type of the model. ``` ```APIDOC Constructor: BinaryQuadraticModel(const Linear& linear, const Quadratic& quadratic, const Vartype& vartype) Description: Constructs a BinaryQuadraticModel from linear, quadratic terms, and variable type (offset defaults to 0). Parameters: linear: A Linear object containing linear biases. quadratic: A Quadratic object containing quadratic biases. vartype: The variable type of the model. ``` ```APIDOC Constructor: BinaryQuadraticModel(const Eigen::Ref& dense_matrix, const std::vector& variables, const FloatType& offset, bool is_ising) Description: Constructs a BinaryQuadraticModel from a dense matrix representation, variable list, offset, and Ising/QUBO flag. Parameters: dense_matrix: A reference to the dense matrix. variables: A vector of variable indices. offset: The energy offset. is_ising: Boolean indicating if the model is Ising (true) or QUBO (false). ``` ```APIDOC Constructor: BinaryQuadraticModel(const Eigen::Ref& dense_matrix, const std::vector& variables, const Vartype& vartype, bool is_ising) Description: Constructs a BinaryQuadraticModel from a dense matrix representation, variable list, variable type, and Ising/QUBO flag (offset defaults to 0). Parameters: dense_matrix: A reference to the dense matrix. variables: A vector of variable indices. vartype: The variable type of the model. is_ising: Boolean indicating if the model is Ising (true) or QUBO (false). ``` ```APIDOC Constructor: BinaryQuadraticModel(const SparseMatrix& sparse_matrix, const std::vector& variables, const FloatType& offset, const Vartype& vartype) Description: Constructs a BinaryQuadraticModel from a sparse matrix representation, variable list, offset, and variable type. Parameters: sparse_matrix: The sparse matrix representation. variables: A vector of variable indices. offset: The energy offset. vartype: The variable type of the model. ``` ```APIDOC Constructor: BinaryQuadraticModel(const SparseMatrix& sparse_matrix, const std::vector& variables, const Vartype& vartype) Description: Constructs a BinaryQuadraticModel from a sparse matrix representation, variable list, and variable type (offset defaults to 0). Parameters: sparse_matrix: The sparse matrix representation. variables: A vector of variable indices. vartype: The variable type of the model. ``` ```APIDOC Constructor: BinaryQuadraticModel(const BinaryQuadraticModel& other) Description: Copy constructor for BinaryQuadraticModel. Parameters: other: The BinaryQuadraticModel object to copy. ``` -------------------------------- ### Get State and Energy from cimod Response (Python) Source: https://jij-inc.github.io/cimod/_sources/reference/cimod/utils/response/index Converts raw spin or binary arrays into the model's specified vartype, handling potential offset shifts. This function is useful for interpreting results from quantum or classical solvers. ```Python def get_state_and_energy(model, result_state, offset=0, model_variables=[]) -> tuple[dict, float]: """ get converted state and energy. This function receives raw array of spins or binaries. If vartype of model and the vartype of the raw array are different, the raw array is automatically converted to the vartype of model with any offset shift. :param model: cimod model (BinaryQuadraticModel or BinaryPolynomialModel) :param result_state: states of spins or binaries :type result_state: list :param offset: offset added to returned energy :type offset: float :param model_variables: list of variables :type model_variables: Optional[list] :returns: labeled states and corresponding energy :rtype: tuple[dict, float] Examples: """ pass ``` -------------------------------- ### cimod::BinaryQuadraticModel Constructors Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Provides documentation for various constructors used to initialize a BinaryQuadraticModel instance from different data structures and formats. ```APIDOC BinaryQuadraticModel(const Linear& linear, const Quadratic& quadratic, const FloatType& offset, const Vartype vartype) Constructs a BinaryQuadraticModel from linear, quadratic biases, offset, and variable type. BinaryQuadraticModel(const Linear& linear, const Quadratic& quadratic, const Vartype vartype) Constructs a BinaryQuadraticModel from linear, quadratic biases, and variable type, with a default offset of 0. BinaryQuadraticModel(const Eigen::Ref& dense_matrix, const std::vector& indices, const FloatType& offset, bool is_upper_triangle) Constructs a BinaryQuadraticModel from an Eigen dense matrix, indices, offset, and a flag indicating if the matrix represents the upper triangle. BinaryQuadraticModel(const Eigen::Ref& dense_matrix, const std::vector& indices, const Vartype vartype, bool is_upper_triangle) Constructs a BinaryQuadraticModel from an Eigen dense matrix, indices, variable type, and a flag indicating if the matrix represents the upper triangle. BinaryQuadraticModel(const SparseMatrix& sparse_matrix, const std::vector& indices, const FloatType& offset, const Vartype vartype) Constructs a BinaryQuadraticModel from a sparse matrix, indices, offset, and variable type. BinaryQuadraticModel(const SparseMatrix& sparse_matrix, const std::vector& indices, const Vartype vartype) Constructs a BinaryQuadraticModel from a sparse matrix, indices, and variable type, with a default offset of 0. BinaryQuadraticModel(const BinaryQuadraticModel& other) Copy constructor for BinaryQuadraticModel. ``` -------------------------------- ### cimod::BinaryQuadraticModel: Variable and Property Getters Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model Provides methods to retrieve information about variables and properties within a BinaryQuadraticModel. This includes checking for variable existence, getting linear and quadratic biases, the offset, variable type, and the list of variables. ```APIDOC size_t length() const - Returns the number of variables in the model. - Deprecated: Use get_num_variables instead. bool contains(const IndexType &v) const - Checks if the model contains a specific variable. - Parameters: - v: The variable identifier (IndexType) to check. - Returns: true if the variable exists, false otherwise. FloatType get_linear(IndexType label_i) const - Retrieves the linear bias for a specific variable. - Parameters: - label_i: The identifier (IndexType) of the variable. - Returns: The linear bias (FloatType) of the variable. Linear get_linear() const - Retrieves the entire linear object containing biases for all variables. - Returns: A Linear object. FloatType get_quadratic(IndexType label_i, IndexType label_j) const - Retrieves the quadratic bias between two specific variables. - Parameters: - label_i: The identifier (IndexType) of the first variable. - label_j: The identifier (IndexType) of the second variable. - Returns: The quadratic bias (FloatType) between the two variables. Quadratic get_quadratic() const - Retrieves the entire quadratic object containing biases for all variable pairs. - Returns: A Quadratic object. FloatType get_offset() const - Retrieves the global offset of the model. - Returns: The offset value (FloatType). Vartype get_vartype() const - Retrieves the variable type of the model. - Returns: The Vartype of the model. const std::vector &get_variables() const - Retrieves a constant reference to the vector of all variables in the model. - Returns: A const reference to std::vector. ``` -------------------------------- ### Binary Quadratic Model Creation Source: https://jij-inc.github.io/cimod/_sources/reference/cimod/index Offers functions for creating and handling BinaryQuadraticModel instances. Supports factory methods for direct model generation and loading from JSON. ```APIDOC cimod.BinaryQuadraticModel(linear, quadratic, *args, **kwargs) Represents a binary quadratic model. :param linear: Linear bias terms. :type linear: dict :param quadratic: Quadratic bias terms. :type quadratic: dict :param sparse: If true, the inner data will be a sparse matrix, otherwise the data will be a dense matrix. :type sparse: bool :param *args: Positional arguments. :param **kwargs: Keyword arguments. :returns: generated BinaryQuadraticModel class cimod.make_BinaryQuadraticModel(linear, quadratic, sparse) BinaryQuadraticModel factory. Generate BinaryQuadraticModel class with the base class specified by the arguments linear and quadratic. :param linear: linear bias :type linear: dict :param quadratic: quadratic bias :type quadratic: dict :param sparse: if true, the inner data will be a sparse matrix, otherwise the data will be a dense matrix :type sparse: bool :returns: generated BinaryQuadraticModel class cimod.make_BinaryQuadraticModel_from_JSON(obj) Factory function to create a BinaryQuadraticModel from a JSON object. :param obj: The JSON object representing the model. :type obj: dict ``` -------------------------------- ### Get cimod BinaryQuadraticModel Class Source: https://jij-inc.github.io/cimod/_modules/cimod/model/binary_quadratic_model Selects the appropriate base class for BinaryQuadraticModel (Sparse or Dense) based on the types of indices in linear and quadratic terms, and the sparsity setting. It handles integer, string, and tuple indices for variables. ```python import cimod import cimod.cxxcimod as cxxcimod from scipy.sparse import dok_matrix, csr_matrix def get_cxxcimod_class(linear, quadratic, sparse): # select base class index = set() base = None if linear != {}: index.add(next(iter(linear))) if quadratic != {}: index.add(next(iter(quadratic))[0]) index.add(next(iter(quadratic))[1]) if len(set(type(i) for i in index)) != 1: # assume that index type is int ind = int(0) else: ind = next(iter(index)) if sparse: if isinstance(ind, int): base = cxxcimod.BinaryQuadraticModel_Sparse elif isinstance(ind, str): base = cxxcimod.BinaryQuadraticModel_str_Sparse elif isinstance(ind, tuple): if len(ind) == 2: base = cxxcimod.BinaryQuadraticModel_tuple2_Sparse elif len(ind) == 3: base = cxxcimod.BinaryQuadraticModel_tuple3_Sparse elif len(ind) == 4: base = cxxcimod.BinaryQuadraticModel_tuple4_Sparse else: raise TypeError("invalid length of tuple") else: raise TypeError("invalid types of linear and quadratic") else: if isinstance(ind, int): base = cxxcimod.BinaryQuadraticModel_Dense elif isinstance(ind, str): base = cxxcimod.BinaryQuadraticModel_str_Dense elif isinstance(ind, tuple): if len(ind) == 2: base = cxxcimod.BinaryQuadraticModel_tuple2_Dense elif len(ind) == 3: base = cxxcimod.BinaryQuadraticModel_tuple3_Dense elif len(ind) == 4: base = cxxcimod.BinaryQuadraticModel_tuple4_Dense else: raise TypeError("invalid length of tuple") else: raise TypeError("invalid types of linear and quadratic") return base ``` -------------------------------- ### BinaryPolynomialModel Class Constructors Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_polynomial_model API documentation for the BinaryPolynomialModel class constructors in the cimod namespace. These constructors initialize the model using different input formats for polynomial coefficients. ```APIDOC BinaryPolynomialModel(const Polynomial &poly_map, const Vartype vartype) - Constructor for BinaryPolynomialModel. - Initializes the model using a map of polynomial terms and their coefficients. - Parameters: - poly_map: A constant reference to a Polynomial map (std::unordered_map, FloatType, vector_hash>). - vartype: The variable type (Vartype) for the model. BinaryPolynomialModel(const PolynomialKeyList &key_list, const PolynomialValueList &value_list, const Vartype vartype) - Constructor for BinaryPolynomialModel. - Initializes the model using separate lists for polynomial keys and values. - Parameters: - key_list: A constant reference to a PolynomialKeyList (std::vector>). - value_list: A constant reference to a PolynomialValueList (std::vector). - vartype: The variable type (Vartype) for the model. BinaryPolynomialModel(const PolynomialKeyList &key_list, const PolynomialValueList &value_list, const Vartype vartype) - Constructor for BinaryPolynomialModel. - Initializes the model using separate lists for polynomial keys and values. - This is a duplicate signature as provided in the source text, likely intended for different internal handling or a typo. - Parameters: - key_list: A constant reference to a PolynomialKeyList (std::vector>). - value_list: A constant reference to a PolynomialValueList (std::vector). - vartype: The variable type (Vartype) for the model. ``` -------------------------------- ### C++ Cimod API Reference Overview Source: https://jij-inc.github.io/cimod/index Provides an overview of the C++ Cimod API, listing key header files and their functionalities. This section details the structure of the C++ library's components. ```APIDOC C++ Cimod API Reference: - Binary Polynomial Model: cxxcimod/include/cimod/binary_polynomial_model.html - Binary Quadratic Model: cxxcimod/include/cimod/binary_quadratic_model.html - Binary Quadratic Model Dict: cxxcimod/include/cimod/binary_quadratic_model_dict.html - Disable Eigen Warning: cxxcimod/include/cimod/disable_eigen_warning.html - Hash: cxxcimod/include/cimod/hash.html - Json: cxxcimod/include/cimod/json.html - Utilities: cxxcimod/include/cimod/utilities.html - Vartypes: cxxcimod/include/cimod/vartypes.html ``` -------------------------------- ### Initialize BinaryQuadraticModel Source: https://jij-inc.github.io/cimod/_sources/reference/cimod/model/legacy/index Constructs a BinaryQuadraticModel object. It accepts linear and quadratic terms, along with arbitrary positional and keyword arguments. ```APIDOC BinaryQuadraticModel(linear, quadratic, *args, **kwargs) Initializes a BinaryQuadraticModel. Parameters: linear: Dictionary or list representing linear biases. quadratic: Dictionary or list representing quadratic biases. *args: Additional positional arguments. **kwargs: Additional keyword arguments. ``` -------------------------------- ### Benchmark Script for dimod and cimod Source: https://jij-inc.github.io/cimod/_sources/index A Python script to benchmark the performance of 'dimod' and 'cimod' libraries. It measures the time taken to initialize and calculate energies for BinaryQuadraticModel objects with varying problem sizes (N). ```python import dimod import cimod import time fil = open("benchmark", "w") fil.write("N t_dimod t_cimod\n") def benchmark(N, test_fw): linear = {} quadratic = {} spin = {} # interactions for i in range(N): spin[i] = 1 for elem in range(N): linear[elem] = 2.0*elem; for i in range(N): for j in range(i+1, N): if i != j: quadratic[(i,j)] = (i+j)/(N) t1 = time.time() # initialize a = test_fw.BinaryQuadraticModel(linear, quadratic, 0, test_fw.BINARY) a.change_vartype(test_fw.SPIN) # calculate energy for 50 times. for _ in range(50): print(a.energy(spin)) t2 = time.time() return t2-t1 d_arr = [] c_arr = [] for N in [25, 50, 100, 200, 300, 400, 600, 800,1000, 1600, 2000, 3200, 5000]: print("N {}".format(N)) d = benchmark(N, dimod) c = benchmark(N, cimod) print("{} {} {}".format(N, d, c)) fil.write("{} {} {}\n".format(N, d, c)) ``` -------------------------------- ### Create Model from QUBO/Ising Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Static methods to create a BinaryQuadraticModel from QUBO or Ising formulations. ```APIDOC BinaryQuadraticModel::from_qubo(QuadraticModel, FloatType) - Creates a BinaryQuadraticModel from a QUBO representation. - Parameters: - QuadraticModel: The QUBO biases. - FloatType: The offset value. - Returns: A new BinaryQuadraticModel instance. BinaryQuadraticModel::from_ising(LinearModel, QuadraticModel, FloatType) - Creates a BinaryQuadraticModel from an Ising representation. - Parameters: - LinearModel: The linear biases. - QuadraticModel: The quadratic biases. - FloatType: The offset value. - Returns: A new BinaryQuadraticModel instance. ``` -------------------------------- ### BinaryQuadraticModel Creation Methods Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model_dict Methods for creating BinaryQuadraticModel objects from different problem formulations. Includes creation from QUBO, Ising, and serializable inputs. ```APIDOC cimod::BinaryQuadraticModel::BinaryQuadraticModel from_qubo(const cimod::Quadratic &Q, FloatType offset = 0.0) Create a binary quadratic model from a QUBO model. Parameters: Q: The QUBO quadratic terms. offset: An optional offset value. Returns: Binary quadratic model with vartype set to .Vartype.BINARY. cimod::BinaryQuadraticModel::BinaryQuadraticModel from_ising(const cimod::Linear &linear, const cimod::Quadratic &quadratic, FloatType offset = 0.0) Create a binary quadratic model from an Ising problem. Parameters: linear: The Ising linear terms. quadratic: The Ising quadratic terms. offset: An optional offset value. Returns: Binary quadratic model with vartype set to .Vartype.SPIN. template cimod::BinaryQuadraticModel::BinaryQuadraticModel from_serializable(const cimod::BinaryQuadraticModel::json &input) Create a binary quadratic model from a serializable input (e.g., JSON). Parameters: input: The serializable input data. Returns: A BinaryQuadraticModel instance. ``` -------------------------------- ### APIDOC: BinaryQuadraticModel Matrix Initialization Source: https://jij-inc.github.io/cimod/cxxcimod/include/cimod/binary_quadratic_model Initializes the quadratic matrix for the BinaryQuadraticModel using a sparse matrix and a vector of labels. It assumes a specific upper triangular format for the input matrix. ```APIDOC inline void _initialize_quadmat(const SparseMatrix &mat, const std::vector &labels_vec) - Initializes the internal quadratic matrix and associated labels. - Assumed matrix format: (J0,0 J0,1 ... J0,N-1 h0 0 J1,1 ... J1,N-1 h1 ... ... ... ... ... 0 0 ... JN-1,N-1 hN-1 0 0 ... 0 1) - Parameters: - mat: The input sparse matrix containing linear and quadratic terms. - labels_vec: A vector of labels corresponding to the matrix dimensions. - Returns: void. Related Methods: - _generate_linear, _generate_quadratic: Methods to extract components after initialization. ``` -------------------------------- ### Python Cimod API Reference Overview Source: https://jij-inc.github.io/cimod/index Provides an overview of the Python Cimod API, listing key modules and submodules. This section outlines the structure of the Python interface for interacting with Cimod. ```APIDOC Python Cimod API Reference: - cimod: reference/cimod/index.html - cimod.model: reference/cimod/model/index.html - cimod.model.binary_polynomial_model: reference/cimod/model/binary_polynomial_model/index.html - cimod.model.binary_quadratic_model: reference/cimod/model/binary_quadratic_model/index.html - cimod.model.legacy: reference/cimod/model/legacy/index.html - cimod.model.legacy.binary_quadratic_model: reference/cimod/model/legacy/binary_quadratic_model/index.html - cimod.utils: reference/cimod/utils/index.html - cimod.utils.decolator: reference/cimod/utils/decolator/index.html - cimod.utils.response: reference/cimod/utils/response/index.html - cimod.vartype: reference/cimod/vartype/index.html ``` -------------------------------- ### Create BinaryQuadraticModel in Python Source: https://jij-inc.github.io/cimod/index Illustrates how to create a BinaryQuadraticModel instance in Python using the cimod library. It shows setting linear and quadratic biases, offset, and variable type, and printing the model's linear and quadratic terms. ```python import cimod import dimod # Set linear biases and quadratic biases linear = {1:1.0, 2:2.0, 3:3.0, 4:4.0} quadratic = {(1,2):12.0, (1,3):13.0, (1,4):14.0, (2,3):23.0, (2,4):24.0, (3,4):34.0} # Set offset offset = 0.0 # Set variable type vartype = dimod.BINARY # Create a BinaryQuadraticModel instance bqm = cimod.BinaryQuadraticModel(linear, quadratic, offset, vartype) print(bqm.linear) print(bqm.quadratic) ``` -------------------------------- ### BinaryQuadraticModel Creation and Factory Functions Source: https://jij-inc.github.io/cimod/reference/cimod/model/binary_quadratic_model/index This section details functions for creating BinaryQuadraticModel objects, including direct instantiation, factory methods, and conversion from different formats like Ising, QUBO, and NumPy matrices. It covers the primary class constructor and utility functions for model generation. ```APIDOC cimod.model.binary_quadratic_model.BinaryQuadraticModel(*linear*, *quadratic*, **args*, ***kwargs*) - Represents a Binary Quadratic Model. cimod.model.binary_quadratic_model.bqm_from_ising(*linear*, *quadratic*, *offset=0.0*, ***kwargs*) - Creates a BinaryQuadraticModel from Ising model parameters. - Parameters: - linear: Dictionary of linear biases. - quadratic: Dictionary of quadratic biases. - offset: Scalar offset value. cimod.model.binary_quadratic_model.bqm_from_numpy_matrix(*mat*, *variables=None*, *offset=0.0*, *vartype='BINARY'*, ***kwargs*) - Creates a BinaryQuadraticModel from a NumPy matrix. - Parameters: - mat: The NumPy matrix representing the quadratic biases. - variables: A list of variable names corresponding to the matrix dimensions. - offset: Scalar offset value. - vartype: The type of variables ('BINARY' or 'SPIN'). cimod.model.binary_quadratic_model.bqm_from_qubo(*Q*, *offset=0.0*, ***kwargs*) - Creates a BinaryQuadraticModel from QUBO parameters. - Parameters: - Q: Dictionary representing the QUBO problem. - offset: Scalar offset value. cimod.model.binary_quadratic_model.make_BinaryQuadraticModel(*linear*, *quadratic*, *sparse*) - BinaryQuadraticModel factory. - Generates a BinaryQuadraticModel class with the base class specified by the arguments linear and quadratic. - Parameters: - linear: Dictionary of linear biases. - quadratic: Dictionary of quadratic biases. - sparse: If true, the inner data will be a sparse matrix, otherwise dense. - Returns: Generated BinaryQuadraticModel class. cimod.model.binary_quadratic_model.make_BinaryQuadraticModel_from_JSON(*obj*) - Creates a BinaryQuadraticModel from a JSON object. - Parameters: - obj: The JSON object containing the model data. ```