#!/usr/bin/env python # coding: utf-8 # In[ ]: import numpy as np import k3d # In[ ]: def get_plot(): iteration = 4 size = 3**iteration voxels = np.ones((size, size, size)); def iterate(length, x, y, z): nl = length // 3 if nl < 1: return margin = (nl-1) // 2 voxels[z-margin:z+margin+1, y-margin:y+margin+1, :] = 0 voxels[z-margin:z+margin+1, :, x-margin:x+margin+1] = 0 voxels[:, y-margin:y+margin+1, x-margin:x+margin+1] = 0 for ix,iy,iz in np.ndindex((3,3,3)): if (1 if ix !=1 else 0) + (1 if iy != 1 else 0) + (1 if iz != 1 else 0) !=2: iterate(nl, x + (ix-1) * nl, y + (iy-1) * nl , z + (iz-1) * nl) iterate(size, size//2, size//2, size//2) plot = k3d.plot() plot += k3d.voxels(voxels.astype(np.uint8), compression_level=9) return plot # # Create and save to *.k3d file # In[ ]: plot = get_plot() plot.display() data = plot.get_binary_snapshot() with open('binary_snapshot.k3d', 'wb') as f: f.write(data) # # Load from *.k3d file # In[ ]: plot2 = k3d.plot() with open('binary_snapshot.k3d', 'rb') as f: plot2.load_binary_snapshot(f.read()) plot2.display() # # Save to standalone *.html file # # Standalone snapshot produce HTML file that include any necessary data to draw plot with data without internet connection/ # In[ ]: plot3 = get_plot() plot3.display() data = plot3.get_snapshot() with open('snapshot_standalone.html', 'w') as f: f.write(data) # # Save to online *.html file # # Online snapshot exclude whole js code of k3d. Produced HTML file contain a minimum code to download a K3D from NPM and display a plot # In[ ]: plot4 = get_plot() plot4.snapshot_type = 'online' plot4.display() data = plot4.get_snapshot() with open('snapshot_online.html', 'w') as f: f.write(data) # # Save to inline *.html file # # Inline element can be embeded in any html document like Sphinx documentation: # # ``` # .. raw:: html # :file: inline_shapshot.html # ``` # In[ ]: plot5 = get_plot() plot5.snapshot_type = 'inline' plot5.display() data = plot5.get_snapshot() with open('snapshot_inline.html', 'w') as f: f.write(data) # In[ ]: import os for f in ['snapshot_standalone.html', 'snapshot_online.html', 'snapshot_inline.html', 'binary_snapshot.k3d']: print(f, os.stat(f).st_size, 'bytes') # In[ ]: