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