pythonreshapequtip

How to reshape a 2d numpy.array or Qobj into dims=[[2,2],[2,2]]


Numpy example below


Goal: QuTiP object

The goal of my request is to add two quantum state objects of type Qobj (density matrices) as in the following example of a Werner state (to give it some physical meaning).

import qutip as q
r = .5
state = r * q.ket2dm(q.ghz_state(2)) + (1-r) * q.maximally_mixed_dm(4)

The error message is

TypeError: Incompatible quantum object dimensions

So one could go to the lower dimensional state but then we loose the relevant dimension properties to proceed with the state:

state = r * q.ket2dm(q.ghz_state(2)).data.toarray() + (1-r) * q.maximally_mixed_dm(4)

My attempts like q.Qobj(q.maximally_mixed_dm(4).data.toarray().reshape([[2,2],[2,2]])) all failed as reshape does not handle lists of lists.

The inverse going from dimensions [[2,2],[2,2]] down to [4,4] is not a miracle using reshape or as shown by the conversion to an array. But is the inverse implemented in either numpy nor qutip?


Edit: For people familiar with numpy

How do you reshape a 2d array (e.g. here 4x4) in to a (2x2)x(2x2) one? The built in function of numpy seems to dislike my requested example. It does not accept lists of lists as shown here:

import numpy as np
state = np.identity(4).reshape([[2,2],[2,2]])

I was surprised that no one ever asked this question before!


Solution

  • You are using reshape in the wrong way. It takes a tuple of the dimensions as an argument (see the docs) and not a tuple of tuples or list of lists with the dimensions as elements - how should that work? I think you are mixing the depth of your list of lists with the dimensionality (which are expected to be the numeric entries of the tuple).

    I am not sure what exactly you wanna end up with but I guess one of the following:

    state = np.identity(4).reshape((2,2,2,2))
    state = np.identity(4).reshape((4,2,2))
    state = np.identity(4).reshape((2,2,4))