示例#1
0
文件: function.py 项目: BQSKit/bqskit
    def __call__(self, params: Sequence[float] | np.ndarray) -> float:
        """Return the cost value given the input parameters."""

        if not is_sequence(params):
            raise TypeError(
                'Expected sequence for params, got %s.' % type(params), )

        if not all(is_real_number(param) for param in params):
            raise TypeError('Expected sequence of floats for params.', )

        return self.get_cost(params)
示例#2
0
文件: astar.py 项目: BQSKit/bqskit
    def __init__(
        self,
        heuristic_factor: float = 10.0,
        cost_factor: float = 1.0,
        cost_gen: CostFunctionGenerator = HilbertSchmidtCostGenerator(),
    ) -> None:
        """
        Construct a AStarHeuristic Function.

        Args:
            heuristic_factor (float): Scale the heuristic component by
                this value.

            cost_factor (float): Scale the cost component by this value.

            cost_gen (CostFunctionGenerator): This is used to generate
                cost functions used during evaluations.
        """
        if not is_real_number(heuristic_factor):
            raise TypeError(
                'Expected float for heuristic_factor, got %s.' %
                type(heuristic_factor), )

        if not is_real_number(cost_factor):
            raise TypeError(
                'Expected float for cost_factor, got %s.' %
                type(cost_factor), )

        if not isinstance(cost_gen, CostFunctionGenerator):
            raise TypeError(
                'Expected CostFunctionGenerator for cost_gen, got %s.' %
                type(cost_gen), )

        self.heuristic_factor = heuristic_factor
        self.cost_factor = cost_factor
        self.cost_gen = cost_gen
示例#3
0
    def __call__(  # type: ignore
        self,
        params: Sequence[float] | np.ndarray,
    ) -> np.ndarray:
        """Return the vector of residuals given the input parameters."""

        if not is_sequence(params):
            raise TypeError(
                'Expected sequence for params, got %s.' % type(params),
            )

        if not all(is_real_number(param) for param in params):
            raise TypeError(
                'Expected sequence of floats for params.',
            )

        return self.get_residuals(params)
示例#4
0
    def __init__(
        self,
        heuristic_function: HeuristicFunction = AStarHeuristic(),
        layer_generator: LayerGenerator = SimpleLayerGenerator(),
        success_threshold: float = 1e-10,
        cost: CostFunctionGenerator = HilbertSchmidtResidualsGenerator(),
        max_layer: int | None = None,
        min_prefix_size: int = 3,
        instantiate_options: dict[str, Any] = {},
        **kwargs: Any,
    ) -> None:
        """
        Construct a search-based synthesis pass.

        Args:
            heuristic_function (HeuristicFunction): The heuristic to guide
                search.

            layer_generator (LayerGenerator): The successor function
                to guide node expansion.

            success_threshold (float): The distance threshold that
                determines successful termintation. Measured in cost
                described by the cost function. (Default: 1e-10)

            cost (CostFunction | None): The cost function that determines
                distance during synthesis. The goal of this synthesis pass
                is to implement circuits for the given unitaries that have
                a cost less than the `success_threshold`.
                (Default: HSDistance())

            max_layer (int): The maximum number of layers to append without
                success before termination. If left as None it will default
                 to unlimited. (Default: None)

            min_prefix_size (int): The minimum number of layers needed
                to prefix the circuit.

            instantiate_options (dict[str: Any]): Options passed directly
                to circuit.instantiate when instantiating circuit
                templates. (Default: {})

            kwargs (dict[str, Any]): Keyword arguments that are passed
                directly to SynthesisPass's constructor. See SynthesisPass
                for more info.

        Raises:
            ValueError: If `max_depth` or `min_prefix_size` is nonpositive.
        """
        if not isinstance(heuristic_function, HeuristicFunction):
            raise TypeError(
                'Expected HeursiticFunction, got %s.' %
                type(heuristic_function), )

        if not isinstance(layer_generator, LayerGenerator):
            raise TypeError(
                'Expected LayerGenerator, got %s.' % type(layer_generator), )

        if not is_real_number(success_threshold):
            raise TypeError(
                'Expected real number for success_threshold'
                ', got %s' % type(success_threshold), )

        if not isinstance(cost, CostFunctionGenerator):
            raise TypeError(
                'Expected cost to be a CostFunctionGenerator, got %s' %
                type(cost), )

        if max_layer is not None and not is_integer(max_layer):
            raise TypeError(
                'Expected max_layer to be an integer, got %s' %
                type(max_layer), )

        if max_layer is not None and max_layer <= 0:
            raise ValueError(
                'Expected max_layer to be positive, got %d.' %
                int(max_layer), )

        if min_prefix_size is not None and not is_integer(min_prefix_size):
            raise TypeError(
                'Expected min_prefix_size to be an integer, got %s' %
                type(min_prefix_size), )

        if min_prefix_size is not None and min_prefix_size <= 0:
            raise ValueError(
                'Expected min_prefix_size to be positive, got %d.' %
                int(min_prefix_size), )

        if not isinstance(instantiate_options, dict):
            raise TypeError(
                'Expected dictionary for instantiate_options, got %s.' %
                type(instantiate_options), )

        self.heuristic_function = heuristic_function
        self.layer_gen = layer_generator
        self.success_threshold = success_threshold
        self.cost = cost
        self.max_layer = max_layer
        self.min_prefix_size = min_prefix_size
        self.instantiate_options: dict[str, Any] = {'cost_fn_gen': self.cost}
        self.instantiate_options.update(instantiate_options)
        super().__init__(**kwargs)
