Esempio n. 1
0
    def __init__(
        self,
        filename="abl.nek5000",
        arrays=(
            "pressure",
            "velocity_mag",
            "x_velocity",
            "y_velocity",
            "z_velocity",
        ),
    ):
        self.filename = filename
        assert Path(filename).exists()

        self.nek5000 = nek5000 = pv.VisItNek5000Reader(FileName=str(filename))
        nek5000.Meshes = ["mesh"]

        # get animation scene
        self.animationScene1 = pv.GetAnimationScene()

        # get the time-keeper
        self.timeKeeper1 = pv.GetTimeKeeper()

        # update animation scene based on data timesteps
        self.animationScene1.UpdateAnimationUsingDataTimeSteps()

        # Properties modified on ablnek5000
        assert isinstance(arrays, (list, tuple))
        nek5000.PointArrays = list(arrays)

        data_info = nek5000.GetDataInformation()
        self.dtype = data_info.GetDataSetTypeAsString()
Esempio n. 2
0
 def goToPrev(self):
     oldTime = self.View.ViewTime
     simple.GetAnimationScene().GoToPrevious()
     if oldTime != self.View.ViewTime:
         self.factory.dispatch("http://vtk.org/event#probeDataChanged", True)
         return True
     return False
    def setupApplication(cls):
        """Setups the default application state."""
        # read data directory.

        root = {"name": "ROOT", "dirs": [], "files": []}
        directory_map = {}
        directory_map[_DataProber.DataPath] = root
        for path, dirs, files in os.walk(_DataProber.DataPath):
            element = directory_map[path]

            for name in dirs:
                item = {"name": name, "dirs": [], "files": []}
                item["name"] = name
                directory_map[os.path.join(path, name)] = item
                element["dirs"].append(item)
            element["files"] = []
            for name in files:
                relpath = os.path.relpath(os.path.join(path, name),
                                          _DataProber.DataPath)
                item = {"name": name, "itemValue": relpath}
                element["files"].append(item)
        cls.Database = root
        cls.View = simple.CreateRenderView()
        simple.Render()

        # setup animation scene
        scene = simple.GetAnimationScene()
        simple.GetTimeTrack()
        scene.PlayMode = "Snap To TimeSteps"
 def goToPrev(self):
     oldTime = self.View.ViewTime
     simple.GetAnimationScene().GoToPrevious()
     if oldTime != self.View.ViewTime:
         self.publish("vtk.event.probe.data.changed", True)
         print 'publish b'
         return True
     return False
Esempio n. 5
0
    def saveView(self, reader):
        """Save figure
        """

        # Get animation scene
        animationScene = pv.GetAnimationScene()
        animationScene.PlayMode = "Snap To TimeSteps"

        # Save animation images
        print("[PNGViewer] ###  Generating PNG images...")
        for t in reader.TimestepValues.GetData()[:]:
            animationScene.AnimationTime = t
            pv.WriteImage(self.file_name + ".%f.png" % t)
        print("[PNGViewer] ### All PNG images generated.")
Esempio n. 6
0
        def create_scene(self,
                         start,
                         end,
                         duration,
                         mode='Real Time',
                         loop=True):
            "Inicializa a visualização da animação."
            scene = pv.GetAnimationScene()
            scene.EndTime = end
            scene.Duration = duration
            scene.StartTime = start
            scene.PlayMode = mode
            scene.Loop = int(loop)

            self.objects_['scene'] = scene
Esempio n. 7
0
    def read(self):
        path = self.path_run
        if path.is_dir():
            path = next(path.glob("*.nek5000"))

        # TODO: needed or not?
        # pvs._DisableFirstRenderCameraReset()
        self.reader = reader = VisItNek5000Reader(FileName=str(path))
        if not reader:
            raise IOError("Error while loading file " + path)

        reader.Meshes = ["mesh"]
        # get animation scene
        self.animationScene = pvs.GetAnimationScene()

        # get the time-keeper
        self.timeKeeper = pvs.GetTimeKeeper()
Esempio n. 8
0
    def updateTime(self, action):
        view = simple.GetRenderView()
        animationScene = simple.GetAnimationScene()
        currentTime = view.ViewTime

        if action == "next":
            animationScene.GoToNext()
            if currentTime == view.ViewTime:
                animationScene.GoToFirst()
        if action == "prev":
            animationScene.GoToPrevious()
            if currentTime == view.ViewTime:
                animationScene.GoToLast()
        if action == "first":
            animationScene.GoToFirst()
        if action == "last":
            animationScene.GoToLast()

        return view.ViewTime
Esempio n. 9
0
    def saveView(self, reader):
        """Save animation
        """

        # Get animation scene
        animationScene = pv.GetAnimationScene()
        animationScene.PlayMode = "Snap To TimeSteps"

        # Save animation images
        for t in reader.TimestepValues.GetData()[:]:
            animationScene.AnimationTime = t

        # Save animation movie
        print("[AnimationViewer] ###  Generating AVI animation...")
        pv.WriteAnimation(self.file_name + ".avi",
                          Magnification=1,
                          Quality=2,
                          FrameRate=1.0,
                          Compression=True)
        print("[AnimationViewer] ### AVI animation generated.")
