Hi Kasper,
Many thanks for the quick reply. Yes, that did the trick.
Here is a short example of what I'm using these dict's for. I have two Cadabra programs, foo.cdb
,
{a,b,c,d,e,f#}::Indices.
\partial{#}::PartialDerivative.
obj01 := A_{a b};
obj02 := \partial_{b}{B_{a}};
obj03 := A_{a b} + \partial_{b}{B_{a}};
import cdblib
cdblib.create ('my-lib.json')
cdblib.put ('key01',obj01,'my-lib.json')
cdblib.put ('key02',obj02,'my-lib.json')
cdblib.put ('key03',obj03,'my-lib.json')
and bah.cdb
,
{a,b,c,d,e,f#}::Indices.
\partial{#}::PartialDerivative.
import cdblib
new01 = cdblib.get ('key01','my-lib.json');
new02 = cdblib.get ('key02','my-lib.json');
new03 = cdblib.get ('key03','my-lib.json');
The foo.cdb
code creates three objects and saves them to a dict. The bah.cdb
codes reads that dict to create three new objects identical to the first three.
Here is the code that defines the Python/Cadabra module, cdblib.py
def create (file_name):
import json, io, os, errno
try:
os.remove(file_name) # delete the file if it exsists
with open(file_name, 'w'): pass # create an empty file
except OSError as e:
if e.errno == errno.ENOENT: # if the file doesn't exit then
with open(file_name, 'w'): pass # create an empty file
else: # otherwise
raise # report an exception
# Create and save an empty dict
data_out = {}
with io.open(file_name, 'w', encoding='utf-8') as out_file:
out_file.write(json.dumps(data_out,
indent=4,
sort_keys=True,
separators=(',', ': '),
ensure_ascii=False)+'\n')
def put (key_name,object,file_name):
import json, io, os
import cadabra2
__cdbkernel__ = cadabra2.__cdbkernel__
# Read the current dict
with io.open(file_name) as inp_file:
data_out = json.load(inp_file)
# Add a new entry to the dict
data_out[key_name] = str(object)
# data_out[key_name] = object.input_form()
# Save the updated dict
with io.open(file_name, 'w', encoding='utf-8') as out_file:
out_file.write(json.dumps(data_out,
indent=4,
sort_keys=True,
separators=(',', ': '),
ensure_ascii=False)+'\n')
def get (key_name,file_name):
import json, io, os
import cadabra2
__cdbkernel__ = cadabra2.__cdbkernel__
# Read the current dict
with io.open(file_name) as inp_file:
data_inp = json.load(inp_file)
# Return one entry from the dict
return cadabra2.Ex (data_inp[key_name])