Saving and loading in JSON#
A laminate designed in one program is often needed in another: a finite element model, an optimisation script or a web page. This example saves a Laminate with save_json, loads it with load_json, embeds it in the input file of a model with to_dict and from_dict, and compares every stored attribute of the loaded laminate with the original, see Saving and loading.
There is no theory and no literature value here: the reference is the original object. All the public attributes are stored, including the derived ones (the stiffnesses, the mass integrals, the ply stiffnesses), such that the loaded object is the saved one without any recomputation, and the comparison is exact, not within a tolerance.
[1]:
import io
import json
import tempfile
from pathlib import Path
import numpy as np
from composites import (laminated_plate, to_dict, from_dict, save_json,
load_json)
tmp_path = Path(tempfile.mkdtemp())
Saving and loading a file#
An unsymmetric laminate with an offset and ply densities, so that every matrix and every moment of the density is non-trivial. The file starts with the keys 'type', 'format_version' and 'composites_version', followed by the attributes in 'data'.
[2]:
laminaprop = (142e9, 8.7e9, 0.28, 5.1e9, 5.1e9, 3.2e9)
lam = laminated_plate([0, 45, -30, 90], plyts=[0.2e-3, 0.3e-3, 0.25e-3,
0.15e-3], laminaprop=laminaprop, rho=1600.,
offset=0.1e-3)
fname = tmp_path / 'laminate.json'
save_json(lam, fname)
print(fname.read_text()[:400], '...')
{
"type": "Laminate",
"format_version": 2,
"composites_version": "0.10.3",
"data": {
"A11": 64490040.283638485,
"A12": 17575300.75732787,
"A16": -617687.8622447681,
"A22": 41049948.60948986,
"A26": 6209398.685194427,
"A66": 19962318.99818508,
"B11": -629.8526230785167,
"B12": 1846.216531491547,
"B16": -2932.446395141969,
"B22": 11006.478600873827,
...
Comparing the loaded laminate with the original#
The laminate is loaded from the file name and from a file object written without indentation (indent=None, a compact file in one line). For each attribute stored in 'data' that is a number or an array, the loaded value is compared with the original one; the plies are compared through their stiffnesses q11L, …, q55L.
[3]:
data = json.loads(fname.read_text())['data']
buf = io.StringIO()
save_json(lam, buf, indent=None)
print('lines of the compact file:', buf.getvalue().count('\n') + 1)
buf.seek(0)
def compare(lam_a, lam_b):
"""Number of attributes compared and number of them not equal"""
n, diff = 0, 0
for name, value in data.items():
if isinstance(value, (int, float)) or (isinstance(value, list) and
value and isinstance(value[0], (int, float, list))):
a = np.asarray(getattr(lam_a, name), dtype=float)
b = np.asarray(getattr(lam_b, name), dtype=float)
n += 1
diff += not np.array_equal(a, b, equal_nan=True)
for pa, pb in zip(lam_a.plies, lam_b.plies):
for name in ('q11L', 'q12L', 'q16L', 'q22L', 'q26L', 'q66L',
'q44L', 'q45L', 'q55L'):
n += 1
diff += getattr(pa, name) != getattr(pb, name)
return n, diff
print('%-26s %12s %12s' % ('loaded from', 'compared', 'not equal'))
for label, loaded in (('file name', load_json(fname)),
('compact file object', load_json(buf))):
print('%-26s %12d %12d' % ((label,) + compare(lam, loaded)))
lines of the compact file: 1
loaded from compared not equal
file name 103 0
compact file object 103 0
Embedding a laminate in another JSON document#
to_dict returns only JSON types (dict, list, str, int, float, None), with the keys 'type', 'format_version', 'composites_version' and 'data', so the laminate can be one entry of the input file of a model. from_dict reads it back.
[4]:
doc = {'name': 'skin', 'mesh_size': 0.01, 'laminate': to_dict(lam)}
fname = tmp_path / 'model.json'
with open(fname, 'w') as f:
json.dump(doc, f)
with open(fname) as f:
doc2 = json.load(f)
lam2 = from_dict(doc2['laminate'])
print('keys of the model file:', sorted(doc2))
print('keys of the laminate: ', sorted(doc2['laminate']))
print()
print('%-14s %26s' % ('attribute', 'max |loaded - original|'))
for name in ('ABD', 'Ats', 'intrhoz6'):
print('%-14s %26.1e' % (name, np.abs(np.asarray(getattr(lam2, name))
- np.asarray(getattr(lam, name))).max()))
n, diff = compare(lam, lam2)
print('\n%d attributes compared, %d not equal' % (n, diff))
keys of the model file: ['laminate', 'mesh_size', 'name']
keys of the laminate: ['composites_version', 'data', 'format_version', 'type']
attribute max |loaded - original|
ABD 0.0e+00
Ats 0.0e+00
intrhoz6 0.0e+00
103 attributes compared, 0 not equal