########################################################################
#
#    Vision Network - Python source code - file generated by vision
#    Wednesday 11 April 2007 13:25:04 
#    
#       The Scripps Research Institute (TSRI)
#       Molecular Graphics Lab
#       La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#   
# revision: Guillaume Vareille
#  
#########################################################################
#
# $Header: /mnt/raid/services/cvs/python/packages/share1.5/Pmv/VisionInterface/APBSIsoContour_net.py,v 1.41.6.1 2016/02/11 21:29:44 annao Exp $
#
# $Id: APBSIsoContour_net.py,v 1.41.6.1 2016/02/11 21:29:44 annao Exp $
#

from traceback import print_exc
## loading libraries ##
from Pmv.VisionInterface.PmvNodes import pmvlib
masterNet.getEditor().addLibraryInstance(pmvlib,"Pmv.VisionInterface.PmvNodes", "pmvlib")

from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(stdlib,"Vision.StandardNodes", "stdlib")

from Volume.VisionInterface.VolumeNodes import vollib
masterNet.getEditor().addLibraryInstance(vollib,"Volume.VisionInterface.VolumeNodes", "vollib")

from DejaVu.VisionInterface.DejaVuNodes import vizlib
masterNet.getEditor().addLibraryInstance(vizlib,"DejaVu.VisionInterface.DejaVuNodes", "vizlib")

try:
    ## saving node VolumeStats ##
    from Volume.VisionInterface.VolumeNodes import VolumeStats
    VolumeStats_1 = VolumeStats(constrkw = {}, name='VolumeStats', library=vollib)
    masterNet.addNode(VolumeStats_1,271,173)
except:
    print "WARNING: failed to restore VolumeStats named VolumeStats in network masterNet"
    print_exc()
    VolumeStats_1=None

try:
    ## saving node GenSurf ##
    from Vision.StandardNodes import Generic
    GenSurf_2 = Generic(constrkw = {}, name='GenSurf', library=stdlib)
    masterNet.addNode(GenSurf_2,411,235)
    apply(GenSurf_2.addInputPort, (), {'name': 'value', 'cast': True, 'datatype': 'float', 'height': 12, 'width': 12, 'shape': 'circle', 'color': 'green'})
    apply(GenSurf_2.addInputPort, (), {'name': 'geom1', 'cast': True, 'datatype': 'geom', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'red'})
    apply(GenSurf_2.addOutputPort, (), {'name': 'out0', 'datatype': 'geom', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'red'})
    apply(GenSurf_2.addOutputPort, (), {'name': 'out1', 'datatype': 'geom', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'red'})
    code = """def doit(self, value, geom1):
     geom1.inheritMaterial = False
     geom1.inheritFrontPolyMode = False
#     geom1.inheritBackPolyMode = False     
     from opengltk.OpenGL import GL
     geom1.frontPolyMode = GL.GL_FILL
#     geom1.backPolyMode = GL.GL_FILL     
     R = 0.
     B = 0.
     if value < 0:
          R = 1.
     else:
          B = 1
     geom1.Set( depthMask = 1)
     geom1.SetMaterial([(0.0,0.0,0.0,0.0),],2)
     geom1.SetMaterial([(0.9,0.9,0.9,1.0),],3)
     geom1.Set(materials=[(R,0.,B,0.8),])
#     geom1.Set(culling='None')

#     if hasattr(self, 'Label') and #        hasattr(self.Label, 'viewer') and #        hasattr(self.Label.viewer, 'RemoveObject'):
#         self.Label.viewer.RemoveObject(self.Label)
     
     from DejaVu.glfSticker import Sticker
     self.Label = Sticker(name='LeftLabel', 
                          label=str(value)[0:7], 
                          position=(0, 1),
                          anchor=(0, 1),
                          frameSpace=(2.,.5),
                          frameColor=(R,0,B,.8),
                          fontColor=(1,1,1,1),
                          framePolygonMode=GL.GL_FILL,
                          immediateRendering=True, # just to make sure it's on top of other transparencies
                          transparent=True,
                          )
     
     self.outputData(out0=geom1, out1=self.Label)


## to ouput data on port out1 use
## self.outputData(out1=data)


"""
    GenSurf_2.configure(function=code)
except:
    print "WARNING: failed to restore Generic named GenSurf in network masterNet"
    print_exc()
    GenSurf_2=None

