qoolqit.embedding
embedding
Section titled “
embedding
”Collection of graph and matrix embedding algorithms.
Modules:
-
algorithms–Embedding algorithms and their configurations.
-
base_embedder–Base classes for embedders and their configs.
-
graph_embedder–Embedders mapping a graph to a graph with coordinates.
-
matrix_embedder–Embedders mapping a matrix to a graph with coordinates.
Classes:
-
BaseEmbedder–Abstract base class for all embedders.
-
Blade–A matrix to graph embedder using the BLaDE algorithm.
-
BladeConfig–Configuration parameters to embed with BLaDE.
-
EmbedderConfig–Base dataclass for all embedding algorithm configurations.
-
GraphToGraphEmbedder–A family of embedders that map a graph to a graph.
-
InteractionEmbedder–A matrix to graph embedder using the interaction embedding algorithm.
-
InteractionEmbedderConfig–Configuration parameters for the interaction embedding.
-
MatrixToGraphEmbedder–A family of embedders that map a matrix to a graph.
-
SpringLayoutConfig–Configuration parameters for the spring-layout embedding.
-
SpringLayoutEmbedder–A graph to graph embedder using the spring layout algorithm.
BaseEmbedder
Section titled “
BaseEmbedder
”BaseEmbedder(algorithm: Callable, config: ConfigType)Abstract base class for all embedders.
An embedder is a function that maps a InDataType to an OutDataType through an embedding algorithm. Parameters of the embedding algorithm can be customized through the EmbedderConfig.
An algorithm should be a standalone function that takes a piece of data of an InDataType and maps it to an OutDataType. Any extra configuration parameters taken as input by the algorithm function should be defined in the config dataclass, inheriting from EmbedderConfig.
Parameters:
-
algorithm(Callable) –a callable to the algorithm function.
-
config(ConfigType) –a config dataclass holding parameter values for the algorithm.
Methods:
-
embed–Validates the input, runs the embedding algorithm, and validates the output.
-
validate_input–Checks if the given data is compatible with the embedder.
-
validate_output–Checks if the resulting output is expected by the embedder.
Attributes:
-
algorithm(Callable) –Returns the callable to the embedding algorithm.
-
config(ConfigType) –Returns the config for the embedding algorithm.
-
info(str) –Prints info about the embedding algorithm.
Source code in qoolqit/embedding/base_embedder.py
def __init__(self, algorithm: Callable, config: ConfigType) -> None: """Default initializer for all embedders, taking an algorithm and a config.
An algorithm should be a standalone function that takes a piece of data of an InDataType and maps it to an OutDataType. Any extra configuration parameters taken as input by the algorithm function should be defined in the config dataclass, inheriting from EmbedderConfig.
Arguments: algorithm: a callable to the algorithm function. config: a config dataclass holding parameter values for the algorithm. """ if not isinstance(config, EmbedderConfig): raise TypeError( "The config must be an instance of a dataclass inheriting from EmbedderConfig." )
algo_signature = inspect.signature(algorithm) config_keys = set(config.dict().keys()) algo_signature_keys = set(algo_signature.parameters.keys()) if not config_keys <= algo_signature_keys: config_keys_str = "\n".join(f"\t- {key}" for key in config_keys) algo_keys_str = "\n".join(f"\t- {key}" for key in algo_signature_keys) raise TypeError( f"Config {config.__class__.__name__} is not compatible with the " + f"algorithm {algorithm.__name__}, as not all configuration fields " + "correspond to keyword arguments in the algorithm function.\n\n" + f"Config {config.__class__.__name__} keys:\n{config_keys_str}\n\n" + f"Algorithm signature parameters:\n{algo_keys_str}" )
self._algorithm = algorithm self._config = config
algorithm
property
Section titled “
algorithm
property
”algorithm: CallableReturns the callable to the embedding algorithm.
config
property
Section titled “
config
property
”config: ConfigTypeReturns the config for the embedding algorithm.
info
property
Section titled “
info
property
”info: strPrints info about the embedding algorithm.
embed
Section titled “
embed
”embed(data: InDataType) -> OutDataTypeValidates the input, runs the embedding algorithm, and validates the output.
Parameters:
-
data(InDataType) –the data to embed.
Source code in qoolqit/embedding/base_embedder.py
def embed(self, data: InDataType) -> OutDataType: """Validates the input, runs the embedding algorithm, and validates the output.
Arguments: data: the data to embed. """ self.validate_input(data) result: OutDataType = self.algorithm(data, **self.config.dict()) self.validate_output(result) return result
validate_input
abstractmethod
Section titled “
validate_input
abstractmethod
”validate_input(data: InDataType) -> NoneChecks if the given data is compatible with the embedder.
Each embedder should write its own data validator. If the data is not of the supported type or in the specific supported format for that embedder, an error should be raised.
Parameters:
-
data(InDataType) –the data to validate.
Raises:
-
TypeError–if the data is not of the supported type.
-
SomeError–some other error if other constraints are not met.
Source code in qoolqit/embedding/base_embedder.py
@abstractmethoddef validate_input(self, data: InDataType) -> None: """Checks if the given data is compatible with the embedder.
Each embedder should write its own data validator. If the data is not of the supported type or in the specific supported format for that embedder, an error should be raised.
Arguments: data: the data to validate.
Raises: TypeError: if the data is not of the supported type. SomeError: some other error if other constraints are not met. """ ...
validate_output
abstractmethod
Section titled “
validate_output
abstractmethod
”validate_output(result: OutDataType) -> NoneChecks if the resulting output is expected by the embedder.
Each embedder should write its own output validator. If the result is not of the supported type or in the specific supported format for that embedder, an error should be raised.
Parameters:
-
result(OutDataType) –the output to validate.
Raises:
-
TypeError–if the output is not of the supported type.
-
SomeError–some other error if other constraints are not met.
Source code in qoolqit/embedding/base_embedder.py
@abstractmethoddef validate_output(self, result: OutDataType) -> None: """Checks if the resulting output is expected by the embedder.
Each embedder should write its own output validator. If the result is not of the supported type or in the specific supported format for that embedder, an error should be raised.
Arguments: result: the output to validate.
Raises: TypeError: if the output is not of the supported type. SomeError: some other error if other constraints are not met. """ ...
Blade
Section titled “
Blade
”Blade(config: BladeConfig
dataclass (qoolqit.embedding.algorithms.BladeConfig)" href="./#qoolqit.embedding.BladeConfig">BladeConfig | None = None)A matrix to graph embedder using the BLaDE algorithm.
Parameters:
-
config(BladeConfig, default:None) –configuration object for the BLaDE algorithm.
Methods:
-
embed–Return a DataGraph with coordinates that embeds the input matrix.
Attributes:
-
algorithm(Callable) –Returns the callable to the embedding algorithm.
-
config(ConfigType) –Returns the config for the embedding algorithm.
-
info(str) –Prints info about the embedding algorithm.
Source code in qoolqit/embedding/matrix_embedder.py
def __init__(self, config: BladeConfig | None = None) -> None: """Inits Blade.
Args: config (BladeConfig): configuration object for the BLaDE algorithm. """ super().__init__(_blade, config=config or BladeConfig())
algorithm
property
Section titled “
algorithm
property
”algorithm: CallableReturns the callable to the embedding algorithm.
config
property
Section titled “
config
property
”config: ConfigTypeReturns the config for the embedding algorithm.
info
property
Section titled “
info
property
”info: strPrints info about the embedding algorithm.
embed
Section titled “
embed
”embed(data: ndarray) -> DataGraph (qoolqit.graphs.DataGraph)" href="../graphs/#qoolqit.graphs.DataGraph">DataGraphReturn a DataGraph with coordinates that embeds the input matrix.
Validates the input, runs the embedding algorithm, and validates the output.
Parameters:
-
data(ndarray) –the matrix to embed into a DataGraph with coordinates.
Source code in qoolqit/embedding/matrix_embedder.py
def embed(self, data: np.ndarray) -> DataGraph: """Return a DataGraph with coordinates that embeds the input matrix.
Validates the input, runs the embedding algorithm, and validates the output.
Args: data (np.ndarray): the matrix to embed into a DataGraph with coordinates. """ self.validate_input(data) positions = self.algorithm(data, **self.config.dict()) graph = DataGraph.from_coordinates(positions.tolist()) return graph
BladeConfig
dataclass
Section titled “
BladeConfig
dataclass
”BladeConfig( max_min_dist_ratio: float | None = None, dimensions: tuple[int, ...] = default_dimensions, starting_positions: ndarray | None = None, pca: bool = default_pca, steps_per_round: int = default_steps_per_round, compute_weight_relative_threshold: Callable[ [float], float ] = default_compute_weight_relative_threshold, compute_max_distance_to_walk: Callable[ [float, float], float | tuple[float, float, float] ] = default_compute_max_distance_to_walk, compute_regulation_cursor: Callable[ [float], float ] = default_compute_regulation_cursor, compute_ratio_step_factors: Callable[ [float], float ] = default_compute_ratio_step_factors, ratio_rerun: int = default_ratio_rerun, device: InitVar[ Device (qoolqit.devices.device.Device)" href="../devices/#qoolqit.devices.Device">Device | None] = None,)Configuration parameters to embed with BLaDE.
-
API reference
qoolqit.embedding
embeddingBlade
Methods:
-
__post_init__–Post initialization of the
BladeConfigdataclass. -
dict–Returns the dataclass as a dictionary.
Attributes:
-
compute_max_distance_to_walk(Callable[[float, float], float | tuple[float, float, float]]) –Function that is called at each step.
-
compute_ratio_step_factors(Callable[[float], float]) –Function that is called at the boundaries of the rounds.
-
compute_regulation_cursor(Callable[[float], float]) –Function that is called at each step.
-
compute_weight_relative_threshold(Callable[[float], float]) –Function that is called at each step.
-
dimensions(tuple[int, ...]) –List of numbers of dimensions to explore one after the other.
-
max_min_dist_ratio(float | None) –If present, sets the maximum radial-to-pairwise distance ratio.
-
pca(bool) –Whether to apply Principal Component Analysis to prioritize dimensions to keep.
-
ratio_rerun(int) –Maximum number of retries when the distance ratio constraint is not met.
-
starting_positions(ndarray | None) –If provided, initial positions to start from.
-
steps_per_round(int) –Number of elementary steps to perform for each dimension transition.
compute_max_distance_to_walk
class-attribute
instance-attribute
Section titled “
compute_max_distance_to_walk
class-attribute
instance-attribute
”compute_max_distance_to_walk: Callable[ [float, float], float | tuple[float, float, float]] = default_compute_max_distance_to_walkFunction that is called at each step.
It takes a float number between 0 and 1 that represents the progress
on the steps, and takes another argument that is set to the current
largest pairwise distance when max_min_dist_ratio is not enabled,
otherwise, it is set to the maximum radial distance for the current
step. It must return a float number that limits the distances
nodes can move at one step (see update_positions to learn more).
compute_ratio_step_factors
class-attribute
instance-attribute
Section titled “
compute_ratio_step_factors
class-attribute
instance-attribute
”compute_ratio_step_factors: Callable[[float], float] = ( default_compute_ratio_step_factors)Function that is called at the boundaries of the rounds.
It defines the target ratio to enforce during the evolution. It acts as a multiplying factor on the target ratio.
compute_regulation_cursor
class-attribute
instance-attribute
Section titled “
compute_regulation_cursor
class-attribute
instance-attribute
”compute_regulation_cursor: Callable[[float], float] = ( default_compute_regulation_cursor)Function that is called at each step.
It takes a float number between 0 and 1 that represents the progress on the steps. It must return a float number between 0 (no regulation) and 1 (full regulation) that uniformizes the ability for the forces to achieve their objectives at each step by changing priorities.
compute_weight_relative_threshold
class-attribute
instance-attribute
Section titled “
compute_weight_relative_threshold
class-attribute
instance-attribute
”compute_weight_relative_threshold: Callable[ [float], float] = default_compute_weight_relative_thresholdFunction that is called at each step.
It takes a float number between 0 and 1 that represents the progress
on the steps. It must return a float number between 0 and 1 that gives
a threshold determining which weights are significant (see
update_positions to learn more).
dimensions
class-attribute
instance-attribute
Section titled “
dimensions
class-attribute
instance-attribute
”dimensions: tuple[int, ...] = default_dimensionsList of numbers of dimensions to explore one after the other.
A list with one value is equivalent to a list containing twice the same value. For a 2D embedding, the last value should be 2. Increasing the number of intermediate dimensions can help to escape from local minima.
max_min_dist_ratio
class-attribute
instance-attribute
Section titled “
max_min_dist_ratio
class-attribute
instance-attribute
”max_min_dist_ratio: float | None = NoneIf present, sets the maximum radial-to-pairwise distance ratio.
Bounds the ratio between the maximum radial distance and the minimum pairwise distances.
pca
class-attribute
instance-attribute
Section titled “
pca
class-attribute
instance-attribute
”pca: bool = default_pcaWhether to apply Principal Component Analysis to prioritize dimensions to keep.
Applies when transitioning from a space to a space with fewer dimensions. It is disabled by default because it can raise an error when there are too many dimensions compared to the number of nodes.
ratio_rerun
class-attribute
instance-attribute
Section titled “
ratio_rerun
class-attribute
instance-attribute
”ratio_rerun: int = default_ratio_rerunMaximum number of retries when the distance ratio constraint is not met.
Defines how many additional computation steps the algorithm performs, putting priority on satisfying the constraint.
starting_positions
class-attribute
instance-attribute
Section titled “
starting_positions
class-attribute
instance-attribute
”starting_positions: ndarray | None = NoneIf provided, initial positions to start from.
Otherwise, random positions will be generated. The number of dimensions of the starting positions must be lower than or equal to the first dimension to explore. If it is lower, it is added dimensions filled with random values.
steps_per_round
class-attribute
instance-attribute
Section titled “
steps_per_round
class-attribute
instance-attribute
”steps_per_round: int = default_steps_per_roundNumber of elementary steps to perform for each dimension transition.
At each step, move vectors are computed and applied on the nodes.
__post_init__
Section titled “
__post_init__
”__post_init__(device: Device (qoolqit.devices.device.Device)" href="../devices/#qoolqit.devices.Device">Device | None) -> NonePost initialization of the BladeConfig dataclass.
Set the max_min_dist_ratio argument of the blade_embedding algorithm
based on the specification of the selected device.
Parameters:
-
device(Device) –the QoolQit device to use to set the maximum ratio between the maximum radial distance and the minimum pairwise distance between atoms.
Source code in qoolqit/embedding/algorithms/blade/blade.py
def __post_init__(self, device: Device | None) -> None: """Post initialization of the `BladeConfig` dataclass.
Set the `max_min_dist_ratio` argument of the `blade_embedding` algorithm based on the specification of the selected device.
Args: device (Device): the QoolQit device to use to set the maximum ratio between the maximum radial distance and the minimum pairwise distance between atoms. """ if device: if self.max_min_dist_ratio: logger.warning( "`max_min_dist_ratio` and `device` attributes should not be set simultaneously." ) min_distance = device._min_distance max_radial_distance = device._max_radial_distance if max_radial_distance and min_distance: self.max_min_dist_ratio = max_radial_distance / min_distancedict() -> dict (qoolqit.embedding.base_embedder.EmbedderConfig.dict)" href="./#qoolqit.embedding.BladeConfig.dict">dictReturns the dataclass as a dictionary.
Source code in qoolqit/embedding/base_embedder.py
def dict(self) -> dict: """Returns the dataclass as a dictionary.""" return asdict(self)
EmbedderConfig
dataclass
Section titled “
EmbedderConfig
dataclass
”EmbedderConfig()Base dataclass for all embedding algorithm configurations.
Subclasses define parameters specific to their algorithms. Each config should define fields that directly translate to arguments in the respective embedding function it configures.
Methods:
-
dict–Returns the dataclass as a dictionary.
dict() -> dict (qoolqit.embedding.base_embedder.EmbedderConfig.dict)" href="./#qoolqit.embedding.BladeConfig.dict">dictReturns the dataclass as a dictionary.
Source code in qoolqit/embedding/base_embedder.py
def dict(self) -> dict: """Returns the dataclass as a dictionary.""" return asdict(self)
GraphToGraphEmbedder
Section titled “
GraphToGraphEmbedder
”GraphToGraphEmbedder( algorithm: Callable, config: ConfigType)A family of embedders that map a graph to a graph.
Focused on unit-disk graph embedding, where the goal is to find a set of coordinates for a graph that has no coordinates, such that the final unit-disk edges matches the set of edges in the original graph.
A custom algorithm and configuration can be set at initialization.
An algorithm should be a standalone function that takes a piece of data of an InDataType and maps it to an OutDataType. Any extra configuration parameters taken as input by the algorithm function should be defined in the config dataclass, inheriting from EmbedderConfig.
Parameters:
-
algorithm(Callable) –a callable to the algorithm function.
-
config(ConfigType) –a config dataclass holding parameter values for the algorithm.
Methods:
-
embed–Validates the input, runs the embedding algorithm, and validates the output.
Attributes:
-
algorithm(Callable) –Returns the callable to the embedding algorithm.
-
config(ConfigType) –Returns the config for the embedding algorithm.
-
info(str) –Prints info about the embedding algorithm.
Source code in qoolqit/embedding/base_embedder.py
def __init__(self, algorithm: Callable, config: ConfigType) -> None: """Default initializer for all embedders, taking an algorithm and a config.
An algorithm should be a standalone function that takes a piece of data of an InDataType and maps it to an OutDataType. Any extra configuration parameters taken as input by the algorithm function should be defined in the config dataclass, inheriting from EmbedderConfig.
Arguments: algorithm: a callable to the algorithm function. config: a config dataclass holding parameter values for the algorithm. """ if not isinstance(config, EmbedderConfig): raise TypeError( "The config must be an instance of a dataclass inheriting from EmbedderConfig." )
algo_signature = inspect.signature(algorithm) config_keys = set(config.dict().keys()) algo_signature_keys = set(algo_signature.parameters.keys()) if not config_keys <= algo_signature_keys: config_keys_str = "\n".join(f"\t- {key}" for key in config_keys) algo_keys_str = "\n".join(f"\t- {key}" for key in algo_signature_keys) raise TypeError( f"Config {config.__class__.__name__} is not compatible with the " + f"algorithm {algorithm.__name__}, as not all configuration fields " + "correspond to keyword arguments in the algorithm function.\n\n" + f"Config {config.__class__.__name__} keys:\n{config_keys_str}\n\n" + f"Algorithm signature parameters:\n{algo_keys_str}" )
self._algorithm = algorithm self._config = config
algorithm
property
Section titled “
algorithm
property
”algorithm: CallableReturns the callable to the embedding algorithm.
config
property
Section titled “
config
property
”config: ConfigTypeReturns the config for the embedding algorithm.
info
property
Section titled “
info
property
”info: strPrints info about the embedding algorithm.
embed
Section titled “
embed
”embed(data: InDataType) -> OutDataTypeValidates the input, runs the embedding algorithm, and validates the output.
Parameters:
-
data(InDataType) –the data to embed.
Source code in qoolqit/embedding/base_embedder.py
def embed(self, data: InDataType) -> OutDataType: """Validates the input, runs the embedding algorithm, and validates the output.
Arguments: data: the data to embed. """ self.validate_input(data) result: OutDataType = self.algorithm(data, **self.config.dict()) self.validate_output(result) return result
InteractionEmbedder
Section titled “
InteractionEmbedder
”InteractionEmbedder( config: InteractionEmbedderConfig
dataclass (qoolqit.embedding.algorithms.InteractionEmbedderConfig)" href="./#qoolqit.embedding.InteractionEmbedderConfig">InteractionEmbedderConfig | None = None,)A matrix to graph embedder using the interaction embedding algorithm.
Starting positions are random unless x0 is set in the config. For reproducible
results, set seed to an integer:
import numpy as npfrom qoolqit.embedding import InteractionEmbedder, InteractionEmbedderConfig
matrix = np.array([[0.0, 1.0, 0.5], [1.0, 0.0, 0.2], [0.5, 0.2, 0.0]])embedder = InteractionEmbedder(InteractionEmbedderConfig(seed=3083257284))graph = embedder.embed(matrix)Parameters:
-
config(InteractionEmbedderConfig | None, default:None) –configuration for the interaction embedding. Defaults are used if None.
Methods:
-
embed–Validates the input, runs the embedding algorithm, and validates the output.
Attributes:
-
algorithm(Callable) –Returns the callable to the embedding algorithm.
-
config(ConfigType) –Returns the config for the embedding algorithm.
-
info(str) –Prints info about the embedding algorithm.
Source code in qoolqit/embedding/matrix_embedder.py
def __init__(self, config: InteractionEmbedderConfig | None = None) -> None: """Inits InteractionEmbedder.
Args: config: configuration for the interaction embedding. Defaults are used if None. """ super().__init__(interaction_embedding, config=config or InteractionEmbedderConfig())
algorithm
property
Section titled “
algorithm
property
”algorithm: CallableReturns the callable to the embedding algorithm.
config
property
Section titled “
config
property
”config: ConfigTypeReturns the config for the embedding algorithm.
info
property
Section titled “
info
property
”info: strPrints info about the embedding algorithm.
embed
Section titled “
embed
”embed(data: InDataType) -> OutDataTypeValidates the input, runs the embedding algorithm, and validates the output.
Parameters:
-
data(InDataType) –the data to embed.
Source code in qoolqit/embedding/base_embedder.py
def embed(self, data: InDataType) -> OutDataType: """Validates the input, runs the embedding algorithm, and validates the output.
Arguments: data: the data to embed. """ self.validate_input(data) result: OutDataType = self.algorithm(data, **self.config.dict()) self.validate_output(result) return result
InteractionEmbedderConfig
dataclass
Section titled “
InteractionEmbedderConfig
dataclass
”InteractionEmbedderConfig( method: str = "Nelder-Mead", maxiter: int = 200000, tol: float = 1e-08, x0: ndarray | None = None, seed: int | None = None,)Configuration parameters for the interaction embedding.
Explicit initial positions, one (x, y) row per node:
import numpy as npfrom qoolqit.embedding import InteractionEmbedderConfig
x0 = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]])config = InteractionEmbedderConfig(x0=x0)Random initial positions with a fixed seed:
from qoolqit.embedding import InteractionEmbedderConfig
config = InteractionEmbedderConfig(seed=3083257284)Initial positions from an external seeded generator:
import numpy as npfrom qoolqit.embedding import InteractionEmbedderConfig
rng = np.random.default_rng(seed=2754767221)config = InteractionEmbedderConfig(x0=rng.random((5, 2)))Attributes:
-
method(str) –optimization method passed to
scipy.optimize.minimize. -
maxiter(int) –maximum number of optimizer iterations.
-
tol(float) –tolerance for termination.
-
x0(ndarray | None) –initial node positions, of shape (N, 2) for an N x N matrix. If None, positions are drawn uniformly in [0, 1), seeded by
seed. -
seed(int | None) –seed for the random initial positions, ignored if
x0is set. If None, results differ between runs.
-
API reference
qoolqit.embedding
embeddingInteractionEmbedder
Methods:
-
dict–Returns the dataclass as a dictionary.
dict() -> dict (qoolqit.embedding.base_embedder.EmbedderConfig.dict)" href="./#qoolqit.embedding.BladeConfig.dict">dictReturns the dataclass as a dictionary.
Source code in qoolqit/embedding/base_embedder.py
def dict(self) -> dict: """Returns the dataclass as a dictionary.""" return asdict(self)
MatrixToGraphEmbedder
Section titled “
MatrixToGraphEmbedder
”MatrixToGraphEmbedder( algorithm: Callable, config: ConfigType)A family of embedders that map a matrix to a graph.
A custom algorithm and configuration can be set at initialization.
An algorithm should be a standalone function that takes a piece of data of an InDataType and maps it to an OutDataType. Any extra configuration parameters taken as input by the algorithm function should be defined in the config dataclass, inheriting from EmbedderConfig.
Parameters:
-
algorithm(Callable) –a callable to the algorithm function.
-
config(ConfigType) –a config dataclass holding parameter values for the algorithm.
Methods:
-
embed–Validates the input, runs the embedding algorithm, and validates the output.
Attributes:
-
algorithm(Callable) –Returns the callable to the embedding algorithm.
-
config(ConfigType) –Returns the config for the embedding algorithm.
-
info(str) –Prints info about the embedding algorithm.
Source code in qoolqit/embedding/base_embedder.py
def __init__(self, algorithm: Callable, config: ConfigType) -> None: """Default initializer for all embedders, taking an algorithm and a config.
An algorithm should be a standalone function that takes a piece of data of an InDataType and maps it to an OutDataType. Any extra configuration parameters taken as input by the algorithm function should be defined in the config dataclass, inheriting from EmbedderConfig.
Arguments: algorithm: a callable to the algorithm function. config: a config dataclass holding parameter values for the algorithm. """ if not isinstance(config, EmbedderConfig): raise TypeError( "The config must be an instance of a dataclass inheriting from EmbedderConfig." )
algo_signature = inspect.signature(algorithm) config_keys = set(config.dict().keys()) algo_signature_keys = set(algo_signature.parameters.keys()) if not config_keys <= algo_signature_keys: config_keys_str = "\n".join(f"\t- {key}" for key in config_keys) algo_keys_str = "\n".join(f"\t- {key}" for key in algo_signature_keys) raise TypeError( f"Config {config.__class__.__name__} is not compatible with the " + f"algorithm {algorithm.__name__}, as not all configuration fields " + "correspond to keyword arguments in the algorithm function.\n\n" + f"Config {config.__class__.__name__} keys:\n{config_keys_str}\n\n" + f"Algorithm signature parameters:\n{algo_keys_str}" )
self._algorithm = algorithm self._config = config
algorithm
property
Section titled “
algorithm
property
”algorithm: CallableReturns the callable to the embedding algorithm.
config
property
Section titled “
config
property
”config: ConfigTypeReturns the config for the embedding algorithm.
info
property
Section titled “
info
property
”info: strPrints info about the embedding algorithm.
embed
Section titled “
embed
”embed(data: InDataType) -> OutDataTypeValidates the input, runs the embedding algorithm, and validates the output.
Parameters:
-
data(InDataType) –the data to embed.
Source code in qoolqit/embedding/base_embedder.py
def embed(self, data: InDataType) -> OutDataType: """Validates the input, runs the embedding algorithm, and validates the output.
Arguments: data: the data to embed. """ self.validate_input(data) result: OutDataType = self.algorithm(data, **self.config.dict()) self.validate_output(result) return result
SpringLayoutConfig
dataclass
Section titled “
SpringLayoutConfig
dataclass
”SpringLayoutConfig( iterations: int = 100, threshold: float = 0.0001, seed: int | None = None,)Configuration parameters for the spring-layout embedding.
-
API reference
qoolqit.embedding
embeddingSpringLayoutEmbedder
Methods:
-
dict–Returns the dataclass as a dictionary.
dict() -> dict (qoolqit.embedding.base_embedder.EmbedderConfig.dict)" href="./#qoolqit.embedding.BladeConfig.dict">dictReturns the dataclass as a dictionary.
Source code in qoolqit/embedding/base_embedder.py
def dict(self) -> dict: """Returns the dataclass as a dictionary.""" return asdict(self)
SpringLayoutEmbedder
Section titled “
SpringLayoutEmbedder
”SpringLayoutEmbedder( config: SpringLayoutConfig
dataclass (qoolqit.embedding.algorithms.SpringLayoutConfig)" href="./#qoolqit.embedding.SpringLayoutConfig">SpringLayoutConfig | None = None,)A graph to graph embedder using the spring layout algorithm.
Methods:
-
embed–Validates the input, runs the embedding algorithm, and validates the output.
Attributes:
-
algorithm(Callable) –Returns the callable to the embedding algorithm.
-
config(ConfigType) –Returns the config for the embedding algorithm.
-
info(str) –Prints info about the embedding algorithm.
Source code in qoolqit/embedding/graph_embedder.py
def __init__(self, config: SpringLayoutConfig | None = None) -> None: """Inits SpringLayoutEmbedder.""" super().__init__(spring_layout_embedding, config=config or SpringLayoutConfig())
algorithm
property
Section titled “
algorithm
property
”algorithm: CallableReturns the callable to the embedding algorithm.
config
property
Section titled “
config
property
”config: ConfigTypeReturns the config for the embedding algorithm.
info
property
Section titled “
info
property
”info: strPrints info about the embedding algorithm.
embed
Section titled “
embed
”embed(data: InDataType) -> OutDataTypeValidates the input, runs the embedding algorithm, and validates the output.
Parameters:
-
data(InDataType) –the data to embed.
Source code in qoolqit/embedding/base_embedder.py
def embed(self, data: InDataType) -> OutDataType: """Validates the input, runs the embedding algorithm, and validates the output.
Arguments: data: the data to embed. """ self.validate_input(data) result: OutDataType = self.algorithm(data, **self.config.dict()) self.validate_output(result) return result