Example #1
0
def test_get_isovol():
    """test get_isovol"""
    r = np.full(3, False)
    db = test_dir + "/test-isovol/"
    iv = ivdb.IvDb(levels=levels, data=data, db=db)
    if isdir(db):
        shutil.rmtree(db)
    mkdir(db)
    mkdir(db + '/vols/')
    # launch VisIt
    import visit
    try:
        visit.LaunchNowin()
    except:
        pass
    visit.OpenDatabase(test_mesh)
    visit.AddPlot('Pseudocolor', data)
    # run __get_isovol
    lbound = 5
    ubound = 15
    i = 1
    export_res, ubound_out = iv._IvDb__get_isovol(lbound, ubound, i)
    # close VisIt
    visit.CloseComputeEngine()
    # check returned values
    if export_res == 1:
        r[0] = True
    if ubound_out == ubound:
        r[1] = True
    # check that vol file produced are the same
    gen_vol = db + "/vols/1.stl"
    exp_vol = exp_vols_dir + "/1.stl"
    r[2] = filecmp.cmp(gen_vol, exp_vol)
    shutil.rmtree(db)
    assert (all(r))
Example #2
0
    def generate_vols(self, filename):
        """Generates the isosurface volumes between the level values.
        Data files are exported as STLs and saved in the folder db.
        Files will be named based on their index corresponding to their
        level values (0.stl is lowest values).

        Input:
        ------
            filename: string, path to vtk file with the mesh
        """
        # create folder for database
        self.__make_db_dir()

        # launch VisIt
        try:
            v.LaunchNowin()
        except:
            pass

        # open file
        v.OpenDatabase(filename)

        # read data using meshio to get min and max and make sure levels are
        # within data bounds:
        arbmin, arbmax, mins, maxs = self.__check_data(filename)
        self.xmin = mins[0]
        self.ymin = mins[1]
        self.zmin = mins[2]
        self.xmax = maxs[0]
        self.ymax = maxs[1]
        self.zmax = maxs[2]
        self.levels.append(arbmax)

        # plot the pseudocolor data in order to get volumes
        v.AddPlot("Pseudocolor", self.data)
        v.DrawPlots()

        # iterate over all isovolume levels
        for i, l in enumerate(self.levels):
            res = 0
            while res == 0:

                # lower bound
                if i == 0:
                    lbound = arbmin
                else:
                    lbound = self.levels[i - 1]

                # upper bound
                ubound = self.levels[i]

                # get volume
                # res = 0 if no level found (should update to next level)
                res, ubound = self.__get_isovol(lbound, ubound, i)

        # delete plots
        v.DeleteAllPlots()

        # close visit
        v.CloseComputeEngine()
Example #3
0
def test_plane_slice_plotting():
    """
    Ensure this function correctly generates a plane slice plot.
    """
    visit.LaunchNowin()
    visit.RestoreSession(plane_slice_session_file, 0)
    plane_slice_plotting(2, 2, "XY Plane", True, True)
    diff = filecmp.cmp("visit0000.png", plane_slice_image)
    assert diff == True
    visit.Close()
Example #4
0
def test_get_isovol_nodata():
    """test get_isovol no data present"""
    r = np.full(6, False)
    db = test_dir + "/test-isovol-nodata/"
    iv = ivdb.IvDb(levels=[5, 15, 25, 28, 35], data=data, db=db)
    if isdir(db):
        shutil.rmtree(db)
    mkdir(db)
    mkdir(db + '/vols/')
    # launch VisIt
    import visit
    try:
        visit.LaunchNowin()
    except:
        pass
    visit.OpenDatabase(test_mesh)
    visit.AddPlot('Pseudocolor', data)
    # run __get_isovol
    lbound = 25
    ubound = 28
    i = 3
    with warnings.catch_warnings(record=True) as w:
        export_res, ubound_out = iv._IvDb__get_isovol(lbound, ubound, i)
    # close VisIt
    visit.CloseComputeEngine()
    # check returned/changed values
    if export_res == 0:
        r[0] = True
    if ubound_out == 35:
        r[1] = True
    if iv.levels == [5, 15, 25, 35]:
        r[2] = True
    gen_vol = db + "/vols/3.stl"
    if not isfile(gen_vol):
        # no file should be generated
        r[3] = True
    r[4:6] = __check_warning(w, ["no data to export between"], 1)
    shutil.rmtree(db)
    assert (all(r))
Example #5
0
    def generate_volumes(self, filename, data, dbname=os.getcwd() + "/tmp"):
        """Creates an STL file for each isovolume. N+1 files are
        generated and stored in the dbname folder.

        Input:
        ------
            filename: string, path to vtk file with the mesh
            data: string, name of the data whose values exist on the
                mesh (will be used to generate isocontours and
                isovolumes)
            dbname: (optional), string, name of folder to store created
                surface files. Must be absolute path!
                default: a folder called 'tmp' in the current directory
        """

        self.data = data
        self.db = dbname

        # make sure levels have been set before proceding
        try:
            self.levels
        except:
            print("ERROR: No contour levels have been set. " +\
                "Please use assign_levels or generate_levels to set.")
            sys.exit()

        # Generate isovolumes using VisIT
        try:
            v.LaunchNowin()
        except:
            print("VisIt already launched.")
        v.OpenDatabase(filename)
        print("Generating isovolumes...")
        self._generate_vols()
        print("...Isovolumes files generated!")
        v.CloseComputeEngine()
Example #6
0
# Visualise result.silo using VisIt
import visit

