Example #1
0
def CalculateRoute(CostMatrix, solverSetting: SolverSetting, workspace):

    ##### Initialize solver specificationss -- In all cases we do parameter-free solving because we don't want to do manual tuning
    SolverName = solverSetting.SolverName  # Name of the solver
    HardwareSpec = solverSetting.Hardware  # The hardware, CPU or FPGA
    Timeout = solverSetting.Timeout  # The timeout for the solver, in seconds

    ##### Raise errors if invalid request - Some solvers require specific user inputs
    if (SolverName.lower() == 'quantum monte carlo'):
        raise HTTPException(
            status_code=400,
            detail=
            'Can only implement a Quantum Monte Carlo with paramtrization (manual tuning). It has been disabled for this demo. Check the QIO docs.'
        )

    if (SolverName.lower() == 'tabu search' or SolverName.lower()
            == 'quantum monte carlo' or SolverName.lower()
            == 'parallel tempering') and (HardwareSpec.lower() == 'fpga'):
        raise HTTPException(
            status_code=400,
            detail=
            'Can only implement Tabu search, Quantum Monte Carlo, Parallel Tempering on CPU. Check the QIO docs.'
        )

    ##### The type of hardware the solver will run on
    if HardwareSpec.lower() == 'cpu':
        HardwareInt = 1
    elif HardwareSpec.lower() == 'fpga':
        HardwareInt = 2
    else:
        raise HTTPException(
            status_code=400,
            detail='Hardware choice not valid - choose from CPU/FPGA')

    ##### The solver algorithm initialized
    if SolverName.lower() == 'simulated annealing':
        solver = SimulatedAnnealing(workspace,
                                    timeout=Timeout,
                                    platform=HardwareInt)
    elif SolverName.lower() == 'parallel tempering':
        solver = ParallelTempering(workspace, timeout=Timeout)
    elif SolverName.lower() == 'tabu search':
        solver = Tabu(workspace, timeout=Timeout)
    elif SolverName.lower() == 'quantum monte carlo':
        solver = QuantumMonteCarlo(workspace, timeout=Timeout)

    ##### Submit the optimization problem to the QIO workspace
    OptimizationProblem = OptProblem(
        CostMatrix)  # Initialize the optimization problem instance
    result = solver.submit(
        OptimizationProblem
    )  # We submit because we want to track the status of the optimization - means we do not immediately have a solution, will need to fetch it later

    ##### Return the optimization result
    return result
Example #2
0
    for j in range(0,N):
        for i in range(0,N):
            for k in range(0,N):
                if k>i:
                    if SolvedSudoku[k,j] == SolvedSudoku[i,j]:
                        #print(f'{j},{i},{k}')
                        print(f'Duplicate int in column {j+1}')
                        InvalidSolution = True

    print(f"Is this solution valid? {not InvalidSolution}")

    return InvalidSolution


############################################################################################
##### Generate cost function
OptimizationProblem = SudokuProblem(Sudoku9B)

# Choose the solver and parameters --- uncomment if you wish to use a different one
solver = SimulatedAnnealing(workspace, timeout = 120)   
#solver = ParallelTempering(workspace, timeout = 120)
#solver = Tabu(workspace, timeout = 120)
#solver = QuantumMonteCarlo(workspace, sweeps = 2, trotter_number = 10, restarts = 72, seed = 22, beta_start = 0.1, transverse_field_start = 10, transverse_field_stop = 0.1) # QMC is not available parameter-free yet

SolverSolution = solver.optimize(OptimizationProblem)  
SolvedSudoku   = ReadResults(SolverSolution['configuration'], Sudoku9B)




Example #3
0
                raise RuntimeError('This solution is not valid -- Traveled to a non-starting node more than once')
        PastNodes.append(Path[k][1])
    print(f"Number of different nodes passed = {NumNodes}. This is valid!") 

    ############################################################################################                        
    ##### Check if the end node is same as the start node
    if Path[1][1] != Path[-1][1]:
        raise RuntimeError(f'This solution is not valid -- Start node {Path[1][1]} is not equal to end node {Path[-1][1]}')
    print('Start and end node are the same. This is valid!')


    print('Valid route!')

############################################################################################
# Generate cost function
OptimizationProblem = OptProblem(CostMatrix)

# Choose the solver and parameters --- uncomment if you wish to use a different one

solver = SimulatedAnnealing(workspace, timeout = 120)   
#solver = ParallelTempering(workspace, timeout = 120)
#solver = Tabu(workspace, timeout = 120)
#solver = QuantumMonteCarlo(workspace, sweeps = 2, trotter_number = 10, restarts = 72, seed = 22, beta_start = 0.1, transverse_field_start = 10, transverse_field_stop = 0.1) # QMC is not available parameter-free yet

route = solver.optimize(OptimizationProblem)                                        # Synchronously submit the optimization problem to the service -- wait until done.
print(route)

# Call the function to interpret/convert/analyze the optimization results into a more meaningful/understandable format
PathDict = ReadResults(route['configuration'], NodeName, CostMatrix, NumNodes)
print(PathDict)
Example #4
0
    try:
        # Optimize the problem
        print("Optimizing with:", s.name)
        Job = s.submit(problem)
        Job.wait_until_completed()
        duration = Job.details.end_execution_time - Job.details.begin_execution_time
        if (Job.details.status == "Succeeded"):
            visualize_result(Job.get_results(), containerWeights*len(Ships), Ships, s.name)
            print("Execution duration: ", duration)
        else:
            print("\rJob ID", Job.id, "failed")
    except BaseException as e:
        print(e)

