def test_stacking_quantum(simulator, value1=(numpy.random.randint(0, 1000) / 1000.0 * (numpy.pi / 2.0)), value2=(numpy.random.randint(0, 1000) / 1000.0 * (numpy.pi / 2.0))): a = Variable('a') b = Variable('b') values = {a: value1, b: value2} H1 = tq.paulis.X(0) H2 = tq.paulis.Y(0) U1= tq.gates.Ry(angle=a,target=0) U2= tq.gates.Rx(angle=b,target=0) e1=ExpectationValue(U1,H1) e2=ExpectationValue(U2,H2) stacked= tq.objective.vectorize([e1, e2]) out=simulate(stacked,variables=values,backend=simulator) v1=out[0] v2=out[1] an1= np.sin(a(values)) an2= -np.sin(b(values)) assert np.isclose(v1+v2,an1+an2,atol=1e-3) # not gonna contract, lets make gradient do some real work ga=grad(stacked,a) gb=grad(stacked,b) la=[tq.simulate(x,variables=values) for x in ga] print(la) lb=[tq.simulate(x,variables=values) for x in gb] print(lb) tota=np.sum(np.array(la)) totb=np.sum(np.array(lb)) gan1= np.cos(a(values)) gan2= -np.cos(b(values)) assert np.isclose(tota+totb,gan1+gan2,atol=1e-3)
def test_stacking(): a=Variable('a') b=Variable('b') def f(x): return np.cos(x)**2. + np.sin(x)**2. funcs=[f,f,f,f] vals = {Variable('a'):numpy.random.uniform(0,np.pi),Variable('b'):numpy.random.uniform(0,np.pi)} O = VectorObjective(argsets=[[a],[b],[a],[b]],transformations=funcs) O1 = O.apply_op_list(funcs) O2 = O1/4 output = simulate(O2,variables=vals) assert np.isclose(1.,np.sum(output))