Esempio n. 1
0
 def setUp(self):
     cfg_mgr = ConfigurationManager()
     hdf5_cfg = OrderedDict([
         ('hdf5_input', 'test/test_driver_hdf5.hdf5')
     ])
     section = {'properties': hdf5_cfg}
     driver = cfg_mgr.get_driver_instance('HDF5')
     self.qmolecule = driver.run(section)
Esempio n. 2
0
 def setUp(self):
     cfg_mgr = ConfigurationManager()
     pyscf_cfg = OrderedDict([('atom', 'H .0 .0 .0; H .0 .0 0.735'),
                              ('unit', 'Angstrom'), ('charge', 0),
                              ('spin', 0), ('basis', 'sto3g')])
     section = {'properties': pyscf_cfg}
     driver = cfg_mgr.get_driver_instance('PYSCF')
     self.qmolecule = driver.run(section)
 def setUp(self):
     cfg_mgr = ConfigurationManager()
     pyscf_cfg = OrderedDict([('atom', 'Li .0 .0 .0; H .0 .0 1.595'),
                              ('unit', 'Angstrom'), ('charge', 0),
                              ('spin', 0), ('basis', 'sto3g')])
     section = {}
     section['properties'] = pyscf_cfg
     driver = cfg_mgr.get_driver_instance('PYSCF')
     molecule = driver.run(section)
     self.ferOp = FermionicOperator(h1=molecule._one_body_integrals,
                                    h2=molecule._two_body_integrals)
 def setUp(self):
     cfg_mgr = ConfigurationManager()
     pyquante_cfg = OrderedDict([('atoms', 'H .0 .0 .0; H .0 .0 0.735'),
                                 ('unit', 'Angstrom'), ('charge', 0),
                                 ('multiplicity', 1), ('basis', 'sto3g')])
     section = {'properties': pyquante_cfg}
     try:
         driver = cfg_mgr.get_driver_instance('PYQUANTE')
     except ModuleNotFoundError:
         self.skipTest('PYQUANTE driver does not appear to be installed')
     self.qmolecule = driver.run(section)
    def setUp(self):
        cfg_mgr = ConfigurationManager()
        gaussian_cfg = """
# rhf/sto-3g scf(conventional) geom=nocrowd

h2 molecule

0 1
H   0.0  0.0    0.0
H   0.0  0.0    0.735

"""
        section = {'data': gaussian_cfg}
        try:
            driver = cfg_mgr.get_driver_instance('GAUSSIAN')
        except ACQUAChemistryError:
            self.skipTest('GAUSSIAN driver does not appear to be installed')
        self.qmolecule = driver.run(section)
Esempio n. 6
0
    def setUp(self):
        cfg_mgr = ConfigurationManager()
        psi4_cfg = """
molecule h2 {
  0 1
  H  0.0 0.0 0.0
  H  0.0 0.0 0.735
}
 
set {
  basis sto-3g
  scf_type pk
}
"""
        section = {'data': psi4_cfg}
        try:
            driver = cfg_mgr.get_driver_instance('PSI4')
        except ACQUAChemistryError:
            self.skipTest('PSI4 driver does not appear to be installed')
        self.qmolecule = driver.run(section)
    def test_freezing_core(self):
        cfg_mgr = ConfigurationManager()
        pyscf_cfg = OrderedDict([('atom',
                                  'H .0 .0 -1.160518; Li .0 .0 0.386839'),
                                 ('unit', 'Angstrom'), ('charge', 0),
                                 ('spin', 0), ('basis', 'sto3g')])
        section = {}
        section['properties'] = pyscf_cfg
        driver = cfg_mgr.get_driver_instance('PYSCF')
        molecule = driver.run(section)
        ferOp = FermionicOperator(h1=molecule._one_body_integrals,
                                  h2=molecule._two_body_integrals)
        ferOp, energy_shift = ferOp.fermion_mode_freezing([0, 6])
        gt = -7.8187092970493755
        diff = abs(energy_shift - gt)
        self.assertLess(diff, 1e-6)

        cfg_mgr = ConfigurationManager()
        pyscf_cfg = OrderedDict([('atom', 'H .0 .0 .0; Na .0 .0 1.888'),
                                 ('unit', 'Angstrom'), ('charge', 0),
                                 ('spin', 0), ('basis', 'sto3g')])
        section = {}
        section['properties'] = pyscf_cfg
        driver = cfg_mgr.get_driver_instance('PYSCF')
        molecule = driver.run(section)
        ferOp = FermionicOperator(h1=molecule._one_body_integrals,
                                  h2=molecule._two_body_integrals)
        ferOp, energy_shift = ferOp.fermion_mode_freezing(
            [0, 1, 2, 3, 4, 10, 11, 12, 13, 14])
        gt = -162.58414559586748
        diff = abs(energy_shift - gt)
        self.assertLess(diff, 1e-6)
    def setUp(self):
        cfg_mgr = ConfigurationManager()
        hdf5_cfg = OrderedDict([
            ('hdf5_input', 'test/test_driver_hdf5.hdf5')
        ])
        section = {'properties': hdf5_cfg}
        driver = cfg_mgr.get_driver_instance('HDF5')
        self.qmolecule = driver.run(section)

        core = get_chemistry_operator_instance('hamiltonian')
        hamiltonian_cfg = OrderedDict([
            ('name', 'hamiltonian'),
            ('transformation', 'full'),
            ('qubit_mapping', 'parity'),
            ('two_qubit_reduction', True),
            ('freeze_core', False),
            ('orbital_reduction', [])
        ])
        core.init_params(hamiltonian_cfg)
        self.algo_input = core.run(self.qmolecule)

        self.reference_energy = -1.857275027031588
