Beispiel #1
0
def evaluate_operator_for_parameter_grid(
    ansatz_specs,
    backend_specs,
    grid,
    operator,
    fixed_parameters="None",
):

    ansatz = create_object(json.loads(ansatz_specs))
    backend = create_object(json.loads(backend_specs))

    grid = load_parameter_grid(grid)
    operator = load_qubit_operator(operator)

    if fixed_parameters != "None":
        if type(fixed_parameters) == str:
            if os.path.exists(fixed_parameters):
                fixed_parameters = load_circuit_template_params(fixed_parameters)
    else:
        fixed_parameters = []

    (
        parameter_grid_evaluation,
        optimal_parameters,
    ) = _evaluate_operator_for_parameter_grid(
        ansatz, grid, backend, operator, previous_layer_params=fixed_parameters
    )

    save_parameter_grid_evaluation(
        parameter_grid_evaluation, "parameter-grid-evaluation.json"
    )
    save_circuit_template_params(optimal_parameters, "/app/optimal-parameters.json")
Beispiel #2
0
    def test_build_uniform_param_grid_number_of_params_per_layer(
            self, number_of_params_per_layer, number_of_layers, min_value,
            max_value, step):
        # Given
        expected_parameter_grid_filename = "parameter-grid.json"
        expected_parameter_grid = _build_uniform_param_grid(
            number_of_params_per_layer,
            number_of_layers,
            min_value=min_value,
            max_value=max_value,
            step=step,
        )

        # When
        build_uniform_param_grid(
            number_of_params_per_layer=number_of_params_per_layer,
            number_of_layers=number_of_layers,
            min_value=min_value,
            max_value=max_value,
            step=step,
        )

        # Then
        try:
            parameter_grid = load_parameter_grid(
                expected_parameter_grid_filename)
            assert [tuple(param) for param in parameter_grid.param_ranges
                    ] == expected_parameter_grid.param_ranges
        finally:
            remove_file_if_exists(expected_parameter_grid_filename)
Beispiel #3
0
def evaluate_operator_for_parameter_grid(
    ansatz_specs: Specs,
    backend_specs: Specs,
    grid: Union[str, ParameterGrid],
    operator: Union[str, SymbolicOperator],
    fixed_parameters: Union[List[float], np.ndarray, str] = None,
):
    """Measure the expection values of the terms in an input operator with respect to the states prepared by the input
    ansatz circuits when set to the different parameters in the input parameter grid on the
    backend described by the backend_specs. The results are serialized into a JSON under the
    files: "parameter-grid-evaluation.json" and "optimal-parameters.json"

    ARGS:
        ansatz_specs (Union[dict, str]): The ansatz producing the parameterized quantum circuits
        backend_specs (Union[dict, str]): The backend on which to run the quantum circuit
        grid (Union[str, ParameterGrid]): The parameter grid describing the different ansatz parameters to use
        operator (Union[str, SymbolicOperator]): The operator to measure
        fixed_parameters (Union[List[float], np.ndarray, str]): Any fixed parameter values that the ansatz should be
            evaluated to that are not described by the parameter grid
    """
    if isinstance(ansatz_specs, str):
        ansatz_specs = json.loads(ansatz_specs)
    ansatz = create_object(ansatz_specs)

    if isinstance(backend_specs, str):
        backend_specs = json.loads(backend_specs)
    backend = create_object(backend_specs)

    if isinstance(grid, str):
        grid = load_parameter_grid(grid)
    if isinstance(operator, str):
        operator = load_qubit_operator(operator)

    if fixed_parameters is not None:
        if isinstance(fixed_parameters, str):
            fixed_parameters = load_circuit_template_params(fixed_parameters)
    else:
        fixed_parameters = []

    (
        parameter_grid_evaluation,
        optimal_parameters,
    ) = _evaluate_operator_for_parameter_grid(
        ansatz,
        grid,
        backend,
        operator,
        previous_layer_params=fixed_parameters)

    save_parameter_grid_evaluation(parameter_grid_evaluation,
                                   "parameter-grid-evaluation.json")
    save_circuit_template_params(optimal_parameters, "optimal-parameters.json")
