Source code for quantum_launcher.problems.problem_initialization.raw
1""" This module contains the Raw class."""
2from typing import Any
3
4import numpy as np
5from qiskit.quantum_info import SparsePauliOp
6
7from quantum_launcher.base import Problem, formatter
8
9
[docs]
10class Raw(Problem):
11 """ Meta class for raw problem """
12 __cached_classes__: dict[str, type] = {}
13
14 @staticmethod
15 def _cache_class(problem_type: str):
16 if problem_type in Raw.__cached_classes__:
17 return Raw.__cached_classes__[problem_type]
18
19 cls = type(problem_type, (Raw, ), {})
20 formatter(cls, problem_type)(_raw_formatter)
21 Raw.__cached_classes__[problem_type] = cls
22 return cls
23
24 @staticmethod
25 def _auto_map_problem(obj: Any) -> str:
26 """Automatically maps obj into str.
27
28 Args:
29 obj (Any): obj of some problem class.
30
31 Returns:
32 str: name of problem class that obj is in.
33 """
34 if isinstance(obj, SparsePauliOp):
35 return 'hamiltonian'
36 if isinstance(obj, tuple) and len(obj) == 2 and \
37 isinstance(obj[0], np.ndarray) and isinstance(obj[1], (int, float)):
38 return 'qubo'
39 try:
40 from dimod.binary.binary_quadratic_model import BinaryQuadraticModel
41 if isinstance(obj, BinaryQuadraticModel):
42 return 'bqm'
43 except ImportError:
44 pass
45 return 'none'
46
47 def __new__(cls, instance: Any, instance_name: str = 'Raw'):
48 if cls is not Raw:
49 return super().__new__(cls)
50 problem_type = cls._auto_map_problem(instance)
51 true_cls = cls._cache_class(problem_type)
52 return true_cls(instance, instance_name)
53
54
55def _raw_formatter(raw: Raw) -> Any:
56 return raw.instance