try:
    ## saving node GenSurf ##
    from Vision.StandardNodes import Generic
    GenSurf_3 = Generic(constrkw = {}, name='GenSurf', library=stdlib)
    masterNet.addNode(GenSurf_3,67,243)
    apply(GenSurf_3.addInputPort, (), {'name': 'value', 'cast': True, 'datatype': 'float', 'height': 12, 'width': 12, 'shape': 'circle', 'color': 'green'})
    apply(GenSurf_3.addInputPort, (), {'name': 'geom1', 'cast': True, 'datatype': 'geom', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'red'})
    apply(GenSurf_3.addOutputPort, (), {'name': 'out0', 'datatype': 'geom', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'red'})
    apply(GenSurf_3.addOutputPort, (), {'name': 'out1', 'datatype': 'geom', 'height': 8, 'width': 12, 'shape': 'rect', 'color': 'red'})
    code = """def doit(self, value, geom1):
     geom1.inheritMaterial = False
     geom1.inheritFrontPolyMode = False
     geom1.inheritBackPolyMode = False
     geom1.inheritCulling = False
     from opengltk.OpenGL import GL
#     geom1.frontPolyMode = GL.GL_FILL
     geom1.backPolyMode = GL.GL_FILL     
     R = 0.
     B = 0.
     if value < 0:
          R = 1.
     else:
          B = 1
     geom1.Set( depthMask = 1)
     geom1.SetMaterial([(0.0,0.0,0.0,0.0),],2)
     geom1.SetMaterial([(0.9,0.9,0.9,1.0),],3)
     geom1.Set(culling='front')
     geom1.Set(materials=[(R,0.,B,0.8),],)
                    
#     if hasattr(self,'Label') and #        hasattr(self.Label,'viewer') and #        hasattr(self.Label.viewer,'RemoveObject'):
#         self.Label.viewer.RemoveObject(self.Label)

     from DejaVu.glfSticker import Sticker
     self.Label = Sticker(  name='RightLabel', 
                            label=str(value)[0:7],
                            position=(1, 1),
                            anchor=(1, 1),
                            frameSpace=(2., .5),
                            frameColor=(R,0,B,.8),
                            fontColor=(1,1,1,1),
                            framePolygonMode=GL.GL_FILL,
                            immediateRendering=True, # just to make sure it's on top of other transparencies
                            transparent=True, 
                            )
 
     self.outputData(out0=geom1,out1 = self.Label )



## to ouput data on port out1 use
## self.outputData(out1=data)


"""
    GenSurf_3.configure(function=code)
except:
    print "WARNING: failed to restore Generic named GenSurf in network masterNet"
    print_exc()
    GenSurf_3=None

try:
    ## saving node -polygons ##
    from DejaVu.VisionInterface.GeometryNodes import IndexedPolygonsNE
    _polygons_4 = IndexedPolygonsNE(constrkw = {}, name='-polygons', library=vizlib)
    masterNet.addNode(_polygons_4,15,105)
    _polygons_4.inputPortByName['name'].widget.set("", run=False)
except:
    print "WARNING: failed to restore IndexedPolygonsNE named -polygons in network masterNet"
    print_exc()
    _polygons_4=None

try:
    ## saving node +polygons ##
    from DejaVu.VisionInterface.GeometryNodes import IndexedPolygonsNE
    _polygons_5 = IndexedPolygonsNE(constrkw = {}, name='+polygons', library=vizlib)
    masterNet.addNode(_polygons_5,403,124)
    _polygons_5.inputPortByName['name'].widget.set("", run=False)
except:
    print "WARNING: failed to restore IndexedPolygonsNE named +polygons in network masterNet"
    print_exc()
    _polygons_5=None

try:
    ## saving node Pmv Viewer ##
    from Pmv.VisionInterface.PmvNodes import PmvViewer
    Pmv_Viewer_6 = PmvViewer(viewer=masterNet.editor.vf.GUI.VIEWER, constrkw = {'viewer': 'masterNet.editor.vf.GUI.VIEWER'}, name='Pmv Viewer', library=pmvlib)
    masterNet.addNode(Pmv_Viewer_6,256,312)
    state = {'localViewer': False, 'twoSide': 0, 'ambient': (0.20000000000000001, 0.20000000000000001, 0.20000000000000001, 1.0)}
    apply(Pmv_Viewer_6.vi.lightModel.Set, (), state)

except:
    print "WARNING: failed to restore PmvViewer named Pmv Viewer in network masterNet"
    print_exc()
    Pmv_Viewer_6=None

