What is the rationale behind black-box quantum circuit? - quantum-computing

I've read some material about quantum computers and quantum circuits. A certain number of already known algorithms (Simon's algorithm, period-finding algorithm, Grover's algorithm, …) have the following form:
Suppose I have an unknown classical function f: {0,1}^n -> {0, 1}^m satisfying a certain number of statements. I can associate the (unknown) quantum circuit U_f to it and plug the |0.. 0> input state. Now let us define circuit X and show that when appended to U_f, the global output can be measured to extract some information about f.
Wait a minute... What is the relation with classical circuits? A classical problem would refer to an unknown input that satisfies certain properties, this input representing a state coming from outside (user action, file system, database, server, whatever). In case this state is rather generated by another circuit/algorithm the logic applies to the input before. In the end we don't reason about unknown circuits but about unknown inputs. The circuits (the algorithms/ the functions) are the known/chosen components.
Here I came to realize that the common name "circuit" was somehow misleading. In a classical world gate inputs can be thought as values coexisting with outputs. But quantum gates seem to require a temporal interpretation: inputs and outputs represent temporal evolution of the same qubits.
Now this does not really explain how you transform a given bunch of a priori unknown classical input bits (that I believe your keyboard will keep on generating in the future except maybe if Schrödinger's cat is sitting on it) into a "black box quantum circuit" transforming |0…0> into something to be reversed. For example Grover's algorithm propose, for a quantum circuit corresponding to a function f: {0, 1}^n -> {0, 1} that yields 1 for a single unknown input, an efficient method to determine this input. Nice! But how and why would you have to start with such a circuit in the first place?

In practice, the 'unknown function black box' is just a circuit that checks if its input meets some criteria or is the solution to a problem.
This is useful because it's easier to make a circuit that detects a solution than it is to actually find a solution. Grover's algorithm then augments our detector circuit into a solver circuit:
The classical equivalent of Grover's algorithm is a brute-force search function like this:
def bruteForceSearch(min, max, predicate):
for i in min..max:
if predicate(i):
return i
return none
which you would use it like so:
let mersennePrimeWithFiveDigitExponent = bruteForceSearch(
10000,
99999,
i => isMersennePrime(2**i - 1))
Notice how the brute force search turns our knowledge of how to recognize something into a mechanism for finding something. Grover's algorithm does the same thing, but quadratically faster and with the caveat that the recognizer must be implemented as a reversible circuit.

Related

Is there a Qiskit function that allows you to see what qubit/quantum register said gate is attached to?

I am trying to find a way to know what named qubit/quantum register a quantum gate (i.e. labelled Pauli-X gate) would be attached to. The documentation does not have a function nor example that informs me of how to go about doing this. The picture below outlines that I am trying to find qubit n0 from quantum gate U0.
Example quantum circuit
The easiest way to do this would probably be to access the data attribute of your QuantumCircuit object (e.g. circuit.data if your circuit object is named circuit). This will be a list of tuples with the instruction objects (ie the gate instance), the quantum bit arguments for that instruction, and the classical bit arguments for the instruction: (instruction, qargs, cargs). For your example circuit it is simple because there is one only one gate so it'll be the first element in that list. So for that case you can do something like u0_qubits = circuit.data[0][1] and u0_qubits will be a list of the Qubit objects. Trying to do this for larger circuits with possible duplicate gates will obviously be more involved.

Why are the inputs to my guess_nonlinear() all 1s?

The N2 diagram for my full problem is below.
The N2 diagram for the coupled portion of the problem is below.
I have a DirectSolver handling the coupling between LLTForces and ImplicitLiftingLine, and an LNBGS solver handling the coupling between LiftingLineGroup and TestCL.
The gist for the problem is here: https://gist.github.com/eufren/31c0e569ed703b2aea3e2ef5360610f7
I have implemented guess_nonlinear() on ImplicitLiftingLine, which should use various outputs from LLTGeometry to give a good initial guess for the vortex strengths based on a linearised form of the governing equations.
def guess_nonlinear(self, inputs, outputs, resids):
freestream_unit_vector = inputs['freestream_unit_vector']
freestream_velocity = inputs['freestream_velocity']
n = inputs['normal_vectors']
A = inputs['surface_areas']
l = inputs['bound_vortices']
ic_tot = inputs['influence_coefficients_total']
v_inf = freestream_velocity
v_inf_vec = v_inf*freestream_unit_vector
lin_numerator = np.pi * v_inf * A * np.sum(n * v_inf_vec, axis=1)
lin_denominator = (np.linalg.norm(np.cross(v_inf_vec, l), axis=1) - np.pi * v_inf * A * np.sum(np.sum(n * ic_tot, axis=2), axis=1))
lin_vtx_str = lin_numerator / lin_denominator
outputs['vortex_strengths'] = lin_vtx_str
However, when the problem is run for the first time, any inputs not explicitly set with p.set_val() are all 1s. This causes guess_nonlinear() to give a bad output and so the system fails to converge:
As far as I can tell, the execution order for the LLT group is correct, and the geometry components should be being executed before the implicit component. I'm confused as to why this doesn't seem to actually be happening when the code is run, and instead these inputs are taking their default values.
What do I need to change to get this to work properly? Additionally, I've found difficulty in getting LNBGS to converge (hence adding guess_nonlinear()) during optimisation - only DirectSolver gets all the way through the optimisation without issues, but it's very slow for large numbers of LLT nodes). How can I improve the linear and nonlinear solver selection, and improve the reliability of the iterative solver?
Note: Thanks for providing a testable example. It made figuring out the answer to your question a lot simpler. Your problem was a bit subtle and I would not have been able to give a good answer without runnable code
Your first question: "Why are all the inputs 1"
"Short" Answer
You have put the nonlinear solver to high in the model hierarchy, which then included a key precurser component that computed your input values. By moving the solver down to a lower level of the model, I was able to ensure that the precurser component (LTTGeometry) ran and had valid outputs before you got to the guess_nonlinear of implicit component.
Here is what you had (Notice the implicit solver included LTTGeometry even though the data cycle does not require that component:
I moved both the nonlinear solver and the linear solver down into the LTTCycle group, which then allows the LTTGeometry component to execute before getting to the nonlinear solver and guess_nonlinear step:
My fix is only partially correct, since there is a secondary cycle from the TestCL component that also needs a solver and does not have one. However, that cycle still does not involve the LTTGeometry group. So the fully correct fix is to restructure you model top run geometry first, and then put the LTTCycle and TestCL groups together so you can run a solver over just them. That was a bit more hacking than I wanted to do on your test problem, but you can see the general idea from the adjusted N2 above.
Long Answer
The guess_nonlinear sequence in OpenMDAO does NOT run the compute method of explicit components or of groups. It follows the execution hierarchy, and calls any guess_nonlinear that it finds. So that means that any explicit components you have in your model will NOT get executed, their outputs will not get updated with computed values, and those computed values will not get passed to the inputs of downstream components.
Things get a little tricky when you have deep model hierarchies. The guess_nonlinear method is called as the first step in the nonlinear solver process. If you have a NonLinearRunOnce solver at the top level, it will follow the compute chain down the line calling compute or solve_nonlinear on each child and doing a data transfer after each one. If one of those children happens to be a group with a nonlinear solver, then that solver will call guess_nonlinear on its children (grandchildren of the top group with the NonLinearRunOnce solver) as the first step. So any outputs that were computed by the siblings of this group will be valid, but none of the outputs from the grandchild level will have been computed yet.
You may be wondering why not just have the guess_nonlinear method call the compute for any explicit components? There is a difficult to balance trade off here. If you assume that all explicit components are very cheap to run, then it might make sense to run the compute methods --- or it might not. A lot depends on the cyclic data structure. If some early component in the group needs guesses from the later one, then running its compute isn't going to help you much at all. Perhaps more importantly though, not all explicit components are cheap to run. You might have a very expensive computation, and calling compute as part of the guess process would be way too costly.
The compromise here, if you need some kind of top level guess process, is that you can implement guess_nonlinear at the group level. It's less common to do, but it gives you total control over what happens. You can call whatever you need to call in whatever sequence.
So the absolute key thing to remember is that the only data you have available to you when a guess_nonlinear is called is any data that was computed before your containing solver was executed. That means any thing that was computed before you got to the model scope of the containing solver (not the scope of the component with the guess_method itself).
Your second question: "How can I speed this up when the number of nodes gets large?"
This one not possible to give a generic answer to at all. I noticed that you have already specified sparse partial derivatives. That is a great start, but if its still not fast enough for you then it means you're reaching the limits of what you can do with a DirectSolver. You note that this solver is the only one that gets you through the optimization without issues, which I will take to mean that ScipyKryloventer link description here and PetscKrylov are not converging the linear system well for you --- at least not by themselves. Thats not surprising, as krylov solvers almost always require some kind of preconditioner... and this is why I can't offer a generic answer. Setting up efficient linear solvers for larger-scale compute is a tricky subject. If you look into the literature, you'll find some good suggestions. You can also study open source implementations like VSPAero for some tips.
effectively, you've reached the limit of what simple linear solvers can offer you. From this point forward, OpenMDAO can help a bit by making it easier to implement some preconditioning, but you'll have to suffer the math side yourself.

Tree generation in abalone artificial intelligence

I need to implement an intelligent agent to play Abalone game, for this kind of game the best way to proceed seems a min-max strategy with alpha beta pruning.
I have already implemented a naive search algorithm that use min-max with pruning,
my problem is...
How to generate the nodes of the tree where perform the search?
I have no idea of the right way to do this, and how assign the weigh to each node.
For generating the tree nodes: You need to implement a method that returns a collection of all possible legal moves given the current board position and the player whose turn it is. All these moves will become children of the node representing the current board position. Repeat until memory is exhausted to generate the game tree ;) or rather until you reach a reasonable tree depth.
For alpha-beta search you also need an evaluation function which calculates the weight for each board position/node. You can do some research or think about such a function yourself, maybe considering the number of stones still on the board. However a bad evaluation function can seriously screw up your results, so take care and run a lot of tests.
If you have trouble coming up with a reasonable evaluation function, I recommend you take a look into Monte-Carlo techniques such as UCT.
http://en.wikipedia.org/wiki/Monte_Carlo_tree_search
These tackle the problem using a probabilistic approach and have some nice advantages over alpha-beta. Also they don't require an evaluation function so you could skip this step.
Good luck!
I have published two libraries for move generation in Abalone. You didn't mention the programming language used for your search implementation, but you can easily port the functions.
For C++, https://sourceforge.net/projects/abnet/
For Python, https://gitlab.com/peer.sommerlund/haliotis
For an evaluation function, distance between all your marbles, or distance to their gravity center (same thing), works nicely. Tino Werner used this with a twist for his program that won ICGA 2003.
For understanding distance when using hex coordinates, I can recommend Amit Patel's page: https://www.redblobgames.com/grids/hexagons/

