Decompose a Quantum Circuit in Cirq - linear-algebra

I am working on Cirq and need to perform certain unitary operations on qubits. For that, I am using the MatrixGate() function in Cirq. Unlike Qiskit, I could not find any function like decompose or transpile to simplify the Unitary operation into basic U3 and CNOT gates.
For instance, if I want to act the following Unitary Operator,
Unitary Operator
To do this I use this code in Qiskit. Looking for something equivalent in Cirq.
qc=QuantumCircuit(2)
qc.unitary(U,[0,1])
qc=transpile(qc,basis_gates=['cx','u3'])
qc.draw(output='mpl')
Unitary Gate
After using Transpile function in Qiskit
Transpiled Unitary Gate
I even tried to work up the Cosine-Sine Decomposition Algorithm which Qiskit uses to decompose these Unitary Operations. As mentioned in the paper, Quantum Circuits for Isometries, but they do not trivially yield the required decomposition.
Please help by either suggesting :
Some code in Cirq to decompose circuits or
A workaround to export Qiksit circuits to Cirq or
A simpler algorithm to decompose Unitary Operations.

An example of such a method is cirq.two_qubit_matrix_to_operations. It uses the kak decomposition (cartan decomposition) to determine how to translate a unitary matrix into a series of operations with minimal number of CZ gates.
import cirq
desired_matrix = cirq.testing.random_unitary(dim=4)
synthesized_operations = cirq.two_qubit_matrix_to_operations(
cirq.LineQubit(0),
cirq.LineQubit(1),
desired_matrix,
allow_partial_czs=False,
)
circuit = cirq.Circuit(synthesized_operations)
synthesized_matrix = cirq.unitary(circuit)
cirq.testing.assert_allclose_up_to_global_phase(
desired_matrix,
synthesized_matrix,
atol=1e-4
)
print(desired_matrix.round(3))
print(circuit)
Prints (for example):
[[ 0.234-0.169j -0.81 +0.038j -0.327+0.138j -0.364-0.029j]
[-0.503-0.407j 0.221-0.206j 0.063+0.144j -0.629-0.264j]
[ 0.271+0.338j 0.337-0.128j -0.343+0.731j -0.165+0.052j]
[ 0.504+0.236j 0.222+0.269j 0.244-0.371j -0.608-0.043j]]
0: ───PhX(-0.283)^0.631───#───PhX(0.673)^0.5────#───PhX(-0.375)^0.5───#───PhX(0.827)^0.147───Z^-0.269───
│ │ │
1: ───PhX(0.508)^0.338────#───PhX(0.65)^(5/6)───#───PhX(0.65)^0.995───#───PhX(0.302)^0.512───Z^-0.516───

Related

Combine two 3D transformations expressed as Vector3 and Quaternion without matrix multiplication

We're working in C but would be happy to find example code in any language!
Psuedo-signature of function required:
apply_transform({tr1:Vector3, rot1:Quaternion}, {tr2:Vector3, rot2:Quaternion}) =>
{tr:Vector3, rot:Quaternion} // result
At the moment we achieve this by:
Composing input translation and rotation parameters into two Matrix4
Multiplying the matrices
Decomposing into the resulting translation and rotation
This works fine but is cumbersome and I'm hoping there is a more efficient way. I think the solution involves dual quaternions, but my math skills aren't up to the task.

How can OpenMDAO be used to solve a linear system of equations without inverting the A matrix?

I have a system of equations that is in the form:
Ax = b
Where A and b are a mixture of known states and state rates derived from earlier components and x is a vector of four yet unknown state rates. I've used Matlab to linearise the problem, all I need to do now is to create some components to find x. However, the inverse of A is large in terms of the number of variables in each index, so I can't just turn these into a straightforward linear equation. Could someone suggest a route to go?
I don't fully understand what you mean by "the inverse of A is large in terms of the number of variables in each index", however I think mean that the inverse of A is to larger and dense to compute and store in memory.
OpenMDAO or not, When you run into this situation you are forced to use an iterative linear solver such as gmres. So that is broadly the approach that is needed here too.
OpenMDAO does have a LinearSystemComponent that you can use as a rough blueprint here. However, it does compute a factorization and store it which is not what you want. Regardless, it gives you the blueprint for how to represent a linear system as an implicit component in OpenMDAO.
Broadly, you have to think of defining a linear residual:
R = Ax-b = 0
Your component will have two inputs A and b, and and one output x.
The two key methods here are apply_nonlinear and solve_nonlinear. I realize that the word nonlinear in the method names is confusing. OpenMDAO assumes that the analysis is nonlinear. In your case it happens to be linear, but you use the nonlinear methods all the same.
I will assume that, although you can't compute/store [A] inverse you can compute/store A (perhaps in a sparse format). In that case you might pass the sparse data array of [A] as the input and fill the sparse matrix as needed from that.
the apply_nonlinear method would look like this:
def apply_nonlinear(self, inputs, outputs, residuals):
"""
R = Ax - b.
Parameters
----------
inputs : Vector
unscaled, dimensional input variables read via inputs[key]
outputs : Vector
unscaled, dimensional output variables read via outputs[key]
residuals : Vector
unscaled, dimensional residuals written to via residuals[key]
"""
residuals['x'] = inputs['A'].dot(outputs['x']) - inputs['b']
The key to your question is really the solve_nonlinear method. It would look something like this (using scipy gmres):
def solve_nonlinear(self, inputs, outputs):
"""
Use numpy to solve Ax=b for x.
Parameters
----------
inputs : Vector
unscaled, dimensional input variables read via inputs[key]
outputs : Vector
unscaled, dimensional output variables read via outputs[key]
"""
x, exitCode = gmres(inputs['A'], inputs['b'])
outputs['x'] = x