try:
    ## saving node Left_Isocontour ##
    from Volume.VisionInterface.VolumeNodes import Isocontour
    Left_Isocontour_7 = Isocontour(constrkw = {}, name='Left_Isocontour', library=vollib)
    masterNet.addNode(Left_Isocontour_7,35,38)
    apply(Left_Isocontour_7.addOutputPort, (), {'name': 'isovalue', 'datatype': 'float', 'height': 12, 'width': 12, 'shape': 'circle', 'color': 'green'})
    apply(Left_Isocontour_7.inputPortByName['isovalue'].widget.configure, (), {'max': 401.27560424804688, 'min': -556.299072265625})
    Left_Isocontour_7.inputPortByName['isovalue'].widget.set(-1.0, run=False)
    Left_Isocontour_7.inputPortByName['calculatesignatures'].widget.set(1, run=False)
    code = """def doit(self, grid3D, isovalue, calculatesignatures, verbosity):
    from UTpackages.UTisocontour import isocontour
    if verbosity is not None and verbosity!=self.verbosity:
        isocontour.setVerboseLevel(verbosity)
        self.verbosity = verbosity
        #return

    data = grid3D.data
    import numpy
    if self.inputPortByName['grid3D'].hasNewValidData():
        origin = numpy.array(grid3D.origin).astype('f')
        stepsize = numpy.array(grid3D.stepSize).astype('f')
        # add 1 dimension for time steps amd 1 for multiple variables
        if data.dtype.char!=numpy.float32:
            print 'converting from ', data.dtype.char
            data = data.astype('f')#numpy.float32)

        self.newgrid3D = numpy.ascontiguousarray(numpy.reshape( numpy.transpose(data),
                                          (1, 1)+tuple(data.shape) ), data.dtype.char)
        # destroy the ConDataset structure
        if self.data:
            isocontour.delDatasetReg(self.data)
            
        self.data = isocontour.newDatasetRegFloat3D(            self.newgrid3D, origin, stepsize)

        w = self.inputPortByName['isovalue'].widget
        if w and grid3D is not None:
            mymin, mymax, mymean, mystdev =  grid3D.stats()
            if (isinstance(mymin, numpy.ndarray)) and (mymin.shape == () ):
                mymin = mymin[0]
            if (isinstance(mymax, numpy.ndarray)) and (mymax.shape == () ):
                mymax = mymax[0]
            w.widget.setMin(mymin)
            w.widget.setMax(mymax)
            #print 'isovalue in doit():', isovalue
            if (isovalue < mymin) or (isovalue > mymax):
                isovalue = mymean
                w.widget.set( isovalue )                    
                warnings.warn('%s: isovalue was outside data range, isovalue is now set to the mean'%self.name)

    if self.data:
        isoc = isocontour.getContour3d(self.data, 0, 0, isovalue,
                                       isocontour.NO_COLOR_VARIABLE)

        vert = numpy.zeros((isoc.nvert,3)).astype('f')
        norm = numpy.zeros((isoc.nvert,3)).astype('f')
        col = numpy.zeros((isoc.nvert)).astype('f')
        tri = numpy.zeros((isoc.ntri,3)).astype('i')
        isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)

        if grid3D.crystal:
            vert = grid3D.crystal.toCartesian(vert) 
        self.outputData(coords=vert, indices=tri, normals=-norm, isovalue=isovalue)
"""
    Left_Isocontour_7.configure(function=code)
except:
    print "WARNING: failed to restore Isocontour named Left_Isocontour in network masterNet"
    print_exc()
    Left_Isocontour_7=None