print("Successfully imported visit")

import urllib2
response = urllib2.urlopen(
    "https://wci.llnl.gov/content/assets/docs/simulation/computer-codes/silo/datafiles/csg.silo"
)
with open('example.silo', 'wb') as f:
    f.write(response.read())

print("Successfully downloaded example silo")

visit.LaunchNowin()
saveatts = visit.SaveWindowAttributes()
saveatts.fileName = 'result-visit.png'
saveatts.family = 0
saveatts.width = 1024
saveatts.height = 768
saveatts.resConstraint = saveatts.NoConstraint
saveatts.outputToCurrentDirectory = 1
visit.SetSaveWindowAttributes(saveatts)
visit.OpenDatabase('example.silo')
visit.AddPlot('Contour', 'density')
c = visit.ContourAttributes()
c.colorType = c.ColorByColorTable
c.colorTableName = "hot"
visit.SetPlotOptions(c)
visit.DrawPlots()
Example #7
0
def visit_plot_qcrit_wx_3d(xdmf_dir,
                           wx_range=(-5.0, 5.0),
                           q_value=0.1,
                           config_view=None,
                           out_dir=os.getcwd(),
                           out_prefix='wake3d_',
                           figsize=(1024, 1024),
                           visit_dir=None,
                           visit_arch='linux-x86_64',
                           state=None,
                           states=None,
                           states_range=[0, None, 1]):
    # Import VisIt package.
    if visit_dir is None:
        visit_dir = os.environ.get('VISIT_DIR')
        if visit_dir is None:
            raise ValueError('Provide VisIt installation path or '
                             'set env variable VISIT_DIR')
    sys.path.append(os.path.join(visit_dir, visit_arch, 'lib',
                                 'site-packages'))
    import visit

    visit.LaunchNowin()

    # Check version of VisIt.
    visit_check_version(visit.Version())

    # Define some variables to get the q_crit and wx_cc.
    p_xdmf_path = os.path.join(str(xdmf_dir), 'p.xmf')
    visit.OpenDatabase(p_xdmf_path, 0)
    visit.DefineScalarExpression("operators/ConnectedComponents/p Grid",
                                 "cell_constant(<p Grid>, 0.)")
    visit.DefineCurveExpression("operators/DataBinning/1D/p Grid",
                                "cell_constant(<p Grid>, 0)")
    visit.DefineScalarExpression("operators/DataBinning/2D/p Grid",
                                 "cell_constant(<p Grid>, 0)")
    visit.DefineScalarExpression("operators/DataBinning/3D/p Grid",
                                 "cell_constant(<p Grid>, 0)")
    visit.DefineScalarExpression("operators/Flux/p Grid",
                                 "cell_constant(<p Grid>, 0.)")
    visit.DefineCurveExpression("operators/Lineout/p",
                                "cell_constant(<p>, 0.)")
    visit.DefineCurveExpression(
        "operators/Lineout/time_derivative/p Grid_time",
        "cell_constant(time_derivative/p Grid_time, 0.)")
    visit.DefineCurveExpression(
        "operators/Lineout/time_derivative/p Grid_lasttime",
        "cell_constant(time_derivative/p Grid_lasttime, 0.)")
    visit.DefineCurveExpression("operators/Lineout/time_derivative/p",
                                "cell_constant(time_derivative/p, 0.)")
    visit.DefineScalarExpression("operators/ModelFit/model",
                                 "point_constant(<p Grid>, 0)")
    visit.DefineScalarExpression("operators/ModelFit/distance",
                                 "point_constant(<p Grid>, 0)")
    visit.DefineScalarExpression("operators/StatisticalTrends/Sum/p",
                                 "cell_constant(<p>, 0.)")
    visit.DefineScalarExpression("operators/StatisticalTrends/Mean/p",
                                 "cell_constant(<p>, 0.)")
    visit.DefineScalarExpression("operators/StatisticalTrends/Variance/p",
                                 "cell_constant(<p>, 0.)")
    visit.DefineScalarExpression("operators/StatisticalTrends/Std. Dev./p",
                                 "cell_constant(<p>, 0.)")
    visit.DefineScalarExpression("operators/StatisticalTrends/Slope/p",
                                 "cell_constant(<p>, 0.)")
    visit.DefineScalarExpression("operators/StatisticalTrends/Residuals/p",
                                 "cell_constant(<p>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Sum/time_derivative/p Grid_time",
        "cell_constant(<time_derivative/p Grid_time>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Sum/time_derivative/p Grid_lasttime",
        "cell_constant(<time_derivative/p Grid_lasttime>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Sum/time_derivative/p",
        "cell_constant(<time_derivative/p>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Mean/time_derivative/p Grid_time",
        "cell_constant(<time_derivative/p Grid_time>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Mean/time_derivative/p Grid_lasttime",
        "cell_constant(<time_derivative/p Grid_lasttime>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Mean/time_derivative/p",
        "cell_constant(<time_derivative/p>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Variance/time_derivative/p Grid_time",
        "cell_constant(<time_derivative/p Grid_time>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Variance/time_derivative/p Grid_lasttime",
        "cell_constant(<time_derivative/p Grid_lasttime>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Variance/time_derivative/p",
        "cell_constant(<time_derivative/p>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Std. Dev./time_derivative/p Grid_time",
        "cell_constant(<time_derivative/p Grid_time>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Std. Dev./time_derivative/p Grid_lasttime",
        "cell_constant(<time_derivative/p Grid_lasttime>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Std. Dev./time_derivative/p",
        "cell_constant(<time_derivative/p>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Slope/time_derivative/p Grid_time",
        "cell_constant(<time_derivative/p Grid_time>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Slope/time_derivative/p Grid_lasttime",
        "cell_constant(<time_derivative/p Grid_lasttime>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Slope/time_derivative/p",
        "cell_constant(<time_derivative/p>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Residuals/time_derivative/p Grid_time",
        "cell_constant(<time_derivative/p Grid_time>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Residuals/time_derivative/p Grid_lasttime",
        "cell_constant(<time_derivative/p Grid_lasttime>, 0.)")
    visit.DefineScalarExpression(
        "operators/StatisticalTrends/Residuals/time_derivative/p",
        "cell_constant(<time_derivative/p>, 0.)")
    visit.DefineVectorExpression("operators/SurfaceNormal/p Grid",
                                 "cell_constant(<p Grid>, 0.)")
    # Define cell-centered velocity vector field.
    ux_xdmf_path = os.path.join(str(xdmf_dir), 'u.xmf')
    uy_xdmf_path = os.path.join(str(xdmf_dir), 'v.xmf')
    uz_xdmf_path = os.path.join(str(xdmf_dir), 'w.xmf')
    vel_exp = ('{' +
               'pos_cmfe(<{}[0]id:u>, <p Grid>, 1.0),'.format(ux_xdmf_path) +
               'pos_cmfe(<{}[0]id:v>, <p Grid>, 0.0),'.format(uy_xdmf_path) +
               'pos_cmfe(<{}[0]id:w>, <p Grid>, 0.0)'.format(uz_xdmf_path) +
               '}')
    visit.DefineVectorExpression('velocity', vel_exp)
    # Define Q-criterion.
    qcrit_exp = ('q_criterion(' + 'gradient(velocity[0]),' +
                 'gradient(velocity[1]),' + 'gradient(velocity[2])' + ')')
    visit.DefineScalarExpression('q_crit', qcrit_exp)
    # Define cell-centered streamwise vorticity.
    wx_xdmf_path = os.path.join(str(xdmf_dir), 'wx.xmf')
    wx_exp = 'pos_cmfe(<{}[0]id:wx>, <p Grid>, 0.0)'.format(wx_xdmf_path)
    visit.DefineScalarExpression('wx_cc', wx_exp)

    # Add a pseudocolor of the cell-centered streamwise vorticity.
    visit.AddPlot('Pseudocolor', 'wx_cc', 1, 1)
    PseudocolorAtts = visit.PseudocolorAttributes()
    PseudocolorAtts.minFlag = 1
    PseudocolorAtts.min = wx_range[0]
    PseudocolorAtts.maxFlag = 1
    PseudocolorAtts.max = wx_range[1]
    PseudocolorAtts.colorTableName = 'viridis'
    PseudocolorAtts.invertColorTable = 1
    PseudocolorAtts.opacityType = PseudocolorAtts.Constant
    PseudocolorAtts.opacity = 0.8
    PseudocolorAtts.legendFlag = 0
    visit.SetPlotOptions(PseudocolorAtts)

    # Add an isosurface of the Q-criterion.
    visit.AddOperator('Isosurface', 1)
    IsosurfaceAtts = visit.IsosurfaceAttributes()
    IsosurfaceAtts.variable = 'q_crit'
    IsosurfaceAtts.contourMethod = IsosurfaceAtts.Value
    IsosurfaceAtts.contourValue = (q_value)
    IsosurfaceAtts.scaling = IsosurfaceAtts.Linear
    visit.SetOperatorOptions(IsosurfaceAtts, 1)

    # Remove info about user, time, database, and legend.
    AnnotationAtts = visit.AnnotationAttributes()
    AnnotationAtts.userInfoFlag = 0
    AnnotationAtts.databaseInfoFlag = 0
    AnnotationAtts.timeInfoFlag = 0
    AnnotationAtts.legendInfoFlag = 0
    AnnotationAtts.axes3D.visible = 0
    AnnotationAtts.axes3D.triadFlag = 1
    AnnotationAtts.axes3D.bboxFlag = 0
    visit.SetAnnotationAttributes(AnnotationAtts)

    # Parse the 3D view configuration file.
    if config_view is not None:
        with open(str(config_view), 'r') as infile:
            config_view = yaml.load(infile, Loader=yaml.FullLoader)
            config_view = config_view['View3DAtts']
    # Set attributes of the view.
    View3DAtts = visit.View3DAttributes()
    for key, value in config_view.items():
        if type(value) is list:
            value = tuple(value)
        setattr(View3DAtts, key, value)
    visit.SetView3D(View3DAtts)

    visit.SetActiveWindow(1)

    visit.Source(os.path.join(visit_dir, visit_arch, 'bin', 'makemovie.py'))
    visit.ToggleCameraViewMode()

    # Create output directory if necessary.
    if not os.path.isdir(str(out_dir)):
        os.makedirs(str(out_dir))

    # Loop over the states to render and save the plots.
    if state is not None:
        states = [state]
    elif states is None:
        if states_range[1] is None:
            states_range[1] = visit.TimeSliderGetNStates()
        else:
            states_range[1] += 1
        states = range(*states_range)

    for i, state in enumerate(states):
        print('[state {}] Rendering and saving figure ...'.format(state))
        visit.SetTimeSliderState(state)

        if i == 0:
            visit.DrawPlots()

        RenderingAtts = visit.RenderingAttributes()
        visit.SetRenderingAttributes(RenderingAtts)

        SaveWindowAtts = visit.SaveWindowAttributes()
        SaveWindowAtts.outputToCurrentDirectory = 0
        SaveWindowAtts.outputDirectory = str(out_dir)
        SaveWindowAtts.fileName = '{}{:0>4}'.format(out_prefix, state)
        SaveWindowAtts.family = 0
        SaveWindowAtts.format = SaveWindowAtts.PNG
        SaveWindowAtts.width = figsize[0]
        SaveWindowAtts.height = figsize[1]
        SaveWindowAtts.quality = 100
        SaveWindowAtts.resConstraint = SaveWindowAtts.NoConstraint
        visit.SetSaveWindowAttributes(SaveWindowAtts)

        visit.SaveWindow()

    os.remove('visitlog.py')
    visit.CloseComputeEngine()
    visit.Close()
    return
