Exemplo n.º 1
0
Arquivo: api.py Projeto: artiomn/qsdk
 def __init__(self,
              backend_address=os.environ.get('DWAVE_SERVER_ADDRESS'),
              *args,
              **kwargs):
     super(DWaveBackend, self).__init__()
     self._backend_address = backend_address
     self._solvers = {
         solver_class.name(): solver_class
         for solver_class in [QuboSolver]
     }
     self._client = Client(endpoint=backend_address, *args, **kwargs)
Exemplo n.º 2
0
    def __init__(self, solver=None, connection_close=True, **config):

        # always use the base class (QPU client filters-out the hybrid solvers)
        config['client'] = 'base'

        if solver is None:
            solver = {}

        if isinstance(solver, abc.Mapping):
            if solver.setdefault('category', 'hybrid') != 'hybrid':
                raise ValueError(
                    "the only 'category' this sampler supports is 'hybrid'")
            if solver.setdefault('supported_problem_types__contains',
                                 'bqm') != 'bqm':
                raise ValueError(
                    "the only problem type this sampler supports is 'bqm'")

        self.client = Client.from_config(solver=solver,
                                         connection_close=connection_close,
                                         **config)

        self.solver = self.client.get_solver()

        # For explicitly named solvers:
        if self.properties.get('category') != 'hybrid':
            raise ValueError("selected solver is not a hybrid solver.")
        if 'bqm' not in self.solver.supported_problem_types:
            raise ValueError(
                "selected solver does not support the 'bqm' problem type.")
Exemplo n.º 3
0
def _config_create(config_file, profile, ask_full=False):
    """Full/simplified dwave create flows."""

    if ask_full:
        rs = Client._fetch_available_regions(DEFAULT_METADATA_API_ENDPOINT)
        prompts = dict(
            region=dict(prompt="Solver API region", choices=[r.code for r in rs]),
            endpoint=dict(prompt="Solver API endpoint URL (overwrites 'region')"),
            token=dict(prompt="Authentication token"),
            client=dict(prompt="Client class", choices='base qpu sw hybrid'.split()),
            solver=dict(prompt="Solver"))

    else:
        prompts = dict(
            token=dict(prompt="Authentication token"))

        click.echo("Using the simplified configuration flow.\n"
                   "Try 'dwave config create --full' for more options.\n")

    # resolve config file path
    ask_to_confirm_config_path = not config_file
    if not config_file:
        config_file = get_configfile_path()
        if not config_file:
            config_file = get_default_configfile_path()

    config_file_exists = os.path.exists(config_file)
    verb = "Updating existing" if config_file_exists else "Creating new"
    click.echo(f"{verb} configuration file: {config_file}")

    if ask_full and ask_to_confirm_config_path:
        config_file = default_text_input("Confirm configuration file path", config_file)
        config_file = os.path.expanduser(config_file)

    config = _load_config(config_file)
    default_section = config.default_section

    # resolve profile
    if not profile:
        existing = config.sections()
        if default_section in config:   # not included in sections
            existing.insert(0, default_section)
        if config_file_exists:
            click.echo(f"Available profiles: {', '.join(existing)}")
        default_profile = next(iter(existing))

        _note = " (select existing or create new)" if config_file_exists else ""
        profile = default_text_input(f"Profile{_note}", default_profile)

    verb = "Updating existing" if profile in config else "Creating new"
    click.echo(f"{verb} profile: {profile}")

    if profile != default_section and not config.has_section(profile):
        config.add_section(profile)

    _input_config_variables(config, profile, prompts)

    _write_config(config, config_file)

    click.echo("Configuration saved.")
Exemplo n.º 4
0
    def __init__(self, **config):
        # strongly prefer hybrid solvers; requires kwarg-level override
        config.setdefault('client', 'hybrid')

        # default to short-lived session to prevent resets on slow uploads
        config.setdefault('connection_close', True)

        if FeatureFlags.hss_solver_config_override:
            # use legacy behavior (override solver config from env/file)
            solver = config.setdefault('solver', {})
            if isinstance(solver, abc.Mapping):
                solver.update(self.default_solver)

        # prefer the latest hybrid CQM solver available, but allow for an easy
        # override on any config level above the defaults (file/env/kwarg)
        defaults = config.setdefault('defaults', {})
        if not isinstance(defaults, abc.Mapping):
            raise TypeError("mapping expected for 'defaults'")
        defaults.update(solver=self.default_solver)

        self.client = Client.from_config(**config)
        self.solver = self.client.get_solver()

        # For explicitly named solvers:
        if self.properties.get('category') != 'hybrid':
            raise ValueError("selected solver is not a hybrid solver.")
        if 'cqm' not in self.solver.supported_problem_types:
            raise ValueError(
                "selected solver does not support the 'cqm' problem type.")