try:
    ## saving node Right_Isocontour ##
    from Volume.VisionInterface.VolumeNodes import Isocontour
    Right_Isocontour_8 = Isocontour(constrkw = {}, name='Right_Isocontour', library=vollib)
    masterNet.addNode(Right_Isocontour_8,517,34)
    apply(Right_Isocontour_8.addOutputPort, (), {'name': 'isovalue', 'datatype': 'float', 'height': 12, 'width': 12, 'shape': 'circle', 'color': 'green'})
    apply(Right_Isocontour_8.inputPortByName['isovalue'].widget.configure, (), {'max': 401.27560424804688, 'min': -556.299072265625})
    Right_Isocontour_8.inputPortByName['isovalue'].widget.set(1.0, run=False)
    Right_Isocontour_8.inputPortByName['calculatesignatures'].widget.set(1, run=False)
    code = """def doit(self, grid3D, isovalue, 
calculatesignatures=None, verbosity=None):
    from UTpackages.UTisocontour import isocontour
    if verbosity is not None and verbosity!=self.verbosity:
        isocontour.setVerboseLevel(verbosity)
        self.verbosity = verbosity
        #return

    data = grid3D.data
    import numpy
    if self.inputPortByName['grid3D'].hasNewValidData():
        origin = numpy.array(grid3D.origin).astype('f')
        stepsize = numpy.array(grid3D.stepSize).astype('f')
        # add 1 dimension for time steps amd 1 for multiple variables
        if data.dtype.char!=numpy.float32:
            print 'converting from ', data.dtype.char
            data = data.astype('f')#numpy.float32)

        self.newgrid3D = numpy.ascontiguousarray(numpy.reshape( numpy.transpose(data),
                                          (1, 1)+tuple(data.shape) ), data.dtype.char)
        # destroy the ConDataset structure
        if self.data:
            isocontour.delDatasetReg(self.data)
            
        self.data = isocontour.newDatasetRegFloat3D(            self.newgrid3D, origin, stepsize)

        w = self.inputPortByName['isovalue'].widget
        if w and grid3D is not None:
            mymin, mymax, mymean, mystdev = grid3D.stats()
            if (isinstance(mymin, numpy.ndarray)) and (mymin.shape == () ):
                mymin = mymin[0]
            if (isinstance(mymax, numpy.ndarray)) and (mymax.shape == () ):
                mymax = mymax[0]
            w.widget.setMin(mymin)
            w.widget.setMax(mymax)
            #print 'isovalue in doit():', isovalue
            if (isovalue < mymin) or (isovalue > mymax):
                isovalue = mymean
                w.widget.set( isovalue )                    
                warnings.warn('%s: isovalue was outside data range, isovalue is now set to the mean'%self.name)

    if self.data:
        isoc = isocontour.getContour3d(self.data, 0, 0, isovalue,
                                       isocontour.NO_COLOR_VARIABLE)

        vert = numpy.zeros((isoc.nvert,3)).astype('f')
        norm = numpy.zeros((isoc.nvert,3)).astype('f')
        col = numpy.zeros((isoc.nvert)).astype('f')
        tri = numpy.zeros((isoc.ntri,3)).astype('i')
        isocontour.getContour3dData(isoc, vert, norm, col, tri, 0)

        if grid3D.crystal:
            vert = grid3D.crystal.toCartesian(vert) 
        self.outputData(coords=vert, indices=tri, normals=norm, isovalue=isovalue)





"""
    Right_Isocontour_8.configure(function=code)
except:
    print "WARNING: failed to restore Isocontour named Right_Isocontour in network masterNet"
    print_exc()
    Right_Isocontour_8=None

try:
    ## saving node Pmv Grids ##
    from Volume.VisionInterface.VolumeNodes import PmvGridChooser
    Pmv_Grids_9 = PmvGridChooser(constrkw = {}, name='Pmv Grids', library=vollib)
    masterNet.addNode(Pmv_Grids_9,200,9)
    apply(Pmv_Grids_9.configure, (), {'expanded': True})
except:
    print "WARNING: failed to restore PmvGridChooser named Pmv Grids in network masterNet"
    print_exc()
    Pmv_Grids_9=None

masterNet.freeze()

## saving connections for network APBSIsoContour ##
if GenSurf_2 is not None and Pmv_Viewer_6 is not None:
    try:
        masterNet.connectNodes(
            GenSurf_2, Pmv_Viewer_6, "out0", "geometries", blocking=True)
    except:
        print "WARNING: failed to restore connection between GenSurf_2 and Pmv_Viewer_6 in network masterNet"
if GenSurf_2 is not None and Pmv_Viewer_6 is not None:
    try:
        masterNet.connectNodes(
            GenSurf_2, Pmv_Viewer_6, "out1", "geometries", blocking=True)
    except:
        print "WARNING: failed to restore connection between GenSurf_2 and Pmv_Viewer_6 in network masterNet"
if Left_Isocontour_7 is not None and _polygons_4 is not None:
    try:
        masterNet.connectNodes(
            Left_Isocontour_7, _polygons_4, "coords", "coords", blocking=True)
    except:
        print "WARNING: failed to restore connection between Left_Isocontour_7 and _polygons_4 in network masterNet"
if Left_Isocontour_7 is not None and _polygons_4 is not None:
    try:
        masterNet.connectNodes(
            Left_Isocontour_7, _polygons_4, "indices", "indices", blocking=True)
    except:
        print "WARNING: failed to restore connection between Left_Isocontour_7 and _polygons_4 in network masterNet"