Beispiel #4
0
    def test_build_uniform_param_grid_ansatz_specs_as_string(
        self,
        number_of_ansatz_layers,
        problem_size,
        number_of_layers,
        min_value,
        max_value,
        step,
    ):
        # Given
        expected_parameter_grid_filename = "parameter-grid.json"
        ansatz_specs = {
            "module_name": "zquantum.core.interfaces.mock_objects",
            "function_name": "MockAnsatz",
            "number_of_layers": number_of_ansatz_layers,
            "problem_size": problem_size,
        }
        ansatz = create_object(copy.deepcopy(ansatz_specs))
        expected_parameter_grid = _build_uniform_param_grid(
            ansatz.number_of_params,
            number_of_layers,
            min_value=min_value,
            max_value=max_value,
            step=step,
        )

        # When
        build_uniform_param_grid(
            ansatz_specs=json.dumps(ansatz_specs),
            number_of_layers=number_of_layers,
            min_value=min_value,
            max_value=max_value,
            step=step,
        )

        # Then
        try:
            parameter_grid = load_parameter_grid(
                expected_parameter_grid_filename)
            assert [tuple(param) for param in parameter_grid.param_ranges
                    ] == expected_parameter_grid.param_ranges
        finally:
            remove_file_if_exists(expected_parameter_grid_filename)
def optimize_variational_circuit(
    ansatz_specs,
    backend_specs,
    optimizer_specs,
    cost_function_specs,
    qubit_operator,
    initial_parameters="None",
    fixed_parameters="None",
    noise_model="None",
    device_connectivity="None",
    parameter_grid="None",
    constraint_operator="None",
):
    if initial_parameters != "None":
        initial_params = load_circuit_template_params(initial_parameters)
    else:
        initial_params = None

    if fixed_parameters != "None":
        fixed_params = load_circuit_template_params(fixed_parameters)
    else:
        fixed_params = None

    # Load qubit operator
    operator = load_qubit_operator(qubit_operator)

    if isinstance(ansatz_specs, str):
        ansatz_specs_dict = yaml.load(ansatz_specs, Loader=yaml.SafeLoader)
    else:
        ansatz_specs_dict = ansatz_specs
    if ansatz_specs_dict["function_name"] == "QAOAFarhiAnsatz":
        ansatz = create_object(ansatz_specs_dict, cost_hamiltonian=operator)
    else:
        ansatz = create_object(ansatz_specs_dict)

    # Load parameter grid
    if parameter_grid != "None":
        grid = load_parameter_grid(parameter_grid)
    else:
        grid = None

    # Load optimizer specs
    if isinstance(optimizer_specs, str):
        optimizer_specs_dict = yaml.load(optimizer_specs,
                                         Loader=yaml.SafeLoader)
    else:
        optimizer_specs_dict = optimizer_specs
    if (grid is not None and optimizer_specs_dict["function_name"]
            == "GridSearchOptimizer"):
        optimizer = create_object(optimizer_specs_dict, grid=grid)
    else:
        optimizer = create_object(optimizer_specs_dict)

    # Load backend specs
    if isinstance(backend_specs, str):
        backend_specs_dict = yaml.load(backend_specs, Loader=yaml.SafeLoader)
    else:
        backend_specs_dict = backend_specs
    if noise_model != "None":
        backend_specs_dict["noise_model"] = load_noise_model(noise_model)
    if device_connectivity != "None":
        backend_specs_dict["device_connectivity"] = load_circuit_connectivity(
            device_connectivity)
    backend = create_object(backend_specs_dict)

    # Load cost function specs
    if isinstance(cost_function_specs, str):
        cost_function_specs_dict = yaml.load(cost_function_specs,
                                             Loader=yaml.SafeLoader)
    else:
        cost_function_specs_dict = cost_function_specs
    estimator_specs = cost_function_specs_dict.pop("estimator-specs", None)
    if estimator_specs is not None:
        cost_function_specs_dict["estimator"] = create_object(estimator_specs)
    cost_function_specs_dict["target_operator"] = operator
    cost_function_specs_dict["ansatz"] = ansatz
    cost_function_specs_dict["backend"] = backend
    cost_function_specs_dict["fixed_parameters"] = fixed_params
    cost_function = create_object(cost_function_specs_dict)

    if constraint_operator != "None":
        constraint_op = load_qubit_operator(constraint_operator)
        constraints_cost_function_specs = yaml.load(cost_function_specs,
                                                    Loader=yaml.SafeLoader)
        constraints_estimator_specs = constraints_cost_function_specs.pop(
            "estimator-specs", None)
        if constraints_estimator_specs is not None:
            constraints_cost_function_specs["estimator"] = create_object(
                constraints_estimator_specs)
        constraints_cost_function_specs["ansatz"] = ansatz
        constraints_cost_function_specs["backend"] = backend
        constraints_cost_function_specs["target_operator"] = constraint_op
        constraint_cost_function = create_object(
            constraints_cost_function_specs)
        constraint_cost_function_wrapper = (
            lambda params: constraint_cost_function.evaluate(params).value)
        constraint_functions = ({
            "type": "eq",
            "fun": constraint_cost_function_wrapper
        }, )
        optimizer.constraints = constraint_functions

    opt_results = optimizer.minimize(cost_function, initial_params)

    save_optimization_results(opt_results, "optimization-results.json")
    save_circuit_template_params(opt_results.opt_params,
                                 "optimized-parameters.json")