Exemplo n.º 5
0
    def dw(self):
        try:
            from dwave.cloud import Client
        except ImportError:
            raise ImportError(
                "dw() requires dwave-cloud-client. Please install before call this function."
            )
        solver = Client.from_config(endpoint=self.dwaveendpoint,
                                    token=self.dwavetoken,
                                    solver=self.dwavesolver).get_solver()

        if self.qubo != []:
            self.qi()

        # for hi
        harr = np.diag(self.J)
        larr = []
        for i in solver.nodes:
            if i < len(harr):
                larr.append(harr[i])
        linear = {index: larr[index] for index in range(len(larr))}

        # for jij
        qarr = []
        qarrv = []
        for i in solver.undirected_edges:
            if i[0] < len(harr) and i[1] < len(harr):
                qarr.append(i)
                qarrv.append(self.J[i[0]][i[1]])

        quad = {key: j for key, j in zip(qarr, qarrv)}
        computation = solver.sample_ising(linear, quad, num_reads=1)

        return computation.samples[0][:len(harr)]
Exemplo n.º 6
0
def solve_ising_dwave(hii, Jij):
    config_file = '/media/sf_QWorld/QWorld/QA_DeNovoAsb/dwcloud.conf'
    client = Client.from_config(config_file, profile='aritra')
    solver = client.get_solver(
    )  # Available QPUs: DW_2000Q_2_1 (2038 qubits), DW_2000Q_5 (2030 qubits)
    dwsampler = DWaveSampler(config_file=config_file)

    edgelist = solver.edges
    adjdict = edgelist_to_adjacency(edgelist)
    embed = minorminer.find_embedding(Jij.keys(), edgelist)
    [h_qpu, j_qpu] = embed_ising(hii, Jij, embed, adjdict)

    response_qpt = dwsampler.sample_ising(h_qpu,
                                          j_qpu,
                                          num_reads=solver.max_num_reads())
    client.close()

    bqm = dimod.BinaryQuadraticModel.from_ising(hii, Jij)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)
    print("Maximum Sampled Configurations from D-Wave\t===>")
    solnsMaxSample = sorted(unembedded.record, key=lambda x: -x[2])
    for i in range(0, 10):
        print(solnsMaxSample[i])
    print("Minimum Energy Configurations from D-Wave\t===>")
    solnsMinEnergy = sorted(unembedded.record, key=lambda x: +x[1])
    for i in range(0, 10):
        print(solnsMinEnergy[i])
Exemplo n.º 7
0
Arquivo: 3.py Projeto: Ocete/TFG
def solve_qubo_dwave(Q, num_reads=1000):
    # Create the solver (connecting to D-Wave) and the Sampler
    config_file = '../dwave.conf'
    client = Client.from_config(config_file, profile='ocete')
    solver = client.get_solver(
    )  # Available QPUs: DW_2000Q_2_1 (2038 qubits), DW_2000Q_5 (2030 qubits)
    dwsampler = DWaveSampler(config_file=config_file)

    # We need to embed Q into a valid graph for the D-Wave architecture
    edgelist = solver.edges
    adjdict = edgelist_to_adjacency(edgelist)
    embed = minorminer.find_embedding(Q, edgelist)
    Q_embeded = embed_qubo(Q, embed, adjdict)

    # Obtain the response from the solver. This is the actual D-Wave execution!
    start = time.time()
    response_qpt = dwsampler.sample_qubo(Q_embeded, num_reads=num_reads)
    qpu_time = time.time() - start
    client.close()

    # Transform the response from the embeded graph to our original architecture
    bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)

    # Order the solutions by lower energy
    return unembedded, qpu_time