if Left_Isocontour_7 is not None and _polygons_4 is not None:
    try:
        masterNet.connectNodes(
            Left_Isocontour_7, _polygons_4, "normals", "vnormals", blocking=True)
    except:
        print "WARNING: failed to restore connection between Left_Isocontour_7 and _polygons_4 in network masterNet"
if GenSurf_3 is not None and Pmv_Viewer_6 is not None:
    try:
        masterNet.connectNodes(
            GenSurf_3, Pmv_Viewer_6, "out0", "geometries", blocking=True)
    except:
        print "WARNING: failed to restore connection between GenSurf_3 and Pmv_Viewer_6 in network masterNet"
if GenSurf_3 is not None and Pmv_Viewer_6 is not None:
    try:
        masterNet.connectNodes(
            GenSurf_3, Pmv_Viewer_6, "out1", "geometries", blocking=True)
    except:
        print "WARNING: failed to restore connection between GenSurf_3 and Pmv_Viewer_6 in network masterNet"
if Right_Isocontour_8 is not None and _polygons_5 is not None:
    try:
        masterNet.connectNodes(
            Right_Isocontour_8, _polygons_5, "coords", "coords", blocking=True)
    except:
        print "WARNING: failed to restore connection between Right_Isocontour_8 and _polygons_5 in network masterNet"
if Right_Isocontour_8 is not None and _polygons_5 is not None:
    try:
        masterNet.connectNodes(
            Right_Isocontour_8, _polygons_5, "indices", "indices", blocking=True)
    except:
        print "WARNING: failed to restore connection between Right_Isocontour_8 and _polygons_5 in network masterNet"
if Right_Isocontour_8 is not None and _polygons_5 is not None:
    try:
        masterNet.connectNodes(
            Right_Isocontour_8, _polygons_5, "normals", "vnormals", blocking=True)
    except:
        print "WARNING: failed to restore connection between Right_Isocontour_8 and _polygons_5 in network masterNet"
if _polygons_4 is not None and GenSurf_3 is not None:
    try:
        masterNet.connectNodes(
            _polygons_4, GenSurf_3, "indexedPolygons", "geom1", blocking=True)
    except:
        print "WARNING: failed to restore connection between _polygons_4 and GenSurf_3 in network masterNet"
if Left_Isocontour_7 is not None and GenSurf_3 is not None:
    try:
        masterNet.connectNodes(
            Left_Isocontour_7, GenSurf_3, "isovalue", "value", blocking=True)
    except:
        print "WARNING: failed to restore connection between Left_Isocontour_7 and GenSurf_3 in network masterNet"
if _polygons_5 is not None and GenSurf_2 is not None:
    try:
        masterNet.connectNodes(
            _polygons_5, GenSurf_2, "indexedPolygons", "geom1", blocking=True)
    except:
        print "WARNING: failed to restore connection between _polygons_5 and GenSurf_2 in network masterNet"
if Right_Isocontour_8 is not None and GenSurf_2 is not None:
    try:
        masterNet.connectNodes(
            Right_Isocontour_8, GenSurf_2, "isovalue", "value", blocking=True)
    except:
        print "WARNING: failed to restore connection between Right_Isocontour_8 and GenSurf_2 in network masterNet"
if Pmv_Grids_9 is not None and Left_Isocontour_7 is not None:
    try:
        masterNet.connectNodes(
            Pmv_Grids_9, Left_Isocontour_7, "grid", "grid3D", blocking=True)
    except:
        print "WARNING: failed to restore connection between Pmv_Grids_9 and Left_Isocontour_7 in network masterNet"
if Pmv_Grids_9 is not None and Right_Isocontour_8 is not None:
    try:
        masterNet.connectNodes(
            Pmv_Grids_9, Right_Isocontour_8, "grid", "grid3D", blocking=True)
    except:
        print "WARNING: failed to restore connection between Pmv_Grids_9 and Right_Isocontour_8 in network masterNet"
if Pmv_Grids_9 is not None and VolumeStats_1 is not None:
    try:
        masterNet.connectNodes(
            Pmv_Grids_9, VolumeStats_1, "grid", "grid", blocking=True)
    except:
        print "WARNING: failed to restore connection between Pmv_Grids_9 and VolumeStats_1 in network masterNet"
masterNet.unfreeze()
#masterNet.run()

