def solve_relaxed_qubo( qubo, optimizer_specs=None, number_of_trials=10, symmetrize_matrix=True, ): qubo = load_qubo(qubo) qubo_matrix = qubo.to_numpy_matrix().astype(float) if symmetrize_matrix: qubo_matrix = (qubo_matrix + qubo_matrix.T) / 2 if is_matrix_positive_semidefinite(qubo_matrix): solution, optimal_value = solve_qp_problem_for_psd_matrix( qubo_matrix, symmetrize_matrix) else: if optimizer_specs is None: raise ValueError( "For qubo with semipositive definite matrix, an optimizer must be provided." ) optimizer = create_object(optimizer_specs) solution, optimal_value = solve_qp_problem_with_optimizer( qubo_matrix, optimizer, number_of_trials, symmetrize_matrix) save_list(solution.tolist(), "solution.json") save_value_estimate(ValueEstimate(optimal_value), "energy.json")
def get_evaluation_result(self, id): # make cost function result result = ValueEstimate(self.cost_func()) save_value_estimate(result, 'client_mock_evaluation_result.json') with open('client_mock_evaluation_result.json', 'r') as f: result_data = json.load(f) result_data["optimization-evaluation-id"] = "MOCKED-ID" return json.JSONEncoder().encode(result_data)
def test_post_result(self): connection = http.client.HTTPConnection(self.ipaddress+":"+str(self.listening_port), timeout=2) # POST argument values to allow proxy to verify that id that comes in with # result POST are correct params = np.random.random((2,2)) save_circuit_template_params(params, 'proxy_test_current_argument_values_artifact.json') with open('proxy_test_current_argument_values_artifact.json', 'r') as f: arg_val_data = json.load(f) # set status to be OPTIMIZING in order to POST argument values connection.request('POST', '/status', body="OPTIMIZING") response = connection.getresponse() self.assertEqual(response.getcode(), 204) # POST argument values connection.request('POST', '/cost-function-argument-values', body=json.JSONEncoder().encode(arg_val_data)) response = connection.getresponse() self.assertEqual(response.getcode(), 200) # decode id from response id_from_argument_value_post = response.read().decode("utf-8") # set status to be EVALUATING connection.request('POST', '/status', body="EVALUATING") response = connection.getresponse() self.assertEqual(response.getcode(), 204) # make cost function result result = ValueEstimate(1.5,10.0) save_value_estimate(result, 'proxy_test_results_artifact.json') with open('proxy_test_results_artifact.json', 'r') as f: result_data = json.load(f) result_data["optimization-evaluation-id"] = id_from_argument_value_post # POST cost function result connection.request('POST', '/cost-function-results', body=json.JSONEncoder().encode(result_data)) response = connection.getresponse() self.assertEqual(response.getcode(), 204) # GET cost function result connection.request('GET', '/cost-function-results', body=id_from_argument_value_post) response = connection.getresponse() self.assertEqual(response.getcode(), 200) # remove id from response and verify it is correct response_string = response.read().decode("utf-8") response_json = json.loads(response_string) response_id = response_json.pop("optimization-evaluation-id") self.assertEqual(id_from_argument_value_post, response_id) # assert result is same as above with open('proxy_test_results_artifact_from_proxy.json', 'w') as f: f.write(json.dumps(response_json)) new_data_loaded_from_file = load_value_estimate('proxy_test_results_artifact_from_proxy.json') self.assertEqual(result.value, new_data_loaded_from_file.value) self.assertEqual(result.precision, new_data_loaded_from_file.precision)
def jw_get_ground_state_at_particle_number(particle_number, qubit_operator): qubit_operator = load_qubit_operator(qubit_operator) sparse_matrix = qubit_operator_sparse(qubit_operator) ground_energy, ground_state_amplitudes = _jw_get_ground_state_at_particle_number( sparse_matrix, particle_number ) ground_state = Wavefunction(ground_state_amplitudes) value_estimate = ValueEstimate(ground_energy) save_wavefunction(ground_state, "ground-state.json") save_value_estimate(value_estimate, "value-estimate.json")
def get_summed_expectation_values( operator: str, measurements: str, use_bessel_correction: Optional[bool] = True): if isinstance(operator, str): operator = load_qubit_operator(operator) operator = change_operator_type(operator, openfermion.IsingOperator) if isinstance(measurements, str): measurements = Measurements.load_from_file(measurements) expectation_values = measurements.get_expectation_values( operator, use_bessel_correction=use_bessel_correction) value_estimate = sum_expectation_values(expectation_values) save_value_estimate(value_estimate, "value-estimate.json")
def evaluate_qubit_operator_list( qubit_operator_list: Union[str, List[QubitOperator]], expectation_values: Union[str, ExpectationValues], ): if isinstance(qubit_operator_list, str): qubit_operator_list = load_qubit_operator_set(qubit_operator_list) if isinstance(expectation_values, str): expectation_values = load_expectation_values(expectation_values) value_estimate = _evaluate_qubit_operator_list(qubit_operator_list, expectation_values) save_value_estimate(value_estimate, "value-estimate.json")
def solve_qubo(qubo, solver_specs, solver_params=None): """Solves qubo using any sampler implementing either dimod.Sampler or zquantum.qubo.BQMSolver""" if solver_params is None: solver_params = {} solver = create_object(solver_specs) qubo = load_qubo(qubo) sampleset = solver.sample(qubo, **solver_params) best_sample_dict = sampleset.first.sample solution_bitstring = tuple(best_sample_dict[i] for i in sorted(best_sample_dict)) lowest_energy = evaluate_bitstring_for_qubo(solution_bitstring, qubo) save_value_estimate(ValueEstimate(lowest_energy), "lowest-energy.json") Measurements([solution_bitstring]).save("solution.json") save_sampleset(sampleset, "sampleset.json")
def evaluate_ansatz_based_cost_function( ansatz_specs: Specs, backend_specs: Specs, cost_function_specs: Specs, ansatz_parameters: Specs, qubit_operator: str, noise_model: Optional[str] = None, device_connectivity: Optional[str] = None, prior_expectation_values: Optional[str] = None, ): ansatz_parameters = load_circuit_template_params(ansatz_parameters) # Load qubit op operator = load_qubit_operator(qubit_operator) if isinstance(ansatz_specs, str): ansatz_specs = json.loads(ansatz_specs) if ansatz_specs["function_name"] == "QAOAFarhiAnsatz": ansatz = create_object(ansatz_specs, cost_hamiltonian=operator) else: ansatz = create_object(ansatz_specs) if isinstance(backend_specs, str): backend_specs = json.loads(backend_specs) if noise_model is not None: backend_specs["noise_model"] = load_noise_model(noise_model) if device_connectivity is not None: backend_specs["device_connectivity"] = load_circuit_connectivity( device_connectivity) backend = create_object(backend_specs) if isinstance(cost_function_specs, str): cost_function_specs = json.loads(cost_function_specs) estimator_specs = cost_function_specs.pop("estimator-specs", None) if estimator_specs is not None: cost_function_specs["estimator"] = create_object(estimator_specs) cost_function_specs["target_operator"] = operator cost_function_specs["ansatz"] = ansatz cost_function_specs["backend"] = backend cost_function = create_object(cost_function_specs) if prior_expectation_values is not None: if isinstance(prior_expectation_values, str): cost_function.estimator.prior_expectation_values = load_expectation_values( prior_expectation_values) value_estimate = cost_function(ansatz_parameters) save_value_estimate(value_estimate, "value_estimate.json")
def test_unsuccessful_post_result_wrong_status(self): connection = http.client.HTTPConnection(self.ipaddress+":"+str(self.listening_port), timeout=2) # POST argument values to allow proxy to verify that argument values that come in with # Value POST are correct params = np.random.random((2,2)) save_circuit_template_params(params, 'proxy_test_current_argument_values_artifact.json') with open('proxy_test_current_argument_values_artifact.json', 'r') as f: arg_val_data = json.load(f) # set status to be OPTIMIZING in order to POST argument values connection.request('POST', '/status', body="OPTIMIZING") response = connection.getresponse() self.assertEqual(response.getcode(), 204) # POST argument values connection.request('POST', '/cost-function-argument-values', body=json.JSONEncoder().encode(arg_val_data)) response = connection.getresponse() self.assertEqual(response.getcode(), 200) # decode id from response id_from_argument_value_post = response.read().decode("utf-8") # set status to be EVALUATING connection.request('POST', '/status', body="EVALUATING") response = connection.getresponse() self.assertEqual(response.getcode(), 204) # make cost function result result = ValueEstimate(1.5,10.0) save_value_estimate(result, 'proxy_test_results_artifact.json') with open('proxy_test_results_artifact.json', 'r') as f: result_data = json.load(f) result_data["optimization-evaluation-id"] = id_from_argument_value_post # set status to be OPTIMIZING - new results should not be able to # be posted while that is the status connection.request('POST', '/status', body="OPTIMIZING") response = connection.getresponse() self.assertEqual(response.getcode(), 204) # POST cost function result connection.request('POST', '/cost-function-results', body=json.JSONEncoder().encode(result_data)) response = connection.getresponse() self.assertEqual(response.getcode(), 409) response_lower = response.read().decode("utf-8").lower() self.assertTrue(response_lower.find('error') != -1) self.assertTrue(response_lower.find('status') != -1) self.assertTrue(response_lower.find('evaluating') != -1)
def jw_get_ground_state_at_particle_number( particle_number: int, qubit_operator: Union[str, SymbolicOperator]): """Get the ground state wavefunction of the operator for the input particle number. Outputs are serialized to JSON within the files: "ground-state.json" and "value-estimate.json" ARGS: particle_number (int): The given number of particles in the system qubit_operator (Union[str, SymbolicOperator]): The operator for which to find the ground state """ if isinstance(qubit_operator, str): qubit_operator = load_qubit_operator(qubit_operator) sparse_matrix = qubit_operator_sparse(qubit_operator) ground_energy, ground_state_amplitudes = _jw_get_ground_state_at_particle_number( sparse_matrix, particle_number) ground_state = Wavefunction(ground_state_amplitudes) value_estimate = ValueEstimate(ground_energy) save_wavefunction(ground_state, "ground-state.json") save_value_estimate(value_estimate, "value-estimate.json")
def evaluate_ansatz_based_cost_function( ansatz_specs: str, backend_specs: str, cost_function_specs: str, ansatz_parameters: str, qubit_operator: str, noise_model="None", device_connectivity="None", ): ansatz_parameters = load_circuit_template_params(ansatz_parameters) # Load qubit op operator = load_qubit_operator(qubit_operator) ansatz_specs = json.loads(ansatz_specs) if ansatz_specs["function_name"] == "QAOAFarhiAnsatz": ansatz = create_object(ansatz_specs, cost_hamiltonian=operator) else: ansatz = create_object(ansatz_specs) backend_specs = json.loads(backend_specs) if noise_model != "None": backend_specs["noise_model"] = load_noise_model(noise_model) if device_connectivity != "None": backend_specs["device_connectivity"] = load_circuit_connectivity( device_connectivity) backend = create_object(backend_specs) cost_function_specs = json.loads(cost_function_specs) estimator_specs = cost_function_specs.pop("estimator-specs", None) if estimator_specs is not None: cost_function_specs["estimator"] = create_object(estimator_specs) cost_function_specs["target_operator"] = operator cost_function_specs["ansatz"] = ansatz cost_function_specs["backend"] = backend cost_function = create_object(cost_function_specs) value_estimate = cost_function(ansatz_parameters) save_value_estimate(value_estimate, "value_estimate.json")
def test_value_estimate_io(self): # Given value = -1.0 precision = 0.1 value_estimate_object = ValueEstimate(value, precision) # When save_value_estimate(value_estimate_object, "value_estimate.json") value_estimate_object_loaded = load_value_estimate( "value_estimate.json") # Then assert value_estimate_object.value == value_estimate_object_loaded.value assert value_estimate_object.precision == value_estimate_object_loaded.precision # Given value_estimate_object = ValueEstimate(value) # When save_value_estimate(value_estimate_object, "value_estimate.json") value_estimate_object_loaded = load_value_estimate( "value_estimate.json") # Then assert value_estimate_object.value == value_estimate_object_loaded.value assert value_estimate_object.precision == value_estimate_object_loaded.precision # Given value = np.float64(-1.0) precision = np.float64(0.1) value_estimate_object = ValueEstimate(value, precision) # When save_value_estimate(value_estimate_object, "value_estimate.json") value_estimate_object_loaded = load_value_estimate( "value_estimate.json") # Then assert value_estimate_object.value == value_estimate_object_loaded.value assert value_estimate_object.precision == value_estimate_object_loaded.precision remove_file_if_exists("value_estimate.json")
def evaluate_ansatz_based_cost_function( ansatz_specs: Specs, backend_specs: Specs, cost_function_specs: Specs, ansatz_parameters: str, target_operator: Union[str, openfermion.SymbolicOperator], estimation_method_specs: Optional[Specs] = None, estimation_preprocessors_specs: Optional[List[Specs]] = None, noise_model: Optional[str] = None, device_connectivity: Optional[str] = None, prior_expectation_values: Optional[str] = None, estimation_tasks_transformations_kwargs: Optional[Dict] = None, ): # Empty dict as default is bad if estimation_tasks_transformations_kwargs is None: estimation_tasks_transformations_kwargs = {} ansatz_parameters = load_array(ansatz_parameters) # Load qubit op if isinstance(target_operator, str): operator = load_qubit_operator(target_operator) else: operator = target_operator if isinstance(ansatz_specs, str): ansatz_specs = json.loads(ansatz_specs) if ansatz_specs["function_name"] == "QAOAFarhiAnsatz": ansatz = create_object(ansatz_specs, cost_hamiltonian=operator) else: ansatz = create_object(ansatz_specs) if isinstance(backend_specs, str): backend_specs = json.loads(backend_specs) if noise_model is not None: backend_specs["noise_model"] = load_noise_model(noise_model) if device_connectivity is not None: backend_specs["device_connectivity"] = layouts.load_circuit_connectivity( device_connectivity ) backend = create_object(backend_specs) if isinstance(cost_function_specs, str): cost_function_specs = json.loads(cost_function_specs) if ( "estimator-specs" in cost_function_specs.keys() or "estimation-tasks-transformations-specs" in cost_function_specs.keys() ): raise RuntimeError( "Estimation-related specs should be separate arguments and not in " "cost_function_specs" ) if prior_expectation_values is not None: if isinstance(prior_expectation_values, str): prior_expectation_values = load_expectation_values(prior_expectation_values) if estimation_method_specs is not None: if isinstance(estimation_method_specs, str): estimation_method_specs = json.loads(estimation_method_specs) estimation_method = create_object(estimation_method_specs) else: estimation_method = estimate_expectation_values_by_averaging cost_function_specs["estimation_method"] = estimation_method if estimation_preprocessors_specs is not None: cost_function_specs["estimation_preprocessors"] = [] for estimation_tasks_transformation_specs in estimation_preprocessors_specs: if isinstance(estimation_tasks_transformation_specs, str): estimation_tasks_transformation_specs = json.loads( estimation_tasks_transformation_specs ) if prior_expectation_values is not None: # Since we don't know which estimation task transformation uses # prior_expectation_values, we add it to the kwargs of each one. If not # used by a particular transformer, it will be ignored. estimation_tasks_transformation_specs[ "prior_expectation_values" ] = prior_expectation_values cost_function_specs["estimation_preprocessors"].append( create_object( estimation_tasks_transformation_specs, **estimation_tasks_transformations_kwargs ) ) # cost_function.estimator.prior_expectation_values cost_function_specs["target_operator"] = operator cost_function_specs["ansatz"] = ansatz cost_function_specs["backend"] = backend cost_function = create_object(cost_function_specs) value_estimate = cost_function(ansatz_parameters) save_value_estimate(value_estimate, "value_estimate.json")
def evaluate_ansatz_based_cost_function( ansatz_specs: Specs, backend_specs: Specs, cost_function_specs: Specs, ansatz_parameters: str, qubit_operator: str, noise_model: Optional[str] = None, device_connectivity: Optional[str] = None, prior_expectation_values: Optional[str] = None, ): ansatz_parameters = load_circuit_template_params(ansatz_parameters) # Load qubit op operator = load_qubit_operator(qubit_operator) if isinstance(ansatz_specs, str): ansatz_specs = json.loads(ansatz_specs) if ansatz_specs["function_name"] == "QAOAFarhiAnsatz": ansatz = create_object(ansatz_specs, cost_hamiltonian=operator) else: ansatz = create_object(ansatz_specs) if isinstance(backend_specs, str): backend_specs = json.loads(backend_specs) if noise_model is not None: backend_specs["noise_model"] = load_noise_model(noise_model) if device_connectivity is not None: backend_specs["device_connectivity"] = load_circuit_connectivity( device_connectivity) backend = create_object(backend_specs) if isinstance(cost_function_specs, str): cost_function_specs = json.loads(cost_function_specs) if prior_expectation_values is not None: if isinstance(prior_expectation_values, str): prior_expectation_values = load_expectation_values( prior_expectation_values) estimator_specs = cost_function_specs.pop("estimator-specs", None) if estimator_specs is not None: if isinstance(estimator_specs, str): estimator_specs = json.loads(estimator_specs) cost_function_specs["estimator"] = create_object(estimator_specs) estimation_preprocessors_specs = cost_function_specs.pop( "estimation-tasks-transformations-specs", None) if estimation_preprocessors_specs is not None: cost_function_specs["estimation_preprocessors"] = [] for estimation_tasks_transformation_specs in estimation_preprocessors_specs: if isinstance(estimation_tasks_transformation_specs, str): estimation_tasks_transformation_specs = json.loads( estimation_tasks_transformation_specs) if prior_expectation_values is not None: # Since we don't know which estimation task transformation uses prior_expectation_values, # we add it to the kwargs of each one. If not used by a particular transformer, it will be ignored. estimation_tasks_transformation_specs[ "prior_expectation_values"] = prior_expectation_values cost_function_specs["estimation_preprocessors"].append( create_object(estimation_tasks_transformation_specs)) # cost_function.estimator.prior_expectation_values cost_function_specs["target_operator"] = operator cost_function_specs["ansatz"] = ansatz cost_function_specs["backend"] = backend cost_function = create_object(cost_function_specs) value_estimate = cost_function(ansatz_parameters) save_value_estimate(value_estimate, "value_estimate.json")