Signal classification - recognise a signal with AI

I have a problem with recognising a signal. Let say the signal is a quasiperiodic signal, the period time has finite limits. The "shape" of the signal must match some criteria, so the actual algorithm using signal processing techniques such as filtering, derivating the the signal, looking for maximum and minimum values. It has a good rate at finding the good signals, but the problem is it also detects wrong shapes too.
So I want to use Aritifical Intelligence - mainly Neural Networks - to overcome this problem. I thought that a multi layer network with some average inputs (the signal can be reduced) and one output whould shows the "matching" from 0..1. However the problem is that I never did such a thing, so I am asking for help, how to achive something like this? How to teach the neural network to get the expected results? (let say I have vectors for inputs which should give 1 as output)
Or this whole idea is a wrong approximation for the problem? I am open to any learning algorithms or idea to learn and use to overcome on this problem.
So here is a figure on the measured signal(s) (values and time is not a concern now) and you can see a lot "wrong" ones, the most detected signals are good as mentioned above.
Your question can be answered in a broad manner. You should consider editing it to prevent it to be closed.
But anyway, Matlab had a lot of built-in function and toolbox to support Artificial Intelligence, with a lot of sample code available, which you can modify and refer to. You can find some in Matlab FileExchange.
And I know reading a lot of technical paper for Artificial Intelligence is a daunting task, so good luck!
You can try to build a neural network using Neuroph. You can inspire from "http://neuroph.sourceforge.net/TimeSeriesPredictionTutorial.html".
On the other hand, it is possible to approximate the signal using Fourier transformation.
You can try 1D convolution. So the basic idea is you give a label 0: bad, 1: good to each signal value at each timestamp. After this, you can model
model = Sequential()
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding = 'same', input_shape=(1,1)))
model.add(Bidirectional(LSTM(20, return_sequences=True)))
model.add(Conv1D(filters=64, kernel_size=3, activation='relu', padding = 'same'))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(100, activation='sigmoid'))
model.add(Dense(2, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
Train the model and then give it a new signal to predict. It will predict given series to 0 and 1 values. if count of 0 is more than count of 1, the signal is not good.

AI Minesweeper project

I need to implement Minesweeper solver. I have started to implement rule based agent.
I have implemented certain rules. I have a heuristic function for choosing best matching rule for current cell (with info about surrounding cells) being treated. So for each chosen cell it can decide for 8 surroundings cells to open them, to mark them or to do nothing. I mean. at the moment, the agent gets as an input some revealed cell and decides what to do with surrounding cells (at the moment, the agent do not know, how to decide which cell to treat).
My question is, what algorithm to implement for deciding which cell to treat?
Suppose, for, the first move, the agent will reveal a corner cell (or some other, according to some rule for the first move). What to do after that?
I understand that I need to implement some kind of search. I know many search algorithms (BFS, DFS, A-STAR and others), that is not the problem, I just do not understand how can I use here these searches.
I need to implement it in a principles of Artificial Intelligence: A modern approach.
BFS, DFS, and A* are probably not appropriate here. Those algorithms are good if you are trying to plan out a course of action when you have complete knowledge of the world. In Minesweeper, you don't have such knowledge.
Instead, I would suggest trying to use some of the logical inference techniques from Section III of the book, particularly using SAT or the techniques from Chapter 10. This will let you draw conclusions about where the mines are using facts like "one of the following eight squares is a mine, and exactly two of the following eight squares is a mine." Doing this at each step will help you identify where the mines are, or realize that you must guess before continuing.
Hope this helps!
I ported this (with a bit of help). Here is the link to it working: http://robertleeplummerjr.github.io/smartSweepers.js/ . Here is the project: https://github.com/robertleeplummerjr/smartSweepers.js
Have fun!

Resources