Exemplo n.º 8
0
def solvers(config_file, profile, solver_id, list_solvers):
    """Get solver details.

    Unless solver name/id specified, fetch and display details for
    all solvers available on configured endpoint.
    """

    with Client.from_config(config_file=config_file, profile=profile) as client:
        solvers = client.get_solvers().values()

        if solver_id:
            solvers = filter(lambda s: s.id == solver_id, solvers)
            if not solvers:
                click.echo("Solver {} not found.".format(solver_id))
                return 1

        if list_solvers:
            for solver in solvers:
                click.echo(solver.id)
            return

        # ~YAML output
        for solver in solvers:
            click.echo("Solver: {}".format(solver.id))
            click.echo("  Parameters:")
            for param, desc in sorted(solver.parameters.items()):
                click.echo("    {}: {}".format(param, strtrunc(desc) if desc else '?'))
            solver.properties.pop('parameters', None)
            click.echo("  Properties:")
            for k,v in sorted(solver.properties.items()):
                click.echo("    {}: {}".format(k, strtrunc(v)))
            click.echo()
Exemplo n.º 9
0
def solvers(config_file, profile, solver_def, list_solvers):
    """Get solver details.

    Unless solver name/id specified, fetch and display details for
    all solvers available on configured endpoint.
    """

    with Client.from_config(config_file=config_file,
                            profile=profile,
                            solver=solver_def) as client:

        try:
            solvers = client.get_solvers(**client.default_solver)
        except SolverNotFoundError:
            click.echo("Solver(s) {} not found.".format(solver_def))
            return 1

        if list_solvers:
            for solver in solvers:
                click.echo(solver.id)
            return

        # ~YAML output
        for solver in solvers:
            click.echo("Solver: {}".format(solver.id))
            click.echo("  Parameters:")
            for param, desc in sorted(solver.parameters.items()):
                click.echo("    {}: {}".format(
                    param,
                    strtrunc(desc) if desc else '?'))
            solver.properties.pop('parameters', None)
            click.echo("  Properties:")
            for k, v in sorted(solver.properties.items()):
                click.echo("    {}: {}".format(k, strtrunc(v)))
            click.echo()
Exemplo n.º 10
0
 def get_sampler_from_config(self, profile=None, solver=None, sampler_type=None):
     """Return a dimod.Sampler object found in the user's configuration file,
     associated solver information, and any extra parameters needed."""
     try:
         with Client.from_config(profile=profile, client=sampler_type) as client:
             if solver == None:
                 solver = client.default_solver
                 solver_name = solver["name__eq"]
             else:
                 solver_name = solver
                 solver = {"name": solver}
             if isinstance(client, hybrid.Client):
                 sampler = LeapHybridSampler(profile=profile, solver=solver)
             elif isinstance(client, sw.Client):
                 self.qmasm.abend("QMASM does not currently support remote software solvers")
             else:
                 sampler = DWaveSampler(profile=profile, solver=solver)
             info = self._recursive_properties(sampler)
             info["solver_name"] = solver_name
             info["endpoint"] = client.endpoint
             if profile != None:
                 info["profile"] = profile
             return sampler, info, {}
     except Exception as err:
         self.qmasm.abend("Failed to construct a sampler (%s)" % str(err))
Exemplo n.º 11
0
def default_solver():
    with Client.from_config() as client:
        try:
            my_default_solver = client.get_solver(qpu=True).id
            ds = "Solver: " + my_default_solver
            print(ds)
        except SolverNotFoundError:
            my_default_solver = " "
            print_markdown(
                "<span style='color:red;font-weight:bold'>No D-Wave solver found.</span>"
            )
            print(
                "Please check available solvers on the <span style='font-weight:bold'>Leap dashboard</span>."
            )
    my_default_token = os.getenv('DWAVE_API_TOKEN')
    if not my_default_token or my_default_token == "None":
        print_markdown(
            "<span style='color:red;font-weight:bold'>No default API token.</span>"
        )
        print("An API token is not set for this environment.")
        print_markdown(
            "You can find your API token on the <span style='font-weight:bold'>Leap dashboard</span>."
        )
        print(
            "Please uncomment the \"sampler =\" line in the next cell and paste your token there."
        )
    else:
        dt = "API Token: " + my_default_token[:10] + "***" + my_default_token[
            -5:]
        print(dt)
    return (my_default_solver, my_default_token)