What is the domain of trigonometric functions in Eiffel? Is it [-pi/4,+pi/4]?

In Eiffel, the class DOUBLE_MATH defines trigonometric functions. When I see the interface of this class as shown here, it says
cosine (v: REAL_64): REAL_64
-- Trigonometric cosine of radian `v' approximated
-- in the range [-pi/4, +pi/4]
and
sine (v: REAL_64): REAL_64
-- Trigonometric sine of radian `v' approximated
-- in range [-pi/4, +pi/4]
and
tangent (v: REAL_64): REAL_64
-- Trigonometric tangent of radian `v' approximated
-- in range [-pi/4, +pi/4]
It seems to claim that the trigonometric functions will only work in the domain [-pi/4,+pi/4]. However, when I tried using them for other values, they seemed to work.
I am worried that it might occasionally fail, or that the success I saw is in fact a form of undefined behavior that cannot be relied upon.
Is it safe to use the functions outside the given domain? If so, why is this domain specified? If not, why is it made such that the functions work only in this domain?
The functions are implemented as wrappers of the corresponding C functions from math.h. Because Eiffel can be compiled for virtually any platform with a C compiler, the comment makes sure to restrict the domain to most restrictive domains of C compiler implementations. Also, some CPUs provide direct support for trigonometric functions, but their precision goes down if the input value is beyond a given range.
To summarize, you need to check the manual of the C compiler for the platforms you are going to use for the specific ranges of trigonometric functions, or, alternatively, make sure the input value is in the range as specified in the comment.

Solve system of implicit ODE with Scilab

I'm modelling an overhead crane and obtained the following equations:
I'm noob when it comes to Scilab and so far I only simullated (using ODE) linear systems with no more than two degrees of freedom, which are simple systems that I can easily convert to am matrix and integrate it using ODE.
But this system in particular I have no clue how to simulate it, not because of the sin and cos functions, but because of the fact that I don't know how to put it in a state space matrix.
I've looked for a few tutorials (listed bellow) but I didn't understand any of those, can somebody tell me how I do it, or at least point where I could learn it?
http://www.openeering.com/sites/default/files/Nonlinear_Systems_Scilab.pdf
http://www.math.univ-metz.fr/~sallet/ODE_Scilab.pdf
Thank you, and sorry about my english
The usual form means writing in terms of first order derivatives. So you'll have relations where the 2nd derivative terms will be written as:
x'' = d(x')/fx
Substitute these into the equations you have. You'll end up with eight simultaneous ODEs to solve instead of four, with appropriate initial conditions.
Although this ODE system is implicit, you can solve it with a classical (explicit) ODE solver by reformulating it this way: if you define X=(x,L,theta,q)^T then your system can be reformulated using matrix algebra as A(X,X') * X" = B(X,X'). Please note that the first order form of this system is
d/dt(X,X') = ( X', A(X,X')^(-1)*B(X,X') )
Suppose now that you have defined two Scilab functions A and B which actually compute their values w.r.t. to the values of Xand X'
function out = A(X,Xprime)
x=X(1)
L=X(2)
theta=X(3)
qa=X(4)
xd=XPrime(1)
Ld=XPrime(2)
thetad=XPrime(3)
qa=XPrime(4);
...
end
function out = B(X,Xprime)
...
end
then the right hand side of the system of 8 ODEs, as it can be given to the ode function of Scilab can be coded as follows
function dstate_dt = rhs(t,state)
X = state(1:4);
Xprime = state(5:8);
out = [ Xprime
A(X,Xprime) \ B(X,Xprime)]
end
Writing the code of A() and B() according to the given equations is the only remaining (but quite easy) task.

algorithm to find derivative

I'm writing program in Python and I need to find the derivative of a function (a function expressed as string).
For example: x^2+3*x
Its derivative is: 2*x+3
Are there any scripts available, or is there something helpful you can tell me?
If you are limited to polynomials (which appears to be the case), there would basically be three steps:
Parse the input string into a list of coefficients to x^n
Take that list of coefficients and convert them into a new list of coefficients according to the rules for deriving a polynomial.
Take the list of coefficients for the derivative and create a nice string describing the derivative polynomial function.
If you need to handle polynomials like a*x^15125 + x^2 + c, using a dict for the list of coefficients may make sense, but require a little more attention when doing the iterations through this list.
sympy does it well.
You may find what you are looking for in the answers already provided. I, however, would like to give a short explanation on how to compute symbolic derivatives.
The business is based on operator overloading and the chain rule of derivatives. For instance, the derivative of v^n is n*v^(n-1)dv/dx, right? So, if you have v=3*x and n=3, what would the derivative be? The answer: if f(x)=(3*x)^3, then the derivative is:
f'(x)=3*(3*x)^2*(d/dx(3*x))=3*(3*x)^2*(3)=3^4*x^2
The chain rule allows you to "chain" the operation: each individual derivative is simple, and you just "chain" the complexity. Another example, the derivative of u*v is v*du/dx+u*dv/dx, right? If you get a complicated function, you just chain it, say:
d/dx(x^3*sin(x))
u=x^3; v=sin(x)
du/dx=3*x^2; dv/dx=cos(x)
d/dx=v*du+u*dv
As you can see, differentiation is only a chain of simple operations.
Now, operator overloading.
If you can write a parser (try Pyparsing) then you can request it to evaluate both the function and derivative! I've done this (using Flex/Bison) just for fun, and it is quite powerful. For you to get the idea, the derivative is computed recursively by overloading the corresponding operator, and recursively applying the chain rule, so the evaluation of "*" would correspond to u*v for function value and u*der(v)+v*der(u) for derivative value (try it in C++, it is also fun).
So there you go, I know you don't mean to write your own parser - by all means use existing code (visit www.autodiff.org for automatic differentiation of Fortran and C/C++ code). But it is always interesting to know how this stuff works.
Cheers,
Juan
Better late than never?
I've always done symbolic differentiation in whatever language by working with a parse tree.
But I also recently became aware of another method using complex numbers.
The parse tree approach consists of translating the following tiny Lisp code into whatever language you like:
(defun diff (s x)(cond
((eq s x) 1)
((atom s) 0)
((or (eq (car s) '+)(eq (car s) '-))(list (car s)
(diff (cadr s) x)
(diff (caddr s) x)
))
; ... and so on for multiplication, division, and basic functions
))
and following it with an appropriate simplifier, so you get rid of additions of 0, multiplying by 1, etc.
But the complex method, while completely numeric, has a certain magical quality. Instead of programming your computation F in double precision, do it in double precision complex.
Then, if you need the derivative of the computation with respect to variable X, set the imaginary part of X to a very small number h, like 1e-100.
Then do the calculation and get the result R.
Now real(R) is the result you would normally get, and imag(R)/h = dF/dX
to very high accuracy!
How does it work? Take the case of multiplying complex numbers:
(a+bi)(c+di) = ac + i(ad+bc) - bd
Now suppose the imaginary parts are all zero, except we want the derivative with respect to a.
We set b to a very small number h. Now what do we get?
(a+hi)(c) = ac + hci
So the real part of this is ac, as you would expect, and the imaginary part, divided by h, is c, which is the derivative of ac with respect to a.
The same sort of reasoning seems to apply to all the differentiation rules.
Symbolic Differentiation is an impressive introduction to the subject-at least for non-specialist like me :) The code is written in C++ btw.
Look up automatic differentiation. There are tools for Python. Also, this.
If you are thinking of writing the differentiation program from scratch, without utilizing other libraries as help, then the algorithm/approach of computing the derivative of any algebraic equation I described in my blog will be helpful.
You can try creating a class that will represent a limit rigorously and then evaluate it for (f(x)-f(a))/(x-a) as x approaches a. That should give a pretty accurate value of the limit.
if you're using string as an input, you can separate individual terms using + or - char as a delimiter, which will give you individual terms. Now you can use power rule to solve for each term, say you have x^3 which using power rule will give you 3x^2, or suppose you have a more complicated term like a/(x^3) or a(x^-3), again you can single out other variables as a constant and now solving for x^-3 will give you -3a/(x^2). power rule alone should be enough, however it will require extensive use of the factorization.
Unless any already made library deriving it's quite complex because you need to parse and handle functions and expressions.
Deriving by itself it's an easy task, since it's mechanical and can be done algorithmically but you need a basic structure to store a function.

Resources