Esempio n. 10
0
 def updateActiveArgument(self, key, value):
     if key == "time":
         simple.GetAnimationScene().TimeKeeper.Time = float(value)
     elif _PVCatalystManager.pipeline_handler:
         _PVCatalystManager.pipeline_handler.update_argument(key, value)
Esempio n. 11
0
 def __init__(self):
     super(ParaViewWebTimeHandler, self).__init__()
     # setup animation scene
     self.scene = simple.GetAnimationScene()
     simple.GetTimeTrack()
     self.scene.PlayMode = "Snap To TimeSteps"
Esempio n. 12
0
from paraview import simple
from paraview.web.dataset_builder import *

# -----------------------------------------------------------------------------
# Pipeline creation
# -----------------------------------------------------------------------------

can = simple.OpenDataFile(inputFile)
can.ElementVariables = ['EQPS']
can.PointVariables = ['DISPL', 'VEL', 'ACCL']
can.GlobalVariables = ['KE', 'XMOM', 'YMOM', 'ZMOM', 'NSTEPS', 'TMSTEP']
can.ElementBlocks = [
    'Unnamed block ID: 1 Type: HEX', 'Unnamed block ID: 2 Type: HEX'
]

anim = simple.GetAnimationScene()
anim.UpdateAnimationUsingDataTimeSteps()

timeValues = anim.TimeKeeper.TimestepValues