Example #8
0
def visit_plot_pseudocolor_2d(xdmf_path,
                              name,
                              value_range=(-5.0, 5.0),
                              curve2d_paths=None,
                              config_view=None,
                              out_dir=os.getcwd(),
                              out_prefix='wake2d_',
                              figsize=(1024, 1024),
                              visit_dir=None,
                              visit_arch='linux-x86_64',
                              state=None,
                              states=None,
                              states_range=[0, None, 1]):
    # Import VisIt package.
    if visit_dir is None:
        visit_dir = os.environ.get('VISIT_DIR')
        if visit_dir is None:
            raise ValueError('Provide VisIt installation path or '
                             'set env variable VISIT_DIR')
    sys.path.append(os.path.join(visit_dir, visit_arch, 'lib',
                                 'site-packages'))
    import visit

    visit.LaunchNowin()

    # Check version of VisIt.
    visit_check_version(visit.Version())

    # Create database correlation with optional Curve2D files.
    num_bodies = 0
    databases = [str(xdmf_path)]
    if curve2d_paths is not None:
        num_bodies = len(curve2d_paths)
        databases = [str(path) for path in curve2d_paths]
        databases.append(str(xdmf_path))
    visit.CreateDatabaseCorrelation('common', databases[num_bodies:], 0)

    # Open the file with the coordinates of the immersed boundary.
    if num_bodies > 0:
        for i in range(num_bodies):
            visit.OpenDatabase(databases[i], 0)
            # Add plot the mesh points.
            visit.AddPlot('Curve', 'curve', 1, 1)
            # Set attributes of the curve.
            CurveAtts = visit.CurveAttributes()
            CurveAtts.lineWidth = 1
            CurveAtts.curveColorSource = CurveAtts.Custom
            CurveAtts.curveColor = (0, 0, 0, 255)
            CurveAtts.showLegend = 0
            CurveAtts.showLabels = 0
            visit.SetPlotOptions(CurveAtts)

    # Open the XMF file for the spanwise-averaged z-component of the vorticity.
    visit.OpenDatabase(databases[-1], 0)
    # Add a pseudocolor plot of the scalar field.
    visit.AddPlot('Pseudocolor', name, 1, 1)
    # Set attributes of the pseudocolor.
    PseudocolorAtts = visit.PseudocolorAttributes()
    PseudocolorAtts.minFlag = 1
    PseudocolorAtts.min = value_range[0]
    PseudocolorAtts.maxFlag = 1
    PseudocolorAtts.max = value_range[1]
    PseudocolorAtts.colorTableName = 'viridis'
    visit.SetPlotOptions(PseudocolorAtts)

    # Parse the 2D view configuration file.
    if config_view is not None:
        with open(str(config_view), 'r') as infile:
            config_view = yaml.load(infile, Loader=yaml.FullLoader)
            config_view = config_view['View2DAtts']
    # Set attributes of the view.
    View2DAtts = visit.View2DAttributes()
    for key, value in config_view.items():
        if type(value) is list:
            value = tuple(value)
        setattr(View2DAtts, key, value)
    visit.SetView2D(View2DAtts)

    # Remove time and user info.
    AnnotationAtts = visit.AnnotationAttributes()
    AnnotationAtts.userInfoFlag = 0
    AnnotationAtts.timeInfoFlag = 1
    visit.SetAnnotationAttributes(AnnotationAtts)

    visit.SetActiveWindow(1)

    visit.Source(os.path.join(visit_dir, visit_arch, 'bin', 'makemovie.py'))
    visit.ToggleCameraViewMode()

    # Create output directory if necessary.
    if not os.path.isdir(str(out_dir)):
        os.makedirs(str(out_dir))

    # Loop over the states to render and save the plots.
    if state is not None:
        states = [state]
    elif states is None:
        if states_range[1] is None:
            states_range[1] = visit.TimeSliderGetNStates()
        else:
            states_range[1] += 1
        states = range(*states_range)

    for i, state in enumerate(states):
        print('[state {}] Rendering and saving figure ...'.format(state))
        visit.SetTimeSliderState(state)

        if i == 0:
            visit.DrawPlots()

        RenderingAtts = visit.RenderingAttributes()
        visit.SetRenderingAttributes(RenderingAtts)

        SaveWindowAtts = visit.SaveWindowAttributes()
        SaveWindowAtts.outputToCurrentDirectory = 0
        SaveWindowAtts.outputDirectory = str(out_dir)
        SaveWindowAtts.fileName = '{}{:0>4}'.format(out_prefix, state)
        SaveWindowAtts.family = 0
        SaveWindowAtts.format = SaveWindowAtts.PNG
        SaveWindowAtts.width = figsize[0]
        SaveWindowAtts.height = figsize[1]
        SaveWindowAtts.quality = 100
        SaveWindowAtts.resConstraint = SaveWindowAtts.NoConstraint
        visit.SetSaveWindowAttributes(SaveWindowAtts)

        visit.SaveWindow()

    os.remove('visitlog.py')
    visit.Close()
    return