# Try to call a solver with different timeout value and see if it affects the results
SolveMyProblem(problem, SimulatedAnnealing(workspace, timeout=10))
# SolveMyProblem(problem, SimulatedAnnealing(workspace, timeout=20))
# SolveMyProblem(problem, SimulatedAnnealing(workspace, timeout=30))
# SolveMyProblem(problem, SimulatedAnnealing(workspace))

# Try using the parameters returned by the parameter free versions and observe the significant performance improvement
SolveMyProblem(problem, SimulatedAnnealing(workspace, timeout=5, beta_start=8.086689309396733e-05, beta_stop=7.594132985765675, restarts=360, sweeps=50))

# SolveMyProblem(problem, SimulatedAnnealing(workspace, platform=HardwarePlatform.FPGA, timeout=5))
# SolveMyProblem(problem, Tabu(workspace, timeout=5))
# SolveMyProblem(problem, ParallelTempering(workspace, timeout=60))
# SolveMyProblem(problem, QuantumMonteCarlo(workspace))

# PathRelinkingSolver is only available if the 1QBit provider is enabled in your quantum workspace
# SolveMyProblem(problem, PathRelinkingSolver(workspace), -1)
Example #5
0
### Combine terms:
terms = []
terms = c1 + c2 + c3 + c4

from azure.quantum.optimization import Problem, ProblemType
from azure.quantum.optimization import SimulatedAnnealing  # Change this line to match the Azure Quantum Optimization solver type you wish to use

# Problem type is PUBO in this instance. You could also have chosen to represent the problem in Ising form.
problem = Problem(name="Job shop sample",
                  problem_type=ProblemType.pubo,
                  terms=terms)

# Provide details of your workspace, created at the beginning of this tutorial
# Provide the name of the solver you wish to use for this problem (as imported above)
solver = SimulatedAnnealing(workspace, timeout=100)  # Timeout in seconds

# Run job synchronously
result = solver.optimize(problem)
config = result['configuration']

# Run job asynchronously
# Alternatively, a job can be run asynchronously, as shown below:
"""
## Submit problem to solver
job = solver.submit(problem)
print(job.id)

## Get job status
job.refresh()
print(job.details.status)
Example #6
0
# Bringing it all together:

"""
build secret santa matrix

        Vincent Tess Uma
Vincent    -    x(0) x(1)
Tess      x(2)   -   x(3)
Uma	      x(4)  x(5)  -
"""

#       row 0             + row 1             + row 2                
terms = build_terms(0, 1) + build_terms(2, 3) + build_terms(4, 5)

#             + col 0             + col 1             + col 2
terms = terms + build_terms(2, 4) + build_terms(0, 5) + build_terms(1, 3)

print(f'Terms: {terms}\n')

problem = Problem(name = 'secret santa', problem_type = ProblemType.pubo, terms = terms)

solver = SimulatedAnnealing(workspace, timeout = 2)

print('Submitting problem to Azure Quantum')
result = solver.optimize(problem)

print(f'\n\nResult: {result}\n')

print('Human-readable solution:')
print_results(result['configuration'])
Example #7
0
                raise RuntimeError(
                    'This solution is not correct -- Traveled to a non-starting node more than once'
                )
        PastNodes.append(Path[k][1])
    print(f"Number of different nodes passed = {NumNodes}. This is correct!")

    ############################################################################################
    ##### Check if the end nodes is same as the start node
    if Path[1][1] != Path[-1][1]:
        raise RuntimeError(
            f'This solution is not correct -- Start node {Path[1][1]} is not equal to end node {Path[-1][1]}'
        )
    print('Start and end node are the same. This is correct!')

    print('Valid route!')


##### Call the function to interpret/convert/analyze the optimization results into a more meaningful/understandable format
OptimizationProblem = OptProblem(CostMatrix)

#select QIO solver
solver = SimulatedAnnealing(workspace, timeout=120)
#solver = ParallelTempering(workspace, timeout = 120)
#solver = Tabu(workspace, timeout = 120)
#solver = QuantumMonteCarlo(workspace, timeout = 120)

route = solver.optimize(
    OptimizationProblem)  # Solve the optimization problem -- wait until done.

PathDict = ReadResults(route['configuration'], NodeName, CostMatrix, NumNodes)
print(PathDict)
Example #8
0
    return terms


from azure.quantum.optimization import Problem, ProblemType
from azure.quantum.optimization import SimulatedAnnealing  # Change this line to match the Azure Quantum Optimization solver type you wish to use
# run the optimization

# sample data
costsArray = [5, 4, 2, 1, 4]
weightsArray = [7, 2, 5, 6, 8]
Weight = 15

terms = knapsackHamiltonian(costsArray, weightsArray, Weight)
problem = Problem(name="knapsack problem",
                  problem_type=ProblemType.pubo,
                  terms=terms)
solver = SimulatedAnnealing(workspace, timeout=100, seed=22)

job = solver.submit(problem)
job.refresh()
result = job.get_results()
config = result['configuration']
resultitems = []
for i in config.keys():
    if config[i]:
        resultitems.append(int(i))

for i in resultitems:
    if i < len(costsArray):
        print("Picked item number " + str(i))