mabuchilab / QNET

Computer algebra package for quantum mechanics and photonic quantum networks
https://qnet.readthedocs.io/
MIT License
71 stars 23 forks source link

LocalSpace.create crashes when using local_identifiers #83

Closed danielwe closed 6 years ago

danielwe commented 6 years ago
from qnet import LocalSpace
hs = LocalSpace.create(0, local_identifiers={'Destroy', 'b'})

Throws exception at instance caching because dict is not hashable. The same happens if passing [('Destroy', 'b')] instead (list is not hashable).

goerz commented 6 years ago

Expression._get_instance_key should use a function _recursive_tuple instead of tuple when converting args and kwargs. This function should recursively translate lists and dicts into tuples (ordered, in the case of dicts - we don't yet rely on the guaranteed ordering in Python >3.6).

There are some other existing classes, e.g. qnet.core.abstract_quantum_algebra.QuantumDerivative that have dealt with the exact same problem by having a custom create. Fixing _get_instance_key might make this custom create unnecessary. But there is the potential problem of incompatibilities between create and init. For all classes where __init__ might accept non-hashable types, there should be an explicit test that instantiating via create results in the same expression as directly calling __init__. This included variations where there might be multiple ways to pass a dict, e.g. as dict, OrderedDict, or list/tuple of key-value-tuples.

Generally, anything __init__ takes, create must also accept, but create is allowed to be more flexible than __init__.

goerz commented 6 years ago

https://github.com/topper-123/freezedata/blob/master/freezedata/freezedata.py might also be interesting to give a look, or there might be other existing implementations. If it's a single file module, we can just copy it into qnet.utils.