Esempio n. 9
0
    def __init__(self, view):
        self._view = view
        self._model = Model()
        self._filemenu = None
        self._title = tk.StringVar()
        self._sectionsView = None
        self._emptyView = None
        self._sectionView_title = tk.StringVar()
        self._propertiesView = None
        self._textView = None
        self._outputView = None
        self._progress = None
        self._button_text = None
        self._start_button = None
        self._save_algo_json = tk.IntVar()
        self._save_algo_json.set(0)
        self._thread_queue = queue.Queue()
        self._thread = None
        self._command = Controller._START
        self._driver_names = []
        config_mgr = ConfigurationManager()
        for name in config_mgr.module_names:
            try:
                config_mgr.get_driver_instance(name)
                self._driver_names.append(name)
            except:
                pass

        self._process_stop = False
        self._validate_integer_command = self._view.register(
            Controller._validate_integer)
        self._validate_float_command = self._view.register(
            Controller._validate_float)
        self._available_backends = []
        self._backendsthread = None
        self.get_available_backends()
    def test_qpe(self, distance):
        self.algorithm = 'QPE'
        self.log.debug(
            'Testing End-to-End with QPE on H2 with interatomic distance {}.'.
            format(distance))
        cfg_mgr = ConfigurationManager()
        pyscf_cfg = OrderedDict([('atom',
                                  'H .0 .0 .0; H .0 .0 {}'.format(distance)),
                                 ('unit', 'Angstrom'), ('charge', 0),
                                 ('spin', 0), ('basis', 'sto3g')])
        section = {}
        section['properties'] = pyscf_cfg
        driver = cfg_mgr.get_driver_instance('PYSCF')
        self.molecule = driver.run(section)

        ferOp = FermionicOperator(h1=self.molecule._one_body_integrals,
                                  h2=self.molecule._two_body_integrals)
        self.qubitOp = ferOp.mapping(
            map_type='PARITY', threshold=1e-10).two_qubit_reduced_operator(2)

        exact_eigensolver = get_algorithm_instance('ExactEigensolver')
        exact_eigensolver.init_args(self.qubitOp, k=1)
        results = exact_eigensolver.run()
        self.reference_energy = results['energy']
        self.log.debug('The exact ground state energy is: {}'.format(
            results['energy']))

        num_particles = self.molecule._num_alpha + self.molecule._num_beta
        two_qubit_reduction = True
        num_orbitals = self.qubitOp.num_qubits + (2 if two_qubit_reduction else
                                                  0)
        qubit_mapping = 'parity'

        num_time_slices = 50
        n_ancillae = 9

        qpe = get_algorithm_instance('QPE')
        qpe.setup_quantum_backend(backend='local_qasm_simulator', shots=100)

        state_in = get_initial_state_instance('HartreeFock')
        state_in.init_args(self.qubitOp.num_qubits, num_orbitals,
                           qubit_mapping, two_qubit_reduction, num_particles)

        iqft = get_iqft_instance('STANDARD')
        iqft.init_args(n_ancillae)

        qpe.init_args(self.qubitOp,
                      state_in,
                      iqft,
                      num_time_slices,
                      n_ancillae,
                      paulis_grouping='random',
                      expansion_mode='suzuki',
                      expansion_order=2,
                      use_basis_gates=True)

        result = qpe.run()

        self.log.debug('measurement results:      {}'.format(
            result['measurements']))
        self.log.debug('top result str label:     {}'.format(
            result['top_measurement_label']))
        self.log.debug('top result in decimal:    {}'.format(
            result['top_measurement_decimal']))
        self.log.debug('stretch:                  {}'.format(
            result['stretch']))
        self.log.debug('translation:              {}'.format(
            result['translation']))
        self.log.debug('final energy from QPE:    {}'.format(result['energy']))
        self.log.debug('reference energy:         {}'.format(
            self.reference_energy))
        self.log.debug('ref energy (transformed): {}'.format(
            (self.reference_energy + result['translation']) *
            result['stretch']))
        self.log.debug('ref binary str label:     {}'.format(
            decimal_to_binary((self.reference_energy + result['translation']) *
                              result['stretch'],
                              max_num_digits=n_ancillae + 3,
                              fractional_part_only=True)))

        np.testing.assert_approx_equal(result['energy'],
                                       self.reference_energy,
                                       significant=2)