Exemplo n.º 12
0
    def __init__(self,
                 config_file=None,
                 profile=None,
                 endpoint=None,
                 token=None,
                 solver=None,
                 solver_features=None,
                 proxy=None,
                 permissive_ssl=False):

        self.client = Client.from_config(config_file=config_file,
                                         profile=profile,
                                         endpoint=endpoint,
                                         token=token,
                                         proxy=proxy,
                                         permissive_ssl=permissive_ssl)

        if solver_features is None:
            # default to getting a QPU rather than a software solver
            solver_features = {'qpu': True}

        # TODO: deprecate `solver`` name in favor of name regex in `solver_features`
        self.solver = self.client.get_solver(name=solver,
                                             features=solver_features)

        # need to set up the nodelist and edgelist, properties, parameters
        self._nodelist = sorted(self.solver.nodes)
        self._edgelist = sorted(
            set(tuple(sorted(edge)) for edge in self.solver.edges))
        self._properties = self.solver.properties.copy()  # shallow copy
        self._parameters = {
            param: ['parameters']
            for param in self.solver.properties['parameters']
        }
Exemplo n.º 13
0
    def __init__(self,
                 failover=False,
                 retry_interval=-1,
                 order_by=None,
                 **config):

        if config.get('solver_features') is not None:
            warn("'solver_features' argument has been renamed to 'solver'.",
                 DeprecationWarning)

            if config.get('solver') is not None:
                raise ValueError(
                    "can not combine 'solver' and 'solver_features'")

            config['solver'] = config.pop('solver_features')

        self.client = Client.from_config(**config)

        if order_by is None:
            # use the default from the cloud-client
            self.solver = self.client.get_solver()
        else:
            self.solver = self.client.get_solver(order_by=order_by)

        self.failover = failover
        self.retry_interval = retry_interval
Exemplo n.º 14
0
    def _get_sampler(self, profile, solver):
        "Return a dimod.Sampler object."
        # Handle built-in software samplers as special cases.
        info = {}
        if solver != None:
            info["solver_name"] = solver
        if solver == "exact":
            return ExactSolver(), info
        elif solver == "neal":
            return SimulatedAnnealingSampler(), info
        elif solver == "tabu":
            return TabuSampler(), info

        # In the common case, read the configuration file, either the
        # default or the one named by the DWAVE_CONFIG_FILE environment
        # variable.
        if profile != None:
            info["profile"] = profile
        try:
            with Client.from_config(profile=profile) as client:
                if solver == None:
                    solver = client.default_solver
                else:
                    solver = {"name": solver}
                sampler = DWaveSampler(profile=profile, solver=solver)
                info = {
                    "solver_name": sampler.solver.name,
                    "endpoint": client.endpoint
                }
                return sampler, info
        except Exception as err:
            self.qmasm.abend("Failed to construct a sampler (%s)" % str(err))
Exemplo n.º 15
0
    def __init__(self, solver=None, connection_close=True, **config):

        # we want a Hybrid solver by default, but allow override
        config.setdefault('client', 'hybrid')

        if solver is None:
            solver = {}

        if isinstance(solver, abc.Mapping):
            # TODO: instead of solver selection, try with user's default first
            if solver.setdefault('category', 'hybrid') != 'hybrid':
                raise ValueError(
                    "the only 'category' this sampler supports is 'hybrid'")
            if solver.setdefault('supported_problem_types__contains',
                                 'bqm') != 'bqm':
                raise ValueError(
                    "the only problem type this sampler supports is 'bqm'")

            # prefer the latest version, but allow kwarg override
            solver.setdefault('order_by', '-version')

        self.client = Client.from_config(solver=solver,
                                         connection_close=connection_close,
                                         **config)

        self.solver = self.client.get_solver()

        # For explicitly named solvers:
        if self.properties.get('category') != 'hybrid':
            raise ValueError("selected solver is not a hybrid solver.")
        if 'bqm' not in self.solver.supported_problem_types:
            raise ValueError(
                "selected solver does not support the 'bqm' problem type.")
Exemplo n.º 16
0
def getHardwareAdjacency(solver_name="DW_2000Q_VFYC_6"):
    """

    :param solver_name: The D'Wave Annealer to be used
    :return: A graph with the Chimera structure of the D'Wave Annealer
    """
    with Client.from_config() as client:
        solver = client.get_solver(solver_name)
        return (solver.nodes, solver.undirected_edges)
def qpu_available():
    """Check whether QPU solver is available"""
    try:
        with Client.from_config() as client:
            solver = client.get_solver(qpu=True)
    except (ConfigFileError, ValueError) as e:
        return False
    else:
        return True
