In [1]:
%matplotlib inline
import netCDF4
import matplotlib.pyplot as plt
import numpy as np

In [2]:
ds = netCDF4.Dataset('/Users/baart_f/data/delft3d/WinterCycle3_DisSeabed_TSS.nc')

In [3]:
import shapely.affinity
import shapely.geometry

In [4]:
var = ds.variables['suspsedconc']
depth = ds.variables['depth'][1:-1,1:-1]
waterlevel = ds.variables['waterlevel'][0, 1:-1, 1:-1]
x = ds.variables['x'][1:-1,1:-1]
y = ds.variables['y'][1:-1,1:-1]

grid_x = ds.variables['grid_x'][1:-1,1:-1,:]
grid_y = ds.variables['grid_y'][1:-1,1:-1,:]
layer_interf = ds.variables['LayerInterf'][:].squeeze()
layer = ds.variables['Layer'][:].squeeze()
    # sigma positive upward                                           
Z = -np.tile(layer_interf, x.shape + (1,)) \
    * np.repeat((depth + waterlevel)[:,:,np.newaxis], layer_interf.shape[0], 2) \
    - np.repeat(depth[:,:,np.newaxis], layer_interf.shape[0],2) 
    # total water depth
    # total water height from bottom

# convert from structured (curvilinear) to rectilinear grid
pts = [shapely.geometry.Point(x_, y_) for x_, y_ in np.c_[x[0], y[0]]]
distances_x = -np.array([pts[0].distance(pts[i]) for i in range(len(pts))])
pts = [shapely.geometry.Point(x_, y_) for x_, y_ in np.c_[x[:,0], y[:,0]]]
distances_y = np.array([pts[0].distance(pts[i]) for i in range(len(pts))])
distances_x.shape, distances_y.shape, x.shape, depth.shape, Z.shape


Out[4]:
((127,), (169,), (169, 127), (169, 127), (169, 127, 31))

In [5]:
fig, axes = plt.subplots(1,3, sharex=True, figsize=(16,5))
ax0, ax1, ax2 = axes


pc = ax0.pcolormesh(x, y, Z[...,0])
plt.colorbar(pc, ax=ax0)
ax0.set_title('depth layer 0')
pc = ax1.pcolormesh(x, y, Z[...,15])
ax1.set_title('depth layer 15')
plt.colorbar(pc, ax=ax1)
# top interface should follow sealevel
ax2.set_title('depth layer -1')
pc = ax2.pcolormesh(x, y, Z[:-1,:-1,-1])
plt.colorbar(pc, ax=ax2)
fig.tight_layout()



In [6]:
data = var[60,...]
data = data.squeeze()[:,1:-1,1:-1]
# roll the first dimension to the end
data = np.rollaxis(data, 0, 3)
# data[data>=0.00015] = 0.00016
#data[data<0] = 0.0
#data[data<=0.00001] = 0.00001
#data = np.log10(data)
x.shape, data[0].shape


Out[6]:
((169, 127), (127, 30))

In [69]:
centers = np.c_[x.ravel(), y.ravel()]

x_ll = x - np.gradient(x)[0]/2.0 - np.gradient(x)[1]/2.0
x_lr = x - np.gradient(x)[0]/2.0 + np.gradient(x)[1]/2.0
x_ur = x + np.gradient(x)[0]/2.0 + np.gradient(x)[1]/2.0
x_ul = x + np.gradient(x)[0]/2.0 - np.gradient(x)[1]/2.0
y_ll = y - np.gradient(y)[0]/2.0 - np.gradient(y)[1]/2.0
y_lr = y - np.gradient(y)[0]/2.0 + np.gradient(y)[1]/2.0
y_ur = y + np.gradient(y)[0]/2.0 + np.gradient(y)[1]/2.0
y_ul = y + np.gradient(y)[0]/2.0 - np.gradient(y)[1]/2.0

cell_x = np.dstack([x_ll, x_lr, x_ur, x_ul])
cell_y = np.dstack([y_ll, y_lr, y_ur, y_ul])

nodes_x = np.empty((x.shape[0]+1, x.shape[1]+1), dtype='double')
nodes_y = np.empty_like(nodes_x)

nodes_x[:-1,:-1] = x_ul
nodes_x[-1,:-1] = x_ll[-1,:]
nodes_x[:-1,-1] = x_ur[:,-1]
nodes_x[-1,-1] = x_lr[-1,-1]
nodes_y[:-1,:-1] = y_ul
nodes_y[-1,:-1] = y_ll[-1,:]
nodes_y[:-1,-1] = y_ur[:,-1]
nodes_y[-1,-1] = y_lr[-1,-1]