Example #9
0
def visit_plot_contour_3d(xdmf_path,
                          name,
                          value_range=(-5.0, 5.0),
                          p3d_paths=None,
                          config_view=None,
                          out_dir=os.getcwd(),
                          out_prefix='wake3d_',
                          figsize=(1024, 1024),
                          visit_dir=None,
                          visit_arch='linux-x86_64',
                          state=None,
                          states=None,
                          states_range=[0, None, 1]):
    # Import VisIt package.
    if visit_dir is None:
        visit_dir = os.environ.get('VISIT_DIR')
        if visit_dir is None:
            raise ValueError('Provide VisIt installation path or '
                             'set env variable VISIT_DIR')
    sys.path.append(os.path.join(visit_dir, visit_arch, 'lib',
                                 'site-packages'))
    import visit

    visit.LaunchNowin()

    # Check version of VisIt.
    visit_check_version(visit.Version())

    # Create database correlation with optional Point3D files.
    num_bodies = 0
    databases = [str(xdmf_path)]
    if p3d_paths is not None:
        num_bodies = len(p3d_paths)
        databases = [str(path) for path in p3d_paths]
        databases.append(str(xdmf_path))
    visit.CreateDatabaseCorrelation('common', databases[num_bodies:], 0)

    # Open the file with the coordinates of the immersed boundary.
    if num_bodies > 0:
        for i in range(num_bodies):
            visit.OpenDatabase(databases[i], 0, 'Point3D_1.0')
            # Add plot the mesh points.
            visit.AddPlot('Mesh', 'points', 1, 1)
            # Set attributes of the mesh plot.
            MeshAtts = visit.MeshAttributes()
            MeshAtts.legendFlag = 0
            MeshAtts.meshColor = (255, 204, 0, 1.0 * 255)
            MeshAtts.meshColorSource = MeshAtts.MeshCustom
            MeshAtts.pointSize = 0.05
            MeshAtts.pointType = MeshAtts.Point
            MeshAtts.pointSizePixels = 2
            MeshAtts.opacity = 1
            visit.SetPlotOptions(MeshAtts)

    # Open the XMF file for the z-component of the vorticity.
    visit.OpenDatabase(databases[-1], 0)
    # Add the plot of the contour of the z-component of the vorticity.
    visit.AddPlot('Contour', name, 1, 1)
    # Set attributes of the contour.
    ContourAtts = visit.ContourAttributes()
    ContourAtts.contourNLevels = 2
    ContourAtts.SetMultiColor(0, (0, 51, 102, 0.6 * 255))
    ContourAtts.SetMultiColor(1, (255, 0, 0, 0.6 * 255))
    ContourAtts.legendFlag = 1
    ContourAtts.minFlag = 1
    ContourAtts.maxFlag = 1
    ContourAtts.min = value_range[0]
    ContourAtts.max = value_range[1]
    visit.SetPlotOptions(ContourAtts)

    # Parse the 3D view configuration file.
    if config_view is not None:
        with open(str(config_view), 'r') as infile:
            config_view = yaml.load(infile, Loader=yaml.FullLoader)
            config_view = config_view['View3DAtts']
    # Set attributes of the view.
    View3DAtts = visit.View3DAttributes()
    for key, value in config_view.items():
        if type(value) is list:
            value = tuple(value)
        setattr(View3DAtts, key, value)
    visit.SetView3D(View3DAtts)

    # Remove time and user info.
    AnnotationAtts = visit.AnnotationAttributes()
    AnnotationAtts.userInfoFlag = 0
    AnnotationAtts.timeInfoFlag = 0
    AnnotationAtts.axes3D.visible = 0
    AnnotationAtts.axes3D.triadFlag = 1
    AnnotationAtts.axes3D.bboxFlag = 0
    visit.SetAnnotationAttributes(AnnotationAtts)

    visit.SetActiveWindow(1)

    visit.Source(os.path.join(visit_dir, visit_arch, 'bin', 'makemovie.py'))
    visit.ToggleCameraViewMode()

    # Create output directory if necessary.
    if not os.path.isdir(str(out_dir)):
        os.makedirs(str(out_dir))

    # Loop over the states to render and save the plots.
    if state is not None:
        states = [state]
    elif states is None:
        if states_range[1] is None:
            states_range[1] = visit.TimeSliderGetNStates()
        else:
            states_range[1] += 1
        states = range(*states_range)

    for i, state in enumerate(states):
        print('[state {}] Rendering and saving figure ...'.format(state))
        visit.SetTimeSliderState(state)

        if i == 0:
            visit.DrawPlots()

        RenderingAtts = visit.RenderingAttributes()
        visit.SetRenderingAttributes(RenderingAtts)

        SaveWindowAtts = visit.SaveWindowAttributes()
        SaveWindowAtts.outputToCurrentDirectory = 0
        SaveWindowAtts.outputDirectory = str(out_dir)
        SaveWindowAtts.fileName = '{}{:0>4}'.format(out_prefix, state)
        SaveWindowAtts.family = 0
        SaveWindowAtts.format = SaveWindowAtts.PNG
        SaveWindowAtts.width = figsize[0]
        SaveWindowAtts.height = figsize[1]
        SaveWindowAtts.quality = 100
        SaveWindowAtts.resConstraint = SaveWindowAtts.NoConstraint
        visit.SetSaveWindowAttributes(SaveWindowAtts)

        visit.SaveWindow()

    os.remove('visitlog.py')
    visit.Close()
    return