示例#5
0
    def __init__(
        self,
        block_size_start: int = 2,
        block_size_limit: int | None = None,
        fail_limit: int = 3,
        success_threshold: float = 1e-6,
        progress_threshold_r: float = 5e-2,
        progress_threshold_a: float = 1e-4,
        cost: CostFunctionGenerator = HilbertSchmidtResidualsGenerator(),
        max_depth: int | None = None,
        instantiate_options: dict[str, Any] = {},
        **kwargs: dict[str, Any],
    ) -> None:
        """
        QPredictDecompositionPass Constructor.

        Args:
            block_size_start (int): The smallest block size to append
                each step. (Default: 2)

            block_size_limit (int | None): The largest block size to append
                each step. If left as None, the unitary being synthesized
                provides the limit. (Default: None)

            fail_limit (int): The amount of tries to make progress before
                increasing block size. (Default: 2)

            success_threshold (float): The distance threshold that
                determines successful termintation. Measured in cost
                described by the cost function. (Default: 1e-6)

            progress_threshold (float): The distance necessary to improve
                for the synthesis algorithm to complete a layer and move
                on. Lowering this will led to synthesis going deeper quicker,
                and raising it will force to algorithm to spend more time
                on each layer. Caution, changing this too much might break
                the synthesis algorithm. (Default: 5e-3)

            cost (CostFunction | None): The cost function that determines
                distance during synthesis. The goal of this synthesis pass
                is to implement circuits for the given unitaries that have
                a cost less than the `success_threshold`.
                (Default: HSDistance())

            max_depth (int): The maximum number of gates to append without
                success before termination. If left as None it will default
                 to unlimited. (Default: None)

            instantiate_options (dict[str: Any]): Options passed directly
                to circuit.instantiate when instantiating circuit
                templates. (Default: {})

            kwargs (dict[str, Any]): Keyword arguments that are passed
                directly to SynthesisPass's constructor. See SynthesisPass
                for more info.

        Raises:
            ValueError: If `block_size_start` is nonpositive.

            ValueError: If `block_size_limit` is less than `block_size_start`.

            ValueError: If `fail_limit` is nonpositive.

            ValueError: If `max_depth` is nonpositive.
        """

        if not is_integer(block_size_start):
            raise TypeError(
                'Expected block_size_start to be an integer, got %s' %
                type(block_size_start), )

        if block_size_start <= 0:
            raise ValueError(
                'Expected block_size_start to be positive, got %d.' %
                block_size_start, )

        if block_size_limit is not None and not is_integer(block_size_limit):
            raise TypeError(
                'Expected block_size_limit to be an integer, got %s' %
                type(block_size_limit), )

        if block_size_limit is not None and block_size_limit < block_size_start:
            raise ValueError(
                'Expected block_size_limit to be larger than block_size_start,'
                'got %d.' % block_size_limit, )

        if not is_integer(fail_limit):
            raise TypeError(
                'Expected fail_limit to be an integer, got %s' %
                type(fail_limit), )

        if fail_limit <= 0:
            raise ValueError(
                'Expected fail_limit to be positive, got %d.' % fail_limit, )

        if not is_real_number(success_threshold):
            raise TypeError(
                'Expected real number for success_threshold'
                ', got %s' % type(success_threshold), )

        if not is_real_number(progress_threshold_r):
            raise TypeError(
                'Expected real number for progress_threshold_r'
                ', got %s' % type(progress_threshold_r), )

        if not is_real_number(progress_threshold_a):
            raise TypeError(
                'Expected real number for progress_threshold_a'
                ', got %s' % type(progress_threshold_a), )

        if not isinstance(cost, CostFunctionGenerator):
            raise TypeError(
                'Expected cost to be a CostFunctionGenerator, got %s' %
                type(cost), )

        if max_depth is not None and not is_integer(max_depth):
            raise TypeError(
                'Expected max_depth to be an integer, got %s' %
                type(max_depth), )

        if max_depth is not None and max_depth <= 0:
            raise ValueError(
                'Expected max_depth to be positive, got %d.' %
                int(max_depth), )

        if not isinstance(instantiate_options, dict):
            raise TypeError(
                'Expected dictionary for instantiate_options, got %s.' %
                type(instantiate_options), )

        self.block_size_start = block_size_start
        self.block_size_limit = block_size_limit
        self.fail_limit = fail_limit
        self.success_threshold = success_threshold
        self.progress_threshold_r = progress_threshold_r
        self.progress_threshold_a = progress_threshold_a
        self.cost = cost
        self.max_depth = max_depth
        self.instantiate_options = {
            'min_iters': 25,
            'diff_tol_r': 1e-4,
        }
        self.instantiate_options.update(instantiate_options)
        super().__init__(**kwargs)  # type: ignore
示例#6
0
    def __init__(
        self,
        start_from_left: bool = True,
        success_threshold: float = 1e-10,
        cost: CostFunctionGenerator = HilbertSchmidtResidualsGenerator(),
        instantiate_options: dict[str, Any] = {},
        collection_filter: Callable[[Operation], bool] | None = None,
    ) -> None:
        """
        Construct a ScanningGateRemovalPass.

        Args:
            start_from_left (bool): Determines where the scan starts
                attempting to remove gates from. If True, scan goes left
                to right, otherwise right to left. (Default: True)

            success_threshold (float): The distance threshold that
                determines successful termintation. Measured in cost
                described by the hilbert schmidt cost function.
                (Default: 1e-10)

            cost (CostFunction | None): The cost function that determines
                successful removal of a gate.
                (Default: HilbertSchmidtResidualsGenerator())

            instantiate_options (dict[str: Any]): Options passed directly
                to circuit.instantiate when instantiating circuit
                templates. (Default: {})

            collection_filter (Callable[[Operation], bool] | None):
                A predicate that determines which operations should be
                attempted to be removed. Called with each operation
                in the circuit. If this returns true, this pass will
                attempt to remove that operation. Defaults to all
                operations.
        """

        if not is_real_number(success_threshold):
            raise TypeError(
                'Expected real number for success_threshold'
                ', got %s' % type(success_threshold), )

        if not isinstance(cost, CostFunctionGenerator):
            raise TypeError(
                'Expected cost to be a CostFunctionGenerator, got %s' %
                type(cost), )

        if not isinstance(instantiate_options, dict):
            raise TypeError(
                'Expected dictionary for instantiate_options, got %s.' %
                type(instantiate_options), )

        self.collection_filter = collection_filter or default_collection_filter

        if not callable(self.collection_filter):
            raise TypeError(
                'Expected callable method that maps Operations to booleans for'
                ' collection_filter, got %s.' % type(self.collection_filter), )

        self.start_from_left = start_from_left
        self.success_threshold = success_threshold
        self.cost = cost
        self.instantiate_options: dict[str, Any] = {
            'dist_tol': self.success_threshold,
            'min_iters': 100,
        }
        self.instantiate_options.update(instantiate_options)