#nodes_x = nodes_x.ravel()
#nodes_y = nodes_y.ravel()
polys = []
n_rows = x.shape[0]
n_cols = x.shape[1]
n_cells = np.prod(x.shape)
print nodes_x.shape, n_cells
maxidx =0 
t        maxidx=max(maxidx, max(*idx))
        x_i = nodes_x.ravel()[idx]
        y_i = nodes_y.ravel()[idx]
        xy_i = np.c_[x_i,y_i]
        polys.append(xy_i)
print maxidx
import matplotlib.collections
patches = matplotlib.collections.PatchCollection((matplotlib.patches.Polygon(xy, closed=True) for xy in polys),  alpha=0.5, facecolor='none', edgecolor='black')
fig, ax = plt.subplots()
ax.add_collection(patches)
ax.autoscale()
ax.set_ylim(5162000, 5167000)
ax.set_xlim(690000, 695000)


(170, 128) 21463
21759
Out[69]:
(690000, 695000)

In [101]:
plt.pcolormesh(distances_x, distances_y, data[:-1, :-1, -10])
plt.colorbar()


Out[101]:
<matplotlib.colorbar.Colorbar instance at 0x10c832b90>

In [8]:
import mayavi.mlab as mlab
from tvtk.api import tvtk


WARNING:traits.has_traits:DEPRECATED: traits.has_traits.wrapped_class, 'the 'implements' class advisor has been deprecated. Use the 'provides' class decorator.

In [55]:
pts = np.c_[X.ravel(), Y.ravel(), Z.ravel()]

grid = tvtk.
grid.print_traits()
grid.point_data.scalars = data.ravel()
grid.point_data.scalars.name = 'sediment'
dataset = mlab.pipeline.add_dataset(grid)
gx = mlab.pipeline.grid_plane(dataset)
gy = mlab.pipeline.grid_plane(dataset)
gy.grid_plane.axis = 'y'
gz = mlab.pipeline.grid_plane(dataset)
gz.grid_plane.axis = 'z'
iso = mlab.pipeline.iso_surface(dataset)
iso.contour.maximum_contour = 0.001
vol = mlab.pipeline.volume(grid)


ERROR:mayavi.core.common:Volume rendering only works with StructuredPoints/ImageData/UnstructuredGrid datasets
_in_set:                   0
_vtk_obj:                  (vtkRectilinearGrid)0x11a299a48
actual_memory_size:        4
bounds:                    (-29699.985284153026, -0.... -0.0012499999720603228)
cell_data:                 <tvtk.tvtk_classes.cell_d...a object at 0x1109da470>
center:                    (-14849.992642076513, 148...13, -0.5004750048974529)
class_name:                'vtkRectilinearGrid'
data_dimension:            3
data_object_type:          3
data_released:             0
debug:                     0
debug_:                    0
dimensions:                array([169, 127,  30])
estimated_memory_size:     0
extent:                    array([  0, 168,   0, 126,   0,  29])
extent_translator:         <tvtk.tvtk_classes.extent...r object at 0x1109dab90>
extent_type:               1
field_data:                <tvtk.tvtk_classes.field_...a object at 0x1109dab90>
global_release_data_flag:  0
global_release_data_flag_: 0
global_warning_display:    1
global_warning_display_:   1
information:               <tvtk.tvtk_classes.inform...n object at 0x1109dab90>
length:                    42002.1602762978
m_time:                    940687
max_cell_size:             8
maximum_number_of_pieces:  -1
number_of_cells:           613872L
number_of_points:          643890L
pipeline_information:      <tvtk.tvtk_classes.inform...n object at 0x1109dab90>
pipeline_m_time:           0
point_data:                <tvtk.tvtk_classes.point_...a object at 0x1109dab90>
producer_port:             <tvtk.tvtk_classes.algori...t object at 0x1109da470>
reference_count:           3
release_data_flag:         0
release_data_flag_:        0
request_exact_extent:      0
request_exact_extent_:     0
scalar_range:              (0.0, 1.0)
source:                    None
update_extent:             array([ 0, -1,  0, -1,  0, -1])
update_ghost_level:        0
update_number_of_pieces:   1
update_piece:              0
update_time:               0
whole_bounding_box:        array([ 0., -1.,  0., -1.,  0., -1.])
whole_extent:              array([ 0, -1,  0, -1,  0, -1])
x_coordinates:             [-0.0, ..., -29699.9852842], length = 127
y_coordinates:             [0.0, ..., 29700.0394107], length = 169
z_coordinates:             [-0.00124999997206, ..., ...9700009823], length = 30
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-a10ccc65aab2> in <module>()
     16 iso = mlab.pipeline.iso_surface(dataset)
     17 iso.contour.maximum_contour = 0.001