Example #10
0
def visit_config(geometry_file, data_file, args):
    """
    Convert geometry file to stl, convert data file to vtk, load each file
    into VisIt, and create and load a session file containing four plot windows.
        1) A cube with a slice through an octant.
        2) XY plane slice through the centroid.
        3) XZ plane slice through the centroid.
        4) YZ plane slice through the centroid.
    Each window has a mesh plot with the "STL_mesh" variable, a Pseudocolor plot
    with the "TALLY_TAG" variable, and the second, third, and fourth windows have
    Contour plots with the "ERROR_TAG" variable. If the user has indicated to,
    launch VisIt and load the session file.

    Input:
    ______
       geometry_file: h5m file
           User supplied geometry file.
       data_file: h5m or vtk file
           User supplied data file.
       args: Namespace
           User supplied geometry file location, data file location, and
           indication if the user wants images of the plot windows with a
           timestamp and the session file saved and opened in VisIt.

    Returns:
    ________
       None
    """

    # Create a list of dictionaries indicating the data, plot, and variable in VisIt.
    Files = [{
        "file_name": data_file,
        "plot_type": "Pseudocolor",
        "data_tag": "TALLY_TAG"
    }, {
        "file_name": data_file,
        "plot_type": "Contour",
        "data_tag": "ERROR_TAG"
    }, {
        "file_name": geometry_file,
        "plot_type": "Mesh",
        "data_tag": "STL_mesh"
    }]

    # Launch VisIt and add appropriate plots.
    Vi.LaunchNowin()
    for file in Files:
        Vi.OpenDatabase(file["file_name"])
        Vi.AddPlot(file["plot_type"], file["data_tag"])

    # Hide the contour plot in the first plot window.
    Vi.SetActivePlots(1)
    Vi.HideActivePlots()

    # Create the plot of the cube by activating the mesh and pseudocolor plots.
    Vi.SetActivePlots((0, 2))

    # Set the view normal to the first octant.
    v = Vi.GetView3D()
    v.viewNormal = (1, 1, 1)
    Vi.SetView3D(v)

    # Apply a clip through the first octant.
    Vi.AddOperator("Clip")
    c = Vi.ClipAttributes()
    c.plane1Origin = (40, 40, 40)
    c.plane1Normal = (1, 1, 1)
    Vi.SetOperatorOptions(c)

    # Include the CNERG logo in the bottom left corner of the plot.
    image = Vi.CreateAnnotationObject("Image")
    image.image = os.path.dirname(os.path.abspath(__file__)) + "/cnerg.jpg"
    image.position = (0.02, 0.02)
    image.width = 10
    image.height = 10

    Vi.DrawPlots()
    if args.images:
        if args.timestamp:
            attributes = Vi.GetAnnotationAttributes()
            attributes.userInfoFlag = 0
            Vi.SetAnnotationAttributes(attributes)
        Vi.SaveWindow()

    # Create the second plot of the XY plane slice.
    plane_slice_plotting(2, 2, "XY Plane", args.images, args.timestamp)

    # Create the third plot of the XZ plane slice.
    plane_slice_plotting(3, 1, "XZ Plane", args.images, args.timestamp)

    # Create the fourth plot of the YZ plane slice.
    plane_slice_plotting(4, 0, "ZY Plane", args.images, args.timestamp)

    # Display the four windows in a 2x2 grid.
    Vi.SetWindowLayout(4)

    # Save the session file with the default VisIt output to the current directory.
    visit_output = "VisitDefaultOutput.session"
    Vi.SaveSession(visit_output)
    Vi.Close()

    # Retrieve the path to the VisIt session file.
    session_file_path = os.path.join(os.getcwd(), visit_output)

    # If the user has indicated to, open the session file with the VisIt GUI.
    if args.openvisit:
        os.system("visit -sessionfile {} &".format(session_file_path))

    # If the user has indicated to, remove the session file after VisIt has opened.
    if not args.sessionfile:
        os.system("sleep 10; rm {}".format(session_file_path))