Exemplo n.º 18
0
def hybrid_solver_available():
    """Check whether hybrid solver is available"""
    try:
        with Client.from_config() as client:
            solver = client.get_solver(hybrid=True)
    except (ConfigFileError, ValueError, SolverNotFoundError) as e:
        return False
    else:
        return True
Exemplo n.º 19
0
def _get_client_solver(config, output=None):
    """Helper function to return an instantiated client, and solver, validating
    parameters in the process, while wrapping errors in `CLIError` and using
    `output` writer as a centralized printer.
    """
    if output is None:
        output = click.echo

    # get client
    try:
        client = Client.from_config(**config)
    except Exception as e:
        raise CLIError("Invalid configuration: {}".format(e), code=1)

    config_file = config.get('config_file')
    if config_file:
        output("Using configuration file: {config_file}", config_file=config_file)

    profile = config.get('profile')
    if profile:
        output("Using profile: {profile}", profile=profile)

    output("Using endpoint: {endpoint}", endpoint=client.endpoint)
    output("Using region: {region}", region=client.region)

    # get solver
    try:
        solver = client.get_solver()
    except SolverAuthenticationError:
        raise CLIError("Authentication error. Check credentials in your configuration file.", 2)
    except SolverNotFoundError:
        raise CLIError("Solver not available.", 6)
    except (InvalidAPIResponseError, UnsupportedSolverError):
        raise CLIError("Invalid or unexpected API response.", 3)
    except RequestTimeout:
        raise CLIError("API connection timed out.", 4)
    except requests.exceptions.SSLError as e:
        # we need to handle `ssl.SSLError` wrapped in several exceptions,
        # with differences between py2/3; greping the message is the easiest way
        if 'CERTIFICATE_VERIFY_FAILED' in str(e):
            raise CLIError(
                "Certificate verification failed. Please check that your API endpoint "
                "is correct. If you are connecting to a private or third-party D-Wave "
                "system that uses self-signed certificate(s), please see "
                "https://support.dwavesys.com/hc/en-us/community/posts/360018930954.", 5)
        raise CLIError("Unexpected SSL error while fetching solver: {!r}".format(e), 5)
    except Exception as e:
        raise CLIError("Unexpected error while fetching solver: {!r}".format(e), 5)

    output("Using solver: {solver_id}", solver_id=solver.id)

    return (client, solver)
Exemplo n.º 20
0
def ping(config_file, profile):
    """Ping the QPU by submitting a single-qubit problem."""

    try:
        client = Client.from_config(config_file=config_file, profile=profile)
    except Exception as e:
        click.echo("Invalid config: {}".format(e))
        return 1
    if config_file:
        click.echo("Using config file: {}".format(config_file))
    if profile:
        click.echo("Using profile: {}".format(profile))
    click.echo("Using endpoint: {}".format(client.endpoint))

    t0 = timer()
    try:
        solvers = client.get_solvers()
    except SolverAuthenticationError:
        click.echo(
            "Authentication error. Check credentials in your config file.")
        return 1
    except (InvalidAPIResponseError, UnsupportedSolverError):
        click.echo("Invalid or unexpected API response.")
        return 2

    try:
        solver = client.get_solver()
    except (ValueError, KeyError):
        # if not otherwise defined (ValueError), or unavailable (KeyError),
        # just use the first solver
        if solvers:
            _, solver = next(iter(solvers.items()))
        else:
            click.echo("No solvers available.")
            return 1

    t1 = timer()
    click.echo("Using solver: {}".format(solver.id))

    timing = solver.sample_ising({0: 1}, {}).timing
    t2 = timer()

    click.echo("\nWall clock time:")
    click.echo(" * Solver definition fetch web request: {:.3f} ms".format(
        (t1 - t0) * 1000.0))
    click.echo(" * Problem submit and results fetch: {:.3f} ms".format(
        (t2 - t1) * 1000.0))
    click.echo(" * Total: {:.3f} ms".format((t2 - t0) * 1000.0))
    click.echo("\nQPU timing:")
    for component, duration in timing.items():
        click.echo(" * {} = {} us".format(component, duration))
    return 0
Exemplo n.º 21
0
def test_limits():

	n_reads = 2
	while True:
		# Create the solver (connecting to D-Wave) and the Sampler
		config_file='../dwave.conf'
		client = Client.from_config(config_file, profile='ocete')
		solver = client.get_solver('Advantage_system1.1') # Use Advantage to test Pegasus

		try_embedding(n_reads, solver, print_embedding=False)
		n_reads += 1

	client.close()