---> 18 vol = mlab.pipeline.volume(grid)

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mayavi/tools/pipe_base.pyc in the_function(*args, **kwargs)
     36 def make_function(factory_class):
     37     def the_function(*args, **kwargs):
---> 38         factory = factory_class(*args, **kwargs)
     39         return factory._target
     40 

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mayavi/tools/pipe_base.pyc in __init__(self, parent, **kwargs)
    161         # Now calling the traits setter, so that traits handlers are
    162         # called
--> 163         self.set(**traits)
    164         if scene is not None:
    165             scene.disable_render = not self._do_redraw

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mayavi/tools/pipe_base.pyc in set(self, trait_change_notify, **traits)
    177             try:
    178                 if callback is not None:
--> 179                     callback()
    180                 self._anytrait_changed(trait, value)
    181             except TraitError:

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mayavi/tools/modules.pyc in _vmin_changed(self)
    598         vmin = self.vmin
    599         vmax = self.vmax
--> 600         range_min, range_max = self._target.current_range
    601         if vmin is None:
    602             vmin = range_min

ValueError: need more than 0 values to unpack

In [9]:
mlab.show()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/traitsui/qt4/instance_editor.pyc in <lambda>()
    510         # Make sure the editor is properly disposed
    511         QtCore.QObject.connect( self._button, QtCore.SIGNAL( 'destroyed()' ),
--> 512                                 lambda: ui.dispose() )
    513 
    514         # Check to see if the view was 'modal', in which case it will already

NameError: free variable 'ui' referenced before assignment in enclosing scope

In [58]:
mlab.contour3d(np.swapaxes(np.swapaxes(data, 0,2), 0,1), extent=[0, x.shape[0], 0, x.shape[1],0,5])
mlab.surf(depth, extent=[0, x.shape[0], 0, x.shape[1],0,5])
mlab.outline()

engine = mlab.get_engine()
scene = mlab.gcf()

from mayavi.filters.point_to_cell_data import PointToCellData
point_to_cell_data = PointToCellData()
array_source = engine.scenes[0].children[0]
engine.add_filter(point_to_cell_data, array_source)
from mayavi.modules.volume import Volume
volume = Volume()
volume.print_traits()
engine.add_filter(volume, point_to_cell_data)
mlab.outline()
#volume.update_ctf = 0


_HideShowAction:         <traitsui.menu.Action object at 0x121672b30>
_actors_added:           False
_available_mapper_types: ['FixedPointVolumeRayCastM... 'VolumeTextureMapper2D']
_ctf:                    <tvtk.util.ctf.ColorTransf...on object at 0x121672770>
_icon_path:              '/opt/local/Library/Framew...2.7/site-packages/traits'
_is_running:             False
_mapper_types:           ['TextureMapper2D', 'RayCa...ointVolumeRayCastMapper']
_menu:                   <pyface.ui.qt4.action.menu...er object at 0x1214085f0>
_module_view:            None
_otf:                    <tvtk.util.ctf.PiecewiseFu...on object at 0x121672830>
_ray_cast_function:      None
_ray_cast_functions:     []
_saved_state:            ''
_view_filename:          '/opt/local/Library/Framew...avi/modules/ui/volume.py'
_volume_mapper:          None
_volume_property:        <tvtk.tvtk_classes.volume_...ty object at 0x1216726b0>
_widget_state:           []
actors:                  [<tvtk.tvtk_classes.volume...e object at 0x121672590>]
children_ui_list:        <undefined>
components:              []
current_range:           ()
icon:                    'module.ico'
input_info:              <mayavi.core.pipeline_info...fo object at 0x1176da2f0>
lut_manager:             <mayavi.modules.volume.Vol...er object at 0x121408cb0>
menu_helper:             <mayavi.core.traits_menu.M...er object at 0x1216729b0>
module_manager:          None
name:                    ''
output_info:             <mayavi.core.pipeline_info...fo object at 0x1167acef0>
outputs:                 []
parent:                  None
ray_cast_function:       None
ray_cast_function_type:  ''
recorder:                None
running:                 False
scene:                   None
type:                    ' module'
visible:                 True
volume:                  <tvtk.tvtk_classes.volume....me object at 0x121672590>
volume_mapper:           None
volume_mapper_type:      'TextureMapper2D'
volume_property:         <tvtk.tvtk_classes.volume_...ty object at 0x1216726b0>
widgets:                 []
Out[58]:
<mayavi.modules.outline.Outline at 0x11e2582f0>

In [59]:
mlab.show()

In [43]:
X.min(), X.max(), Y.min(), Y.max(), Z.min(), Z.max()


Out[43]:
(0, 168, 0, 126, -459.86200451850891, -0.46231760899012642)

In [63]:
import IPython.display
IPython.display.Image('plume.png')


Out[63]:

In [ ]: