5
5
from tidy3d .exceptions import SetupError
6
6
7
7
8
- def plot_sim_3d (sim , width = 800 , height = 800 ) -> None :
8
+ def plot_scene_3d (scene , width = 800 , height = 800 ) -> None :
9
+ import json
10
+ import gzip
11
+ from base64 import b64encode
12
+ from io import BytesIO
13
+ import h5py
14
+
15
+ # Serialize scene to HDF5 in-memory
16
+ buffer = BytesIO ()
17
+ scene .to_hdf5 (buffer )
18
+ buffer .seek (0 )
19
+
20
+ # Open source HDF5 for reading and prepare modified copy
21
+ with h5py .File (buffer , "r" ) as src :
22
+ buffer2 = BytesIO ()
23
+ with h5py .File (buffer2 , "w" ) as dst :
24
+
25
+ def copy_item (name , obj ):
26
+ if isinstance (obj , h5py .Group ):
27
+ dst .create_group (name )
28
+ for k , v in obj .attrs .items ():
29
+ dst [name ].attrs [k ] = v
30
+ elif isinstance (obj , h5py .Dataset ):
31
+ data = obj [()]
32
+ if name == "JSON_STRING" :
33
+ # Parse and update JSON string
34
+ json_str = (
35
+ data .decode ("utf-8" )
36
+ if isinstance (data , (bytes , bytearray ))
37
+ else data
38
+ )
39
+ json_data = json .loads (json_str )
40
+ json_data ["size" ] = list (scene .size )
41
+ json_data ["center" ] = list (scene .center )
42
+ json_data ["grid_spec" ] = {}
43
+ new_str = json .dumps (json_data )
44
+ dst .create_dataset (name , data = new_str .encode ("utf-8" ))
45
+ else :
46
+ dst .create_dataset (name , data = data )
47
+ for k , v in obj .attrs .items ():
48
+ dst [name ].attrs [k ] = v
49
+
50
+ src .visititems (copy_item )
51
+ buffer2 .seek (0 )
52
+
53
+ # Gzip the modified HDF5
54
+ gz_buffer = BytesIO ()
55
+ with gzip .GzipFile (fileobj = gz_buffer , mode = "wb" ) as gz :
56
+ gz .write (buffer2 .read ())
57
+ gz_buffer .seek (0 )
58
+
59
+ # Base64 encode and display with gzipped flag
60
+ sim_base64 = b64encode (gz_buffer .read ()).decode ("utf-8" )
61
+ plot_sim_3d (sim_base64 , width = width , height = height , is_gz_base64 = True )
62
+
63
+
64
+ def plot_sim_3d (sim , width = 800 , height = 800 , is_gz_base64 = False ) -> None :
9
65
"""Make 3D display of simulation in ipyython notebook."""
10
66
11
67
try :
@@ -19,10 +75,14 @@ def plot_sim_3d(sim, width=800, height=800) -> None:
19
75
from base64 import b64encode
20
76
from io import BytesIO
21
77
22
- buffer = BytesIO ()
23
- sim .to_hdf5_gz (buffer )
24
- buffer .seek (0 )
25
- base64 = b64encode (buffer .read ()).decode ("utf-8" )
78
+ if not is_gz_base64 :
79
+ buffer = BytesIO ()
80
+ sim .to_hdf5_gz (buffer )
81
+ buffer .seek (0 )
82
+ base64 = b64encode (buffer .read ()).decode ("utf-8" )
83
+ else :
84
+ base64 = sim
85
+
26
86
js_code = """
27
87
/**
28
88
* Simulation Viewer Injector
0 commit comments