Exemplo n.º 22
0
def solveWithDwave(qubo, num_reads=100, solver_name="DW_2000Q_VFYC_6"):
    """

    :param qubo: The qubo to be solved
    :param num_reads: The amount of reads the D'Wave quantum annealer should do
    :param solver_name: The D'Wave Annealer to be used
    :return: num_reads Solutions of the Qubo
    """
    with Client.from_config() as client:
        solver = client.get_solver(solver_name)
        computation = solver.sample_qubo(qubo, num_reads=num_reads)
        result = computation.result()
        return result
Exemplo n.º 23
0
def solve_qubo_dwave(Q,
                     n_genome_reads,
                     num_reads=100,
                     label='',
                     annealing_time=20):
    # Create the solver (connecting to D-Wave) and the Sampler
    config_file = '../dwave_adv.conf'
    client = Client.from_config(config_file, profile='ocete')
    solver = client.get_solver('Advantage_system1.1')
    dwsampler = DWaveSampler(
        solver={
            'qpu': True,
            'topology__type': 'pegasus',
            'annealing_time': annealing_time
        },  # Watch out, Leap doesn seem to take into account
        # this parameter, you have to give it as  a paramater in the dwsampler.sample() call
        token=token,
        endpoint=endpoint)

    # We need to embed Q into a valid graph for the D-Wave architecture
    adjdict = edgelist_to_adjacency(solver.edges)
    embed = minorminer.find_embedding(Q, solver.edges)
    Q_embeded = embed_qubo(Q, embed, adjdict)

    # Obtain the response from the solver. This is the actual D-Wave execution!
    start = time.time()
    response_qpt = dwsampler.sample_qubo(Q_embeded,
                                         num_reads=num_reads,
                                         label=label,
                                         annealing_time=annealing_time)
    qpu_time = time.time() - start
    client.close()

    # Transform the response from the embeded graph to our original architecture
    bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)

    # Sort the solutions from lowest energy and format them to quboDict format
    unformated_solutions_list = sorted(unembedded.record, key=lambda x: +x[1])
    solutions_list = []
    for sol, energy, num_appereances in unformated_solutions_list:
        solutions_list.append([
            rebuild_quboDict_from_vector(sol, n_genome_reads), energy,
            num_appereances
        ])

    return solutions_list, qpu_time, get_max_chain_length(embed)
Exemplo n.º 24
0
def upload(config_file, profile, endpoint, region, client_type, solver_def,
           problem_id, format, input_file):
    """Multipart problem upload with cold restart support."""

    try:
        client = Client.from_config(
            config_file=config_file, profile=profile,
            endpoint=endpoint, region=region,
            client=client_type)
    except Exception as e:
        click.echo("Invalid configuration: {}".format(e))
        return 1
    if config_file:
        click.echo("Using configuration file: {}".format(config_file))
    if profile:
        click.echo("Using profile: {}".format(profile))
    click.echo("Using endpoint: {}".format(client.endpoint))

    click.echo(("Preparing to upload a problem from {!r} "
                "in {!r} format.").format(input_file.name, format))

    if format == 'coo':
        click.echo("Transcoding 'coo' to 'dimodbqm'.")

        try:
            import dimod
        except ImportError: # pragma: no cover
            raise RuntimeError("Can't decode 'coo' format without dimod. "
                               "Re-install the library with 'bqm' support.")

        # note: `BQM.from_coo` doesn't support files opened in binary (yet);
        # fallback to reopen for now
        with open(input_file.name, 'rt') as fp:
            bqm = dimod.BinaryQuadraticModel.from_coo(fp)
            problem_file = bqm_as_file(bqm)

    elif format == 'dimodbqm':
        problem_file = input_file

    click.echo("Uploading...")

    try:
        future = client.upload_problem_encoded(
            problem=problem_file, problem_id=problem_id)
        remote_problem_id = future.result()
    except Exception as e:
        click.echo(e)
        return 2

    click.echo("Upload done. Problem ID: {!r}".format(remote_problem_id))
Exemplo n.º 25
0
    def __init__(self, failover=False, retry_interval=-1, **config):
        # strongly prefer QPU solvers; requires kwarg-level override
        config.setdefault('client', 'qpu')

        # weakly prefer QPU solver with the highest qubit count,
        # easily overridden on any config level above defaults (file/env/kwarg)
        defaults = config.setdefault('defaults', {})
        if not isinstance(defaults, abc.Mapping):
            raise TypeError("mapping expected for 'defaults'")
        defaults.update(solver=dict(order_by='-num_active_qubits'))

        self.client = Client.from_config(**config)
        self.solver = self.client.get_solver()

        self.failover = failover
        self.retry_interval = retry_interval