Esempio n. 11
0
 def __init__(self):
     """Create Model object."""
     self._configuration_mgr = ConfigurationManager()
     self._parser = InputParser()
 def __init__(self):
     """Create an ACQUAChemistry object."""
     self._configuration_mgr = ConfigurationManager()
     self._parser = None
     self._core = None
class ACQUAChemistry(object):
    """Main entry point."""

    KEY_HDF5_OUTPUT = 'hdf5_output'
    _DRIVER_RUN_TO_HDF5 = 1
    _DRIVER_RUN_TO_ALGO_INPUT = 2

    def __init__(self):
        """Create an ACQUAChemistry object."""
        self._configuration_mgr = ConfigurationManager()
        self._parser = None
        self._core = None

    def get_effective_logging_level(self):
        """
        Returns the logging level being used by ACQUA Chemistry
        """
        levels = get_logger_levels_for_names(
            ['qiskit_acqua_chemistry', 'qiskit_acqua'])
        return levels[0]

    def set_logging(self, level=logging.INFO):
        """Sets logging output of the logging messages.
        Sets the output of logging messages (above level `level`) by
        configuring the logger accordingly.
        Disables logging if set to logging.NOTSET
        Params:
            level (int): minimum severity of the messages that are displayed.
        """
        logging_config = build_logging_config(
            ['qiskit_acqua_chemistry', 'qiskit_acqua'], level)
        preferences = Preferences()
        preferences.set_logging_config(logging_config)
        preferences.save()
        set_logger_config(logging_config)

    def run(self, input, output=None):
        if input is None:
            raise ACQUAChemistryError("Missing input.")

        self._parser = InputParser(input)
        self._parser.parse()
        driver_return = self._run_driver_from_parser(self._parser, False)
        if driver_return[0] == ACQUAChemistry._DRIVER_RUN_TO_HDF5:
            logger.info('No further process.')
            return {'printable': [driver_return[1]]}

        data = run_algorithm(driver_return[1], driver_return[2], True)
        if not isinstance(data, dict):
            raise ACQUAChemistryError(
                "Algorithm run result should be a dictionary")

        if logger.isEnabledFor(logging.DEBUG):
            logger.debug('Algorithm returned: {}'.format(
                json.dumps(data, indent=4)))

        convert_json_to_dict(data)
        lines, result = self._format_result(data)
        logger.info('Processing complete. Final result available')
        result['printable'] = lines

        if output is not None:
            with open(output, 'w') as f:
                for line in lines:
                    print(line, file=f)

        return result

    def save_input(self, input_file):
        """Save the input of a run to a file.
        Params:
            input_file (string): file path
        """
        if self._parser is None:
            raise ACQUAChemistryError("Missing input information.")

        self._parser.save_to_file(input_file)

    def run_drive_to_jsonfile(self, input, jsonfile):
        if jsonfile is None:
            raise ACQUAChemistryError("Missing json file")

        data = self._run_drive(input, True)
        if data is None:
            logger.info('No data to save. No further process.')
            return

        logger.debug('Result: {}'.format(
            json.dumps(data, sort_keys=True, indent=4)))
        with open(jsonfile, 'w') as fp:
            json.dump(data, fp, sort_keys=True, indent=4)

        print("Algorithm input file saved: '{}'".format(jsonfile))

    def run_algorithm_from_jsonfile(self, jsonfile, output=None):
        with open(jsonfile) as json_file:
            return self.run_algorithm_from_json(json.load(json_file), output)

    def run_algorithm_from_json(self, params, output=None):
        ret = run_algorithm(params, None, True)
        if not isinstance(ret, dict):
            raise ACQUAChemistryError(
                "Algorithm run result should be a dictionary")

        logger.debug('Algorithm returned: {}'.format(json.dumps(ret,
                                                                indent=4)))
        convert_json_to_dict(ret)
        print('Output:')
        if isinstance(ret, dict):
            for k, v in ret.items():
                print("'{}': {}".format(k, v))
        else:
            print(ret)

        return ret

    def _format_result(self, data):
        lines, result = self._core.process_algorithm_result(data)
        return lines, result

    def run_drive(self, input):
        return self._run_drive(input, False)

    def _run_drive(self, input, save_json_algo_file):
        if input is None:
            raise ACQUAChemistryError("Missing input.")

        self._parser = InputParser(input)
        self._parser.parse()
        driver_return = self._run_driver_from_parser(self._parser,
                                                     save_json_algo_file)
        driver_return[1]['input'] = driver_return[2].to_params()
        driver_return[1]['input']['name'] = driver_return[2].configuration[
            'name']
        return driver_return[1]

    def _run_driver_from_parser(self, p, save_json_algo_file):
        if p is None:
            raise ACQUAChemistryError("Missing parser")

        p.validate_merge_defaults()
        #logger.debug('ALgorithm Input Schema: {}'.format(json.dumps(p.to_JSON(), sort_keys=True, indent=4)))

        experiment_name = "-- no &NAME section found --"
        if InputParser.NAME in p.get_section_names():
            name_sect = p.get_section(InputParser.NAME)
            if 'data' in name_sect:
                experiment_name = name_sect['data']
        logger.info('Running chemistry problem from input file: {}'.format(
            p.get_filename()))
        logger.info('Experiment description: {}'.format(
            experiment_name.rstrip()))

        driver_name = p.get_section_property(InputParser.DRIVER,
                                             InputParser.NAME)
        if driver_name is None:
            raise ACQUAChemistryError(
                'Property "{0}" missing in section "{1}"'.format(
                    InputParser.NAME, InputParser.DRIVER))

        hdf5_file = p.get_section_property(InputParser.DRIVER,
                                           ACQUAChemistry.KEY_HDF5_OUTPUT)

        section = p.get_section(driver_name)
        if 'data' not in section:
            raise ACQUAChemistryError(
                'Property "data" missing in section "{0}"'.format(driver_name))

        if driver_name not in self._configuration_mgr.module_names:
            raise ACQUAChemistryError(
                'Driver "{0}" missing in local drivers'.format(driver_name))

        work_path = None
        input_file = p.get_filename()
        if input_file is not None:
            work_path = os.path.dirname(os.path.realpath(input_file))

        driver = self._configuration_mgr.get_driver_instance(driver_name)
        driver.work_path = work_path
        molecule = driver.run(section)

        if work_path is not None and hdf5_file is not None and not os.path.isabs(
                hdf5_file):
            hdf5_file = os.path.abspath(os.path.join(work_path, hdf5_file))

        molecule.log()

        if hdf5_file is not None:
            molecule._origin_driver_name = driver_name
            molecule._origin_driver_config = section['data']
            molecule.save(hdf5_file)
            text = "HDF5 file saved '{}'".format(hdf5_file)
            logger.info(text)
            if not save_json_algo_file:
                logger.info('Run ended with hdf5 file saved.')
                return ACQUAChemistry._DRIVER_RUN_TO_HDF5, text

        # Run the Hamiltonian to process the QMolecule and get an input for algorithms
        self._core = get_chemistry_operator_instance(
            p.get_section_property(InputParser.OPERATOR, InputParser.NAME))
        self._core.init_params(p.get_section_properties(InputParser.OPERATOR))
        input_object = self._core.run(molecule)

        logger.debug('Core computed substitution variables {}'.format(
            self._core.molecule_info))
        result = p.process_substitutions(self._core.molecule_info)
        logger.debug('Substitutions {}'.format(result))

        params = {}
        for section_name, section in p.get_sections().items():
            if section_name == InputParser.NAME or \
               section_name == InputParser.DRIVER or \
               section_name == driver_name.lower() or \
               section_name == InputParser.OPERATOR or \
               'properties' not in section:
                continue

            params[section_name] = copy.deepcopy(section['properties'])
            if InputParser.PROBLEM == section_name and \
                InputParser.ENABLE_SUBSTITUTIONS in params[section_name]:
                del params[section_name][InputParser.ENABLE_SUBSTITUTIONS]

        return ACQUAChemistry._DRIVER_RUN_TO_ALGO_INPUT, params, input_object