Example #11
0
def make_moving_frame_of_reference_movie(x_begin,
                                         x_end,
                                         y_begin,
                                         y_end,
                                         speed_x,
                                         speed_y,
                                         variable_name,
                                         minThreshold,
                                         maxThreshold,
                                         input_directory,
                                         input_file_name,
                                         output_directory,
                                         output_file_name,
                                         color_table="hot_desaturated",
                                         start_frame=-1,
                                         end_frame=-1,
                                         frame_skip_dt=1.0):
    '''
   Function for making a movie with a moving frame of reference.
   :param x_begin             The starting frame's beginning x-coordinate
   :param x_end               The starting frame's ending x-coordinate
   :param y_begin             The starting frame's beginning x-coordinate
   :param y_end               The starting frame's ending y-coordinate
   :param speed_x             The speed at which the frame moves in the x direction
   :param speed_y             The speed at which the frame moves in the y direction
   :param variable_name       Name of the variable (For ex \"rho\")
   :param minThreshold        Minimum threshold for the variable
   :param maxThreshold        Maximum threshold for the variable
   :param input_directory     The path to the directory where the files are
   :param input_file_name     Name of the files (For ex \"bulk.*.silo\")
   :param output_directory    Directory where to output the movie
   :param output_file_name    Name of the outputted file (For ex \"RHOMOVIE\")
   :param color_table         Name of the color table (\"hot_desaturated\" by default)
   :param start_frame         Starting frame for the movie (if -1, equals 0, -1 by default)
   :param end_frame           Ending frame for the movie (if -1, equals the last frame, -1 by default)
   :param frame_skip_dt       The number of seconds one skip in frame equals (1.0 by default) (Note: This may change depending on the run and should always be checked)
   '''
    # OPTIONS
    #################################################################
    # Input the boundary box for starting coordinates (Starting values)
    startX = x_begin  # The left x-boundary of the box
    endX = x_end  # The right x-boundary of the box
    startY = y_begin  # The bottom y-boundary of the box
    endY = y_end  # The upper y-boundary of the box

    # Input frame properties
    startFrame = start_frame  # Note: if startFrame is set to -1 the start frame gets set to 0
    endFrame = end_frame  # Note: if endFrame is set to -1 the endFrame is automatically the number of frames in the database
    frameInSeconds = frame_skip_dt  # Set how many seconds one frame skip is

    # Input speed in x and y direction
    speedX = speed_x  # Meters per second
    speedY = speed_y  # Meters per second

    # Input variable
    variableName = variable_name
    minVariableValue = minThreshold
    maxVariableValue = maxThreshold
    colorTableName = color_table

    # Input directory and file names
    outputDir = output_directory  # Set the output directory (Where .png s are saved)
    outputFileName = output_file_name  # The file names for the png files. These for ex. will be saved visit0000.png, visit0001.png, .
    databaseName = "localhost:" + input_directory + input_file_name + " database"  # For navigating to the silo files
    # visitBinDirectory = "/usr/local/visit/bin" #Nevermind this
    # Note: a slice of the plot in z-axis is taken automatically
    #################################################################

    # Launch visit
    visitBinDirectory = '/home/htest/visit/bin'
    vis.LaunchNowin(vdir=visitBinDirectory)
    dx = speedX * frameInSeconds  # Note: This is in meters per frame!
    dy = speedY * frameInSeconds  # Note: This is in meters per frame!
    #Set up window and annotations
    vis.OpenDatabase(databaseName, 0)
    #Load settings
    visSettings.load_visit_settings()

    vis.AddPlot("Pseudocolor", variableName, 1, 1)
    vis.SetActivePlots(0)
    vis.PseudocolorAtts = vis.PseudocolorAttributes()
    vis.PseudocolorAtts.legendFlag = 1
    vis.PseudocolorAtts.lightingFlag = 1
    vis.PseudocolorAtts.minFlag = 1
    vis.PseudocolorAtts.maxFlag = 1
    vis.PseudocolorAtts.centering = vis.PseudocolorAtts.Natural  # Natural, Nodal, Zonal
    vis.PseudocolorAtts.scaling = vis.PseudocolorAtts.Linear  # Linear, Log, Skew
    vis.PseudocolorAtts.limitsMode = vis.PseudocolorAtts.CurrentPlot  # OriginalData, CurrentPlot
    vis.PseudocolorAtts.min = minVariableValue
    vis.PseudocolorAtts.max = maxVariableValue
    vis.PseudocolorAtts.pointSize = 0.05
    vis.PseudocolorAtts.pointType = vis.PseudocolorAtts.Point  # Box, Axis, Icosahedron, Point, Sphere
    vis.PseudocolorAtts.skewFactor = 1
    vis.PseudocolorAtts.opacity = 1
    vis.PseudocolorAtts.colorTableName = color_table
    vis.PseudocolorAtts.invertColorTable = 0
    vis.PseudocolorAtts.smoothingLevel = 0
    vis.PseudocolorAtts.pointSizeVarEnabled = 0
    vis.PseudocolorAtts.pointSizeVar = "default"
    vis.PseudocolorAtts.pointSizePixels = 2
    vis.PseudocolorAtts.lineStyle = vis.PseudocolorAtts.SOLID  # SOLID, DASH, DOT, DOTDASH
    vis.PseudocolorAtts.lineWidth = 0
    vis.PseudocolorAtts.opacityType = vis.PseudocolorAtts.Explicit  # Explicit, ColorTable
    vis.SetPlotOptions(vis.PseudocolorAtts)
    vis.SetActivePlots(0)
    vis.AddOperator("Slice", 1)
    vis.AddOperator("Threshold", 1)
    vis.ThresholdAtts = vis.ThresholdAttributes()
    vis.ThresholdAtts.outputMeshType = 0
    vis.ThresholdAtts.listedVarNames = ("Boundary_type")
    vis.ThresholdAtts.zonePortions = (1)
    vis.ThresholdAtts.lowerBounds = (1)
    vis.ThresholdAtts.upperBounds = (1)
    vis.ThresholdAtts.defaultVarName = variableName
    vis.ThresholdAtts.defaultVarIsScalar = 1
    vis.SetOperatorOptions(vis.ThresholdAtts, 1)
    vis.ThresholdAtts = vis.ThresholdAttributes()
    vis.ThresholdAtts.outputMeshType = 0
    vis.ThresholdAtts.listedVarNames = ("Boundary_type")
    vis.ThresholdAtts.zonePortions = (1)
    vis.ThresholdAtts.lowerBounds = (1)
    vis.ThresholdAtts.upperBounds = (1)
    vis.ThresholdAtts.defaultVarName = variableName
    vis.ThresholdAtts.defaultVarIsScalar = 1
    vis.SetOperatorOptions(vis.ThresholdAtts, 1)
    vis.SetActivePlots(0)
    vis.SliceAtts = vis.SliceAttributes()
    vis.SliceAtts.originType = vis.SliceAtts.Intercept  # Point, Intercept, Percent, Zone, Node
    vis.SliceAtts.originPoint = (0, 0, 0)
    vis.SliceAtts.originIntercept = 0
    vis.SliceAtts.originPercent = 0
    vis.SliceAtts.originZone = 0
    vis.SliceAtts.originNode = 0
    vis.SliceAtts.normal = (0, 0, 1)
    vis.SliceAtts.axisType = vis.SliceAtts.ZAxis  # XAxis, YAxis, ZAxis, Arbitrary, ThetaPhi
    vis.SliceAtts.upAxis = (0, 1, 0)
    vis.SliceAtts.project2d = 1
    vis.SliceAtts.interactive = 1
    vis.SliceAtts.flip = 0
    vis.SliceAtts.originZoneDomain = 0
    vis.SliceAtts.originNodeDomain = 0
    vis.SliceAtts.meshName = "SpatialGrid"
    vis.SliceAtts.theta = 0
    vis.SliceAtts.phi = 90
    vis.SetOperatorOptions(vis.SliceAtts, 1)
    vis.DrawPlots()

    if endFrame == -1:
        endFrame = vis.TimeSliderGetNStates() - 1

    if startFrame == -1:
        startFrame = 0

    # Iterate through frames
    for i in xrange(startFrame, endFrame + 1):
        vis.SetTimeSliderState(i)
        frame = i - startFrame
        vis.View2DAtts = vis.View2DAttributes()
        vis.View2DAtts.windowCoords = (startX + frame * dx, endX + frame * dx,
                                       startY + frame * dy, endY + frame * dy)
        vis.View2DAtts.viewportCoords = (0.2, 0.95, 0.15, 0.95)
        vis.View2DAtts.fullFrameActivationMode = vis.View2DAtts.Auto  # On, Off, Auto
        vis.View2DAtts.fullFrameAutoThreshold = 100
        vis.View2DAtts.xScale = vis.View2DAtts.LINEAR  # LINEAR, LOG
        vis.View2DAtts.yScale = vis.View2DAtts.LINEAR  # LINEAR, LOG
        vis.View2DAtts.windowValid = 1
        vis.SetView2D(vis.View2DAtts)
        vis.SaveWindowAtts = vis.SaveWindowAttributes()
        vis.SaveWindowAtts.outputToCurrentDirectory = 0
        vis.SaveWindowAtts.outputDirectory = outputDir
        vis.SaveWindowAtts.fileName = outputFileName
        vis.SaveWindowAtts.family = 1
        vis.SaveWindowAtts.format = vis.SaveWindowAtts.PNG  # BMP, CURVE, JPEG, OBJ, PNG, POSTSCRIPT, POVRAY, PPM, RGB, STL, TIFF, ULTRA, VTK, PLY
        vis.SaveWindowAtts.width = 1024
        vis.SaveWindowAtts.height = 1024
        vis.SaveWindowAtts.screenCapture = 0
        vis.SaveWindowAtts.saveTiled = 0
        vis.SaveWindowAtts.quality = 100
        vis.SaveWindowAtts.progressive = 0
        vis.SaveWindowAtts.binary = 0
        vis.SaveWindowAtts.stereo = 0
        vis.SaveWindowAtts.compression = vis.SaveWindowAtts.PackBits  # None, PackBits, Jpeg, Deflate
        vis.SaveWindowAtts.forceMerge = 0
        vis.SaveWindowAtts.resConstraint = vis.SaveWindowAtts.ScreenProportions  # NoConstraint, EqualWidthHeight, ScreenProportions
        vis.SaveWindowAtts.advancedMultiWindowSave = 0
        vis.SetSaveWindowAttributes(vis.SaveWindowAtts)
        vis.SaveWindow()
    vis.DeleteActivePlots()
    vis.CloseDatabase(databaseName)
    # Make the movie:
    framerate = 7
    subprocess.call([
        pythonLibDirectoryPath + pyVisitPath + "moviecompilescript.sh",
        outputDir, outputFileName, framerate
    ])