Exemplo n.º 26
0
    def __init__(self, **config):

        if config.get('solver_features') is not None:
            warn("'solver_features' argument has been renamed to 'solver'.", DeprecationWarning)

            if config.get('solver') is not None:
                raise ValueError("can not combine 'solver' and 'solver_features'")

            config['solver'] = config.pop('solver_features')

        self.client = Client.from_config(**config)
        self.solver = self.client.get_solver()

        # need to set up the properties, parameters
        self._properties = self.solver.properties.copy()  # shallow copy
        self._parameters = {param: ['parameters'] for param in self.solver.properties['parameters']}
Exemplo n.º 27
0
def get_ocean_qubo_re(traveling_cost_qubo, traveling_qubo, B, cities_size):
    with Client.from_config() as client:
        solver = client.get_solver()
        p_qubo = traveling_qubo + traveling_cost_qubo * B
        keys = []
        for i in range(len(p_qubo[0])):
            for j in range(len(p_qubo[1])):
                keys.append((i, j))
        Q = {key: val for key, val in zip(keys, p_qubo.reshape(-1))}
#         sampler = neal.SimulatedAnnealingSampler()
#         print(Q)
        computation = solver.sample_qubo(Q,num_reads=10)
        for sample in computation.samples:
            result = sample
            print(result)
    return result
Exemplo n.º 28
0
def solvers(config_file, profile, client_type, solver_def, list_solvers,
            list_all):
    """Get solver details.

    Solver filter is inherited from environment or the specified configuration
    file and profile.
    """

    if list_all:
        client_type = 'base'
        solver_def = '{}'

    with Client.from_config(config_file=config_file,
                            profile=profile,
                            client=client_type,
                            solver=solver_def) as client:

        try:
            solvers = client.get_solvers(**client.default_solver)
        except SolverNotFoundError:
            click.echo("Solver(s) {} not found.".format(solver_def))
            return 1

        if list_solvers:
            for solver in solvers:
                click.echo(solver.id)
            return

        # ~YAML output
        for solver in solvers:
            click.echo("Solver: {}".format(solver.id))
            click.echo("  Parameters:")
            for name, val in sorted(solver.parameters.items()):
                click.echo("    {}: {}".format(name,
                                               strtrunc(val) if val else '?'))
            solver.properties.pop('parameters', None)
            click.echo("  Properties:")
            for name, val in sorted(solver.properties.items()):
                click.echo("    {}: {}".format(name, strtrunc(val)))
            click.echo("  Derived properties:")
            for name in sorted(solver.derived_properties):
                click.echo("    {}: {}".format(name,
                                               strtrunc(getattr(solver,
                                                                name))))
            click.echo()
Exemplo n.º 29
0
    def __init__(self, solver=None, connection_close=True, **config):

        if solver is None:
            solver = {}

        if isinstance(solver, abc.Mapping):
            if solver.setdefault('category', 'hybrid') != 'hybrid':
                raise ValueError(
                    "the only 'category' this sampler supports is 'hybrid'")

        self.client = Client.from_config(solver=solver,
                                         connection_close=connection_close,
                                         **config)
        self.solver = self.client.get_solver()

        # For explicitly named solvers:
        if ('category' not in self.properties.keys()) or (
                not self.properties['category'] == 'hybrid'):
            raise ValueError("selected solver is not a hybrid solver.")
Exemplo n.º 30
0
    def dwave(self):
        from dwave.cloud import Client
        solver = Client.from_config(endpoint=self.dwaveendpoint,
                                    token=self.dwavetoken,
                                    solver=self.dwavesolver).get_solver()

        if self.qubo != []:
            self.qi()
        harr = [-1, 1, -1, 1, -1, 1]
        larr = []
        for i in solver.nodes:
            if i < len(harr):
                larr.append(harr[i])
        linear = {index: larr[index] for index in range(len(larr))}
        #quad = {key: np.random.choice([-1, 1]) for key in solver.undirected_edges}
        quad = {}

        computation = solver.sample_ising(linear, quad, num_reads=100)

        return computation.samples[0]