sceneDescription = {
    'scene': [{
        'name': 'Can',
        'source': can,
        'colors': {
            'DISPL': {
                'location': 'POINT_DATA'
            },
            'VEL': {
                'location': 'POINT_DATA'
            },
Esempio n. 13
0
def render_frames(
    scene,
    frames_dir=None,
    frame_window=None,
    render_missing_frames=False,
    save_state_to_file=None,
    no_render=False,
    show_preview=False,
    show_progress=False,
    job_id=None,
):
    # Validate scene
    if scene["View"]["ViewSize"][0] % 16 != 0:
        logger.warning(
            "The view width should be a multiple of 16 to be compatible with"
            " QuickTime.")
    if scene["View"]["ViewSize"][1] % 2 != 0:
        logger.warning(
            "The view height should be even to be compatible with QuickTime.")

    render_start_time = time.time()

    # Setup layout
    layout = pv.CreateLayout("Layout")

    # Setup view
    if "Background" in scene["View"]:
        bg_config = scene["View"]["Background"]
        del scene["View"]["Background"]
        if isinstance(bg_config, list):
            if isinstance(bg_config[0], list):
                assert len(bg_config) == 2, (
                    "When 'Background' is a list of colors, it must have 2"
                    " entries.")
                bg_config = dict(
                    BackgroundColorMode="Gradient",
                    Background=parse_as.color(bg_config[0]),
                    Background2=parse_as.color(bg_config[1]),
                )
            else:
                bg_config = dict(
                    BackgroundColorMode="Single Color",
                    Background=parse_as.color(bg_config),
                )
            bg_config["UseColorPaletteForBackground"] = 0
            scene["View"].update(bg_config)
            bg_config = None
    else:
        bg_config = None
    view = pv.CreateRenderView(**scene["View"])
    pv.AssignViewToLayout(view=view, layout=layout, hint=0)

    # Set spherical background texture
    if bg_config is not None:
        bg_config["BackgroundColorMode"] = "Texture"
        skybox_datasource = bg_config["Datasource"]
        del bg_config["Datasource"]
        background_texture = pvserver.rendering.ImageTexture(
            FileName=parse_as.path(scene["Datasources"][skybox_datasource]))
        background_sphere = pv.Sphere(Radius=bg_config["Radius"],
                                      ThetaResolution=100,
                                      PhiResolution=100)
        background_texture_map = pv.TextureMaptoSphere(Input=background_sphere)
        pv.Show(
            background_texture_map,
            view,
            Texture=background_texture,
            BackfaceRepresentation="Cull Frontface",
            Ambient=1.0,
        )

    # Load the waveform data file
    waveform_h5file, waveform_subfile = parse_as.file_and_subfile(
        scene["Datasources"]["Waveform"])
    waveform_data = WaveformDataReader(FileName=waveform_h5file,
                                       Subfile=waveform_subfile)
    pv.UpdatePipeline()

    # Generate volume data from the waveform. Also sets the available time range.
    # TODO: Pull KeepEveryNthTimestep out of datasource
    waveform_to_volume_configs = scene["WaveformToVolume"]
    if isinstance(waveform_to_volume_configs, dict):
        waveform_to_volume_configs = [{
            "Object": waveform_to_volume_configs,
        }]
        if "VolumeRepresentation" in scene:
            waveform_to_volume_configs[0]["VolumeRepresentation"] = scene[
                "VolumeRepresentation"]
    waveform_to_volume_objects = []
    for waveform_to_volume_config in waveform_to_volume_configs:
        volume_data = WaveformToVolume(
            WaveformData=waveform_data,
            SwshCacheDirectory=parse_as.path(
                scene["Datasources"]["SwshCache"]),
            **waveform_to_volume_config["Object"],
        )
        if "Modes" in waveform_to_volume_config["Object"]:
            volume_data.Modes = waveform_to_volume_config["Object"]["Modes"]
        if "Polarizations" in waveform_to_volume_config["Object"]:
            volume_data.Polarizations = waveform_to_volume_config["Object"][
                "Polarizations"]
        waveform_to_volume_objects.append(volume_data)

    # Compute timing and frames information
    time_range_in_M = (
        volume_data.TimestepValues[0],
        volume_data.TimestepValues[-1],
    )
    logger.debug(f"Full available data time range: {time_range_in_M} (in M)")
    if "FreezeTime" in scene["Animation"]:
        frozen_time = scene["Animation"]["FreezeTime"]
        logger.info(f"Freezing time at {frozen_time}.")
        view.ViewTime = frozen_time
        animation = None
    else:
        if "Crop" in scene["Animation"]:
            time_range_in_M = scene["Animation"]["Crop"]
            logger.debug(f"Cropping time range to {time_range_in_M} (in M).")
        animation_speed = scene["Animation"]["Speed"]
        frame_rate = scene["Animation"]["FrameRate"]
        num_frames = animate.num_frames(
            max_animation_length=time_range_in_M[1] - time_range_in_M[0],
            animation_speed=animation_speed,
            frame_rate=frame_rate,
        )
        animation_length_in_seconds = num_frames / frame_rate
        animation_length_in_M = animation_length_in_seconds * animation_speed
        time_per_frame_in_M = animation_length_in_M / num_frames
        logger.info(f"Rendering {animation_length_in_seconds:.2f}s movie with"
                    f" {num_frames} frames ({frame_rate} FPS or"
                    f" {animation_speed:.2e} M/s or"
                    f" {time_per_frame_in_M:.2e} M/frame)...")
        if frame_window is not None:
            animation_window_num_frames = frame_window[1] - frame_window[0]
            animation_window_time_range = (
                time_range_in_M[0] + frame_window[0] * time_per_frame_in_M,
                time_range_in_M[0] +
                (frame_window[1] - 1) * time_per_frame_in_M,
            )
            logger.info(
                f"Restricting rendering to {animation_window_num_frames} frames"
                f" (numbers {frame_window[0]} to {frame_window[1] - 1}).")
        else:
            animation_window_num_frames = num_frames
            animation_window_time_range = time_range_in_M
            frame_window = (0, num_frames)

        # Setup animation so that sources can retrieve the `UPDATE_TIME_STEP`
        animation = pv.GetAnimationScene()
        # animation.UpdateAnimationUsingDataTimeSteps()
        # Since the data can be evaluated at arbitrary times we define the time steps
        # here by setting the number of frames within the full range
        animation.PlayMode = "Sequence"
        animation.StartTime = animation_window_time_range[0]
        animation.EndTime = animation_window_time_range[1]
        animation.NumberOfFrames = animation_window_num_frames
        logger.debug(
            f"Animating from scene time {animation.StartTime} to"
            f" {animation.EndTime} in {animation.NumberOfFrames} frames.")

        def scene_time_from_real(real_time):
            return (real_time / animation_length_in_seconds *
                    animation_length_in_M)

        # For some reason the keyframe time for animations is expected to be within
        # (0, 1) so we need to transform back and forth from this "normalized" time
        def scene_time_from_normalized(normalized_time):
            return animation.StartTime + normalized_time * (
                animation.EndTime - animation.StartTime)

        def normalized_time_from_scene(scene_time):
            return (scene_time - animation.StartTime) / (animation.EndTime -
                                                         animation.StartTime)

        # Setup progress measuring already here so volume data computing for
        # initial frame is measured
        if show_progress and not no_render:
            logging.getLogger().handlers = [TqdmLoggingHandler()]
            animation_window_frame_range = tqdm.trange(
                animation_window_num_frames,
                desc="Rendering",
                unit="frame",
                miniters=1,
                position=job_id,
            )
        else:
            animation_window_frame_range = range(animation_window_num_frames)

        # Set the initial time step
        animation.GoToFirst()

    # Display the volume data. This will trigger computing the volume data at the
    # current time step.
    for volume_data, waveform_to_volume_config in zip(
            waveform_to_volume_objects, waveform_to_volume_configs):
        vol_repr = (waveform_to_volume_config["VolumeRepresentation"]
                    if "VolumeRepresentation" in waveform_to_volume_config else
                    {})
        volume_color_by = config_color.extract_color_by(vol_repr)
        if (vol_repr["VolumeRenderingMode"] == "GPU Based"
                and len(volume_color_by) > 2):
            logger.warning(
                "The 'GPU Based' volume renderer doesn't support multiple"
                " components.")
        volume = pv.Show(volume_data, view, **vol_repr)
        pv.ColorBy(volume, value=volume_color_by)

    if "Slices" in scene:
        for slice_config in scene["Slices"]:
            slice_obj_config = slice_config.get("Object", {})
            slice = pv.Slice(Input=volume_data)
            slice.SliceType = "Plane"
            slice.SliceOffsetValues = [0.0]
            slice.SliceType.Origin = slice_obj_config.get(
                "Origin", [0.0, 0.0, -0.3])
            slice.SliceType.Normal = slice_obj_config.get(
                "Normal", [0.0, 0.0, 1.0])
            slice_rep = pv.Show(slice, view,
                                **slice_config.get("Representation", {}))
            pv.ColorBy(slice_rep, value=volume_color_by)

    # Display the time
    if "TimeAnnotation" in scene:
        time_annotation = pv.AnnotateTimeFilter(volume_data,
                                                **scene["TimeAnnotation"])
        pv.Show(time_annotation, view, **scene["TimeAnnotationRepresentation"])

    # Add spheres
    if "Spheres" in scene:
        for sphere_config in scene["Spheres"]:
            sphere = pv.Sphere(**sphere_config["Object"])
            pv.Show(sphere, view, **sphere_config["Representation"])

    # Add trajectories and objects that follow them
    if "Trajectories" in scene:
        for trajectory_config in scene["Trajectories"]:
            trajectory_name = trajectory_config["Name"]
            radial_scale = (trajectory_config["RadialScale"]
                            if "RadialScale" in trajectory_config else 1.0)
            # Load the trajectory data
            traj_data_reader = TrajectoryDataReader(
                RadialScale=radial_scale,
                **scene["Datasources"]["Trajectories"][trajectory_name],
            )
            # Make sure the data is loaded so we can retrieve timesteps.
            # TODO: This should be fixed in `TrajectoryDataReader` by
            # communicating time range info down the pipeline, but we had issues
            # with that (see also `WaveformDataReader`).
            traj_data_reader.UpdatePipeline()
            if "Objects" in trajectory_config:
                with animate.restore_animation_state(animation):
                    follow_traj = FollowTrajectory(
                        TrajectoryData=traj_data_reader)
                for traj_obj_config in trajectory_config["Objects"]:
                    for traj_obj_key in traj_obj_config:
                        if traj_obj_key in [
                                "Representation",
                                "Visibility",
                                "TimeShift",
                                "Glyph",
                        ]:
                            continue
                        traj_obj_type = getattr(pv, traj_obj_key)
                        traj_obj_glyph = traj_obj_type(
                            **traj_obj_config[traj_obj_key])
                    follow_traj.UpdatePipeline()
                    traj_obj = pv.Glyph(Input=follow_traj,
                                        GlyphType=traj_obj_glyph)
                    # Can't set this in the constructor for some reason
                    traj_obj.ScaleFactor = 1.0
                    for glyph_property in (traj_obj_config["Glyph"] if "Glyph"
                                           in traj_obj_config else []):
                        setattr(
                            traj_obj,
                            glyph_property,
                            traj_obj_config["Glyph"][glyph_property],
                        )
                    traj_obj.UpdatePipeline()
                    if "TimeShift" in traj_obj_config:
                        traj_obj = animate.apply_time_shift(
                            traj_obj, traj_obj_config["TimeShift"])
                    pv.Show(traj_obj, view,
                            **traj_obj_config["Representation"])
                    if "Visibility" in traj_obj_config:
                        animate.apply_visibility(
                            traj_obj,
                            traj_obj_config["Visibility"],
                            normalized_time_from_scene,
                            scene_time_from_real,
                        )
            if "Tail" in trajectory_config:
                with animate.restore_animation_state(animation):
                    traj_tail = TrajectoryTail(TrajectoryData=traj_data_reader)
                if "TimeShift" in trajectory_config:
                    traj_tail = animate.apply_time_shift(
                        traj_tail, trajectory_config["TimeShift"])
                tail_config = trajectory_config["Tail"]
                traj_color_by = config_color.extract_color_by(tail_config)
                if "Visibility" in tail_config:
                    tail_visibility_config = tail_config["Visibility"]
                    del tail_config["Visibility"]
                else:
                    tail_visibility_config = None
                tail_rep = pv.Show(traj_tail, view, **tail_config)
                pv.ColorBy(tail_rep, value=traj_color_by)
                if tail_visibility_config is not None:
                    animate.apply_visibility(
                        traj_tail,
                        tail_visibility_config,
                        normalized_time_from_scene=normalized_time_from_scene,
                        scene_time_from_real=scene_time_from_real,
                    )
            if "Move" in trajectory_config:
                move_config = trajectory_config["Move"]
                logger.debug(
                    f"Animating '{move_config['guiName']}' along trajectory.")
                with h5py.File(trajectory_file, "r") as traj_data_file:
                    trajectory_data = np.array(
                        traj_data_file[trajectory_subfile])
                if radial_scale != 1.0:
                    trajectory_data[:, 1:] *= radial_scale
                logger.debug(f"Trajectory data shape: {trajectory_data.shape}")
                animate.follow_path(
                    gui_name=move_config["guiName"],
                    trajectory_data=trajectory_data,
                    num_keyframes=move_config["NumKeyframes"],
                    scene_time_range=time_range_in_M,
                    normalized_time_from_scene=normalized_time_from_scene,
                )

    # Add non-spherical horizon shapes (instead of spherical objects following
    # trajectories)
    if "Horizons" in scene:
        for horizon_config in scene["Horizons"]:
            with animate.restore_animation_state(animation):
                horizon = pv.PVDReader(FileName=scene["Datasources"]
                                       ["Horizons"][horizon_config["Name"]])
                if horizon_config.get("InterpolateTime", False):
                    horizon = pv.TemporalInterpolator(
                        Input=horizon, DiscreteTimeStepInterval=0)
            if "TimeShift" in horizon_config:
                horizon = animate.apply_time_shift(horizon,
                                                   horizon_config["TimeShift"],
                                                   animation)
            # Try to make horizon surfaces smooth. At low angular resoluton
            # they still show artifacts, so perhaps more can be done.
            horizon = pv.ExtractSurface(Input=horizon)
            horizon = pv.GenerateSurfaceNormals(Input=horizon)
            horizon_rep_config = horizon_config.get("Representation", {})
            if "Representation" not in horizon_rep_config:
                horizon_rep_config["Representation"] = "Surface"
            if "AmbientColor" not in horizon_rep_config:
                horizon_rep_config["AmbientColor"] = [0.0, 0.0, 0.0]
            if "DiffuseColor" not in horizon_rep_config:
                horizon_rep_config["DiffuseColor"] = [0.0, 0.0, 0.0]
            if "Specular" not in horizon_rep_config:
                horizon_rep_config["Specular"] = 0.2
            if "SpecularPower" not in horizon_rep_config:
                horizon_rep_config["SpecularPower"] = 10
            if "SpecularColor" not in horizon_rep_config:
                horizon_rep_config["SpecularColor"] = [1.0, 1.0, 1.0]
            if "ColorBy" in horizon_rep_config:
                horizon_color_by = config_color.extract_color_by(
                    horizon_rep_config)
            else:
                horizon_color_by = None
            horizon_rep = pv.Show(horizon, view, **horizon_rep_config)
            if horizon_color_by is not None:
                pv.ColorBy(horizon_rep, value=horizon_color_by)
            # Animate visibility
            if "Visibility" in horizon_config:
                animate.apply_visibility(
                    horizon,
                    horizon_config["Visibility"],
                    normalized_time_from_scene=normalized_time_from_scene,
                    scene_time_from_real=scene_time_from_real,
                )
            if "Contours" in horizon_config:
                for contour_config in horizon_config["Contours"]:
                    contour = pv.Contour(Input=horizon,
                                         **contour_config["Object"])
                    contour_rep = pv.Show(contour, view,
                                          **contour_config["Representation"])
                    pv.ColorBy(contour_rep, None)
                    if "Visibility" in horizon_config:
                        animate.apply_visibility(
                            contour,
                            horizon_config["Visibility"],
                            normalized_time_from_scene=
                            normalized_time_from_scene,
                            scene_time_from_real=scene_time_from_real,
                        )

    # Configure transfer functions
    if "TransferFunctions" in scene:
        for tf_config in scene["TransferFunctions"]:
            colored_field = tf_config["Field"]
            transfer_fctn = pv.GetColorTransferFunction(colored_field)
            opacity_fctn = pv.GetOpacityTransferFunction(colored_field)
            tf.configure_transfer_function(transfer_fctn, opacity_fctn,
                                           tf_config["TransferFunction"])

    # Save state file before configuring camera keyframes.
    # TODO: Make camera keyframes work with statefile
    if save_state_to_file is not None:
        pv.SaveState(save_state_to_file + ".pvsm")

    # Camera shots
    # TODO: Make this work with freezing time while the camera is swinging
    if animation is None:
        for i, shot in enumerate(scene["CameraShots"]):
            if (i == len(scene["CameraShots"]) - 1 or
                (shot["Time"] if "Time" in shot else 0.0) >= view.ViewTime):
                camera_motion.apply(shot)
                break
    else:
        camera_motion.apply_swings(
            scene["CameraShots"],
            scene_time_range=time_range_in_M,
            scene_time_from_real=scene_time_from_real,
            normalized_time_from_scene=normalized_time_from_scene,
        )

    # Report time
    if animation is not None:
        report_time_cue = pv.PythonAnimationCue()
        report_time_cue.Script = """
def start_cue(self): pass

def tick(self):
    import paraview.simple as pv
    import logging
    logger = logging.getLogger('Animation')
    scene_time = pv.GetActiveView().ViewTime
    logger.info(f"Scene time: {scene_time}")

def end_cue(self): pass
"""
        animation.Cues.append(report_time_cue)

    if show_preview and animation is not None:
        animation.PlayMode = "Real Time"
        animation.Duration = 10
        animation.Play()
        animation.PlayMode = "Sequence"

    if no_render:
        logger.info("No rendering requested. Total time:"
                    f" {time.time() - render_start_time:.2f}s")
        return

    if frames_dir is None:
        raise RuntimeError("Trying to render but `frames_dir` is not set.")
    if os.path.exists(frames_dir):
        logger.warning(
            f"Output directory '{frames_dir}' exists, files may be overwritten."
        )
    else:
        os.makedirs(frames_dir)

    if animation is None:
        pv.Render()
        pv.SaveScreenshot(os.path.join(frames_dir, "frame.png"))
    else:
        # Iterate over frames manually to support filling in missing frames.
        # If `pv.SaveAnimation` would support that, here's how it could be
        # invoked:
        # pv.SaveAnimation(
        #     os.path.join(frames_dir, 'frame.png'),
        #     view,
        #     animation,
        #     FrameWindow=frame_window,
        #     SuffixFormat='.%06d')
        # Note that `FrameWindow` appears to be buggy, so we set up the
        # `animation` according to the `frame_window` above so the frame files
        # are numberd correctly.
        for animation_window_frame_i in animation_window_frame_range:
            frame_i = frame_window[0] + animation_window_frame_i
            frame_file = os.path.join(frames_dir, f"frame.{frame_i:06d}.png")
            if render_missing_frames and os.path.exists(frame_file):
                continue
            logger.debug(f"Rendering frame {frame_i}...")
            animation.AnimationTime = (
                animation.StartTime +
                time_per_frame_in_M * animation_window_frame_i)
            pv.Render()
            pv.SaveScreenshot(frame_file)
            logger.info(f"Rendered frame {frame_i}.")

    logger.info(
        f"Rendering done. Total time: {time.time() - render_start_time:.2f}s")
def pvd_to_mp4(sim_dir,
               path_to_movies,
               movie_name='movie',
               representation='Surface',
               num_regions=0):

    ###############################
    # Validate directory and data #
    ###############################

    if not (os.path.isdir(sim_dir)):
        raise Exception('pvd_to_mp4: Invalid simulation directory')

    if not (os.path.isdir(path_to_movies)):
        raise Exception('pvd_to_mp4: Invalid movie directory')

    if representation not in ['Surface', 'Points']:
        raise Exception(
            'pvd_to_mp4: Representation must be either Surface or Points')

    if num_regions not in [0, 9]:
        raise Exception(
            'pvd_to_mp4: Currently there is only support for 9 node regions')

    # sim_id = os.path.basename(os.path.normpath(sim_dir))

    possible_data_directories = []
    for directory in os.listdir(sim_dir):
        if directory.startswith('results_from_time'):
            possible_data_directories.append(os.path.join(sim_dir, directory))

    if len(possible_data_directories) == 0:
        raise Exception(
            'pvd_to_mp4: Could not find a "results_from_time_X" directory')

    # The last directory alphabetically will be the one after any initial relaxation simulation
    data_directory = sorted(possible_data_directories)[-1]

    # Get the location of the pvd file
    pvd_file = os.path.join(data_directory, 'results.pvd')
    if not (os.path.isfile(pvd_file)):
        raise Exception('pvd_to_mp4: Could not find a pvd data file')

    if os.path.getsize(pvd_file) < 1024:
        raise Exception(
            'pvd_to_mp4: pvd file exists but is < 1kb. Presumably simulation failed to finish as expected.'
        )

    full_movie_path = os.path.join(path_to_movies,
                                   movie_name + '_' + representation + '.mp4')

    ##################################
    # Set up scene with box and data #
    ##################################

    # Get active view. This is the ParaView default view - blue background with cross hairs and orientation axes
    render_view = pv.GetActiveViewOrCreate('RenderView')

    # Change parameters to be how we want them for output
    render_view.ViewSize = [1600, 900]  # Size of output (pixels)
    render_view.CenterAxesVisibility = 0  # Remove cross hairs
    render_view.OrientationAxesVisibility = 0  # Remove orientation axes
    render_view.Background = [0.5, 0.5,
                              0.5]  # Set background colour to 50% grey

    # Create a unit square (a 3D Box with ZLength set to zero)
    unit_square = pv.Box()
    unit_square.ZLength = 0.0
    unit_square.YLength = 9.0 / 16.0
    unit_square.Center = [0.5, 0.5, 0.0]

    # Show the box in the current render view, and colour it black
    unit_square_display = pv.Show(unit_square, render_view)
    unit_square_display.DiffuseColor = [0.0, 0.0, 0.0]

    # Read the relevant pvd file from the Chaste output
    results_pvd = pv.PVDReader(FileName=pvd_file)

    # Show the data in the current render view as a surface
    results_pvd_display = pv.Show(results_pvd, render_view)
    results_pvd_display.Representation = representation

    if representation == 'Points' and num_regions == 9:
        pv.ColorBy(results_pvd_display, ('POINTS', 'Node Regions'))
        node_regions_lut = pv.GetColorTransferFunction('NodeRegions')

        # Each four digits are: data value, r, g, b (colour)
        node_regions_lut.RGBPoints = [
            0.0,
            1.00,
            0.00,
            0.00,  # LEFT_APICAL_REGION, red
            1.0,
            1.00,
            0.00,
            0.00,  # RIGHT_APICAL_REGION, red
            2.0,
            1.00,
            0.00,
            1.00,  # LEFT_PERIAPICAL_REGION, purple
            3.0,
            1.00,
            0.00,
            1.00,  # RIGHT_PERIAPICAL_REGION, purple
            4.0,
            0.00,
            0.00,
            1.00,  # LEFT_LATERAL_REGION, blue
            5.0,
            0.00,
            0.00,
            1.00,  # RIGHT_LATERAL_REGION, blue
            6.0,
            1.00,
            1.00,
            1.00,  # LEFT_BASAL_REGION, white
            7.0,
            1.00,
            1.00,
            1.00,  # RIGHT_BASAL_REGION, white
            8.0,
            1.00,
            1.00,
            1.00
        ]  # LAMINA_REGION, white

        cell_regions_lut = pv.GetColorTransferFunction('CellRegions')
        cell_regions_lut.RGBPoints = [
            -1.0,
            0.0,
            0.00,
            0.00,  # basal lamina, black
            0.0,
            0.00,
            0.00,
            1.00,  # left region, blue
            1.0,
            1.00,
            1.00,
            1.00,  # centre_region, white
            2.0,
            1.00,
            0.00,
            0.00
        ]  # right_region, red

        # Glyphs for cell region
        cell_glyphs = pv.Glyph(Input=results_pvd, GlyphType='2D Glyph')

        cell_glyphs.Scalars = ['CELLS', 'Cell Regions']
        cell_glyphs.ScaleFactor = 0.01
        cell_glyphs.GlyphMode = 'All Points'
        cell_glyphs.GlyphType.GlyphType = 'Diamond'
        cell_glyphs.GlyphType.Filled = 1
        cell_glyphs.GlyphTransform.Scale = [1.0, 2.0, 1.0]

        cell_glyphs_display = pv.Show(cell_glyphs, render_view)
        cell_glyphs_display.Opacity = 0.5

        # Glyphs for node region
        node_glyphs = pv.Glyph(Input=results_pvd, GlyphType='2D Glyph')

        node_glyphs.Scalars = ['POINTS', 'Node Regions']
        node_glyphs.ScaleFactor = 0.002
        node_glyphs.GlyphMode = 'All Points'
        node_glyphs.GlyphType.GlyphType = 'Circle'
        node_glyphs.GlyphType.Filled = 1

        pv.Show(node_glyphs, render_view)

    ###################################
    # Put the camera where we want it #
    ###################################

    # This happens after all calls to Show, as Show may do some automatic camera re-setting
    render_view.InteractionMode = '2D'
    render_view.CameraPosition = [0.5, 0.5, 1.0]
    render_view.CameraFocalPoint = [0.5, 0.5, 0.0]

    # This parameter sets the 'zoom' and needs fine-tuning by the aspect ratio
    render_view.CameraParallelScale = 0.5 * 9.0 / 16.0

    ##################################
    # Set up and write the animation #
    ##################################

    # Get an animation scene, which has parameters we need to change before output
    animation_scene = pv.GetAnimationScene()

    # Get a list of time step values from the pvd file.  Typically this will look like [t_0, t1, t2, ..., t_end]
    time_step_info = results_pvd.TimestepValues
    num_time_steps = len(time_step_info)

    # Set the animation parameters
    animation_scene.NumberOfFrames = num_time_steps  # If num frames != num time steps, some interpolation will be used
    animation_scene.StartTime = time_step_info[
        0]  # Usually t_0, the first entry in time_step_info
    animation_scene.EndTime = time_step_info[
        -1]  # Usually t_end, the final entry in time_step_info

    # Write the animation as a series of uncompressed png files, with no magnification
    pv.WriteAnimation(sim_dir + 'results_' + representation + '.png',
                      Magnification=1,
                      Compression=False)

    # Raise exception if the png files are not generated as expected
    if not (os.path.isfile(sim_dir + 'results_' + representation +
                           '.0000.png')):
        raise Exception('pvd_to_mp4: png sequence not exported as expected')

    #######################################
    # Convert from png to mp4 and tidy up #
    #######################################

    # Ubuntu 14.04 (trusty) came bundled with avconv instead of ffmpeg, but they're nearly the same software
    # so we don't have to change the command other than the name of the video converter to use
    if platform.linux_distribution()[2] == 'trusty':
        video_converter = 'avconv'
    else:
        video_converter = 'ffmpeg'

    # Set how long you want the video to be (in seconds), and set the frame rate accordingly
    video_duration = 15.0
    frame_rate = str(num_time_steps / video_duration)

    # Send the system command to run avconv/ffmpeg. Parameters:
    #   -v 0                        Suppress console output so as not to clutter the terminal
    #   -r frame_rate               Set the frame rate calculated above
    #   -f image2                   Set the convert format (image sequence to video)
    #   -i dir/results.%04d.png     Input expected as dir/results.####.png, the output from WriteAnimation above
    #   -c:v h264                   Video codec to use is h264
    #   -crf 0                      Set video quality: 0 best, 51 worst (https://trac.ffmpeg.org/wiki/Encode/H.264)
    #   -y dir/movie.mp4            Output directory and name
    os.system(video_converter + ' -v 0 -r ' + frame_rate + ' -f image2 -i ' +
              sim_dir + 'results_' + representation +
              '.%04d.png -c:v h264 -crf 0 -y ' + full_movie_path)

    # Raise exception if the mp4 file is not generated as expected
    if not (os.path.isfile(full_movie_path)):
        raise Exception('pvd_to_mp4: mp4 not generated as expected')

    # Raise exception if the mp4 file file is created but is smaller than 1kb - ffmpeg sometimes
    # generates an empty file even if an error occurs
    if os.path.getsize(full_movie_path) < 1024:
        raise Exception('pvd_to_mp4: mp4 not generated as expected')

    # Clean up the png files created by WriteAnimation
    os.system('rm ' + sim_dir + '*.png')
Esempio n. 15
0
# import the simple module from the paraview
import paraview.simple as pv
# disable automatic camera reset on 'Show'
pv._DisableFirstRenderCameraReset()

# create a new 'VisItNek5000Reader'
ablnek5000 = pv.VisItNek5000Reader(
    # FileName='/run/media/avmo/seagate/runs/abl_irrot_15x24x10_V1pix1.x1.571_2020-02-05_12-02-28/abl.nek5000'
    FileName=
    '/home/avmo/src/exabl/data/abl_irrot_15x24x10_V1pix1.x1.571_2020-02-05_12-02-28/abl.nek5000'
)
ablnek5000.Meshes = ['mesh']
ablnek5000.PointArrays = []

# get animation scene
animationScene1 = pv.GetAnimationScene()

# get the time-keeper
timeKeeper1 = pv.GetTimeKeeper()

# update animation scene based on data timesteps
animationScene1.UpdateAnimationUsingDataTimeSteps()

# Properties modified on ablnek5000
ablnek5000.PointArrays = [
    'pressure', 'velocity_mag', 'x_velocity', 'y_velocity', 'z_velocity'
]

# get active view
renderView1 = pv.GetActiveViewOrCreate('RenderView')
# uncomment following to set a specific view size
Esempio n. 16
0
    def __init__(self, filepath='.'):
        self.filepath = filepath
        self.time = 0.0
        self.surfaceColorMode = 0  # Local range
        self.subSurfaceColorMode = 0  # Local range

        # Surface View
        self.viewSurface = simple.CreateRenderView(True)
        self.viewSurface.EnableRenderOnInteraction = 0
        self.viewSurface.OrientationAxesVisibility = 0
        self.viewSurface.Background = [0.9, 0.9, 0.9]
        self.viewSurface.InteractionMode = '2D'
        self.viewSurface.CameraParallelProjection = 1

        # SubSurface view
        self.viewSubSurface = simple.CreateRenderView(True)
        self.viewSubSurface.EnableRenderOnInteraction = 0
        self.viewSubSurface.OrientationAxesVisibility = 0
        self.viewSubSurface.Background = [0.9, 0.9, 0.9]
        self.viewSubSurface.InteractionMode = '2D'
        self.viewSubSurface.CameraParallelProjection = 1

        # Read dataset
        self.reader = simple.ParFlowReader(FileName=filepath, DeflectTerrain=1)
        self.readerSurface = simple.OutputPort(self.reader, 1)
        self.readerSubSurface = simple.OutputPort(self.reader, 0)

        # Water table depth
        self.waterTableDepth = simple.WaterTableDepth(
            Subsurface=self.readerSubSurface, Surface=self.readerSurface)
        self.cellCenter = simple.CellCenters(Input=self.waterTableDepth)
        self.wtdVectCalc = simple.Calculator(Input=self.cellCenter)
        self.wtdVectCalc.ResultArrayName = 'wtdVect'
        self.wtdVectCalc.Function = 'iHat + jHat + kHat * water table depth'

        self.waterTableDepthGlyph = simple.Glyph(
            Input=self.wtdVectCalc,
            GlyphType='Cylinder',
            ScaleFactor=500,
            GlyphMode='All Points',
            GlyphTransform='Transform2',
            ScaleArray=['POINTS', 'wtdVect'],
            VectorScaleMode='Scale by Components',
        )
        self.waterTableDepthGlyph.GlyphTransform.Rotate = [90.0, 0.0, 0.0]
        self.waterTableDepthGlyph.GlyphType.Resolution = 12
        self.waterTableDepthGlyph.GlyphType.Radius = 0.25
        self.waterTableRepresentation = simple.Show(self.waterTableDepthGlyph,
                                                    self.viewSubSurface)
        self.waterTableRepresentation.Visibility = 0

        # Water balance
        self.waterBalance = simple.WaterBalance(
            Subsurface=self.readerSubSurface, Surface=self.readerSurface)
        self.waterBalanceOverTime = simple.PlotGlobalVariablesOverTime(
            Input=self.waterBalance)

        # Surface representation
        self.surfaceRepresentation = simple.Show(self.readerSurface,
                                                 self.viewSurface)
        self.surfaceRepresentation.SetScalarBarVisibility(
            self.viewSurface, True)

        # SubSurface representation + slice extract
        self.reader.UpdatePipeline()
        self.voi = self.reader.GetClientSideObject().GetOutputDataObject(
            0).GetExtent()
        self.extractSubset = simple.ExtractSubset(Input=self.readerSubSurface)
        self.subSurfaceRepresentation = simple.Show(self.extractSubset,
                                                    self.viewSubSurface)
        self.subSurfaceRepresentation.Representation = 'Surface'

        # Reset camera + center of rotation
        simple.Render(self.viewSurface)
        simple.ResetCamera(self.viewSurface)
        self.viewSurface.CenterOfRotation = self.viewSurface.CameraFocalPoint
        simple.Render(self.viewSubSurface)
        simple.ResetCamera(self.viewSubSurface)
        self.viewSubSurface.CenterOfRotation = self.viewSubSurface.CameraFocalPoint

        # Time management
        self.animationScene = simple.GetAnimationScene()
        self.animationScene.UpdateAnimationUsingDataTimeSteps()