Giter VIP home page Giter VIP logo

Comments (3)

albi3ro avatar albi3ro commented on June 26, 2024

I have a fairly hacky patch, but it might be sufficient for your purposes. A better fix might involve with copying and updating Device.execute to change the call signature for expval.

class ProdPatch(qml.operation.Observable):

    def __init__(self, prod_op):
        self.prod_op = prod_op

    @property
    def name(self):
        return [op.name for op in self.prod_op]

    @property
    def parameters(self):
        return self.prod_op.parameters

    @property
    def wires(self):
        return self.prod_op.wires

class MyDevice(Device):
    author = "Christian Gogolin"
    pennylane_requires = ">=0.29.1"
    name = "MyDevice"
    short_name = "my.device"
    version = "0.1.0"

    _capabilities = {
        "tensor_observables": True,
    }

    @property
    def observables(self):
        return ["PauliZ", "Prod"]

    def supports_observable(self, observable):
        if isinstance(observable, list):
            return all(self.supports_observable(ob) for ob in observable)
        return super().supports_observable(observable)
    
    def execute(self, queue, observables, parameters=None, **kwargs):
        new_measurements = []
        for mp in observables:
            if mp.obs and isinstance(mp.obs, qml.ops.Prod):
                new_measurements.append( type(mp)(obs=ProdPatch(mp.obs)) )
            else:
                new_measurements.append(mp)
        return super().execute(queue, new_measurements, parameters=parameters, **kwargs)
    
    def __init__(self, wires, *args, **kwargs):
        if wires != 2:
            raise NotImplementedError()
        self._state = None
        super().__init__(wires, *args, **kwargs)
    
    def apply(self, operation, wires, par):
        raise NotImplementedError(f"operation={operation}")

    def expval(self, observable, wires, par):
        if isinstance(observable, list):
            observables = observable
            for observable in observables:
                if observable != "PauliZ":
                    raise NotImplementedError()
            return np.prod([self.expval(observable, wire, par) for observable, wire in zip(observables, wires)])

        if observable != "PauliZ":
            raise NotImplementedError()
        return float(np.real(np.dot(self._state.conj().T, qml.matrix(qml.PauliZ(wires), wire_order=qml.wires.Wires([0, 1])).dot(self._state))).item())

    @property
    def operations(self):
        return []

    def reset(self):
        self._state = np.array([1., 0., 0., 0.])

I think this case actually helps demonstrate why we went though all the effort to both change operator arithmetic and to move to a new device interface.

  1. Tensor.name broke the interface set out in Operator. Every other operator had it's name be a string, but Tensor had its name be a list of strings. This exception can be difficult to anticipate and account for.

  2. A name or type by itself can be insufficient to determine whether or not something is supported. For example, a hamiltonian containing a Hermitian. The set of strings might say the device supports Hamiltonian, but then it won't be able to support a Hamiltonian that contains a Hermitian.

  3. Legacy devices (qml.Device) rely on things hardcoded into an "abstract base class" that make it rather difficult to extend and customize.

We can add in some patches to qml.Device if that would help, but those wouldn't be released till our next release in July.

from pennylane.

cvjjm avatar cvjjm commented on June 26, 2024

Thanks for going through the trouble of proposing a workaround!!!

I agree that it is rather ugly, but it may help me not waste too much time on code that I anyway plan to port over to the new device API...

I reported this here just because it was a bit annoying to experience breaking changes to a part of the codebase that is deprecated and which I had therefore hoped would not change, but I understand that this is due to the coupling between the legacy devices and the operator arithmetic.

from pennylane.

CatalinaAlbornoz avatar CatalinaAlbornoz commented on June 26, 2024

Thank you for reporting this here @cvjjm! It does help us a lot to receive your feedback, both the good and bad experiences.

from pennylane.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.