Example #12
0
    # Create a list of dictionaries indicating the data, plot, and variable in VisIt.
    Files = [{
        "file_name": geometry_file,
        "plot_type": "Mesh",
        "data_tag": "STL_mesh"
    }, {
        "file_name": data_file,
        "plot_type": "Pseudocolor",
        "data_tag": "TALLY_TAG"
    }, {
        "file_name": data_file,
        "plot_type": "Contour",
        "data_tag": "ERROR_TAG"
    }]

    Vi.LaunchNowin()
    for file in Files:
        Vi.OpenDatabase(file["file_name"])
        Vi.AddPlot(file["plot_type"], file["data_tag"])

    # Hide the contour plot in the first plot window.
    Vi.SetActivePlots(2)
    Vi.HideActivePlots()

    # Create the plot of the cube by activating the mesh and pseudocolor plots.
    Vi.SetActivePlots((0, 1))

    # Set the view normal to the first octant.
    v = Vi.GetView3D()
    v.viewNormal = (1, 1, 1)
    Vi.SetView3D(v)
Example #13
0
def visit_initialize():
    visit.LaunchNowin()
    visit_check_version(visit.Version())
def visit_initialize():
    """Launch VisIt in no-window mode and check VisIt version."""
    visit.LaunchNowin()
    visit_check_version()