def RequestData(self, request, inInfo, outInfo):
        logger.info("Loading waveform data...")
        start_time = time.time()

        output = dsa.WrapDataObject(vtkTable.GetData(outInfo))

        if (self._filename is not None and self._subfile is not None
                and len(self.mode_names) > 0):
            with h5py.File(self._filename, "r") as f:
                strain = f[self._subfile]
                t = strain["Y_l2_m2.dat"][:, 0]
                col_time = vtknp.numpy_to_vtk(t, deep=False)
                col_time.SetName("Time")
                output.AddColumn(col_time)

                for mode_name in self.mode_names:
                    logger.debug(f"Reading mode '{mode_name}'...")
                    col_mode = vtknp.numpy_to_vtk(strain[mode_name +
                                                         ".dat"][:, 1:],
                                                  deep=False)
                    col_mode.SetName(mode_name)
                    output.AddColumn(col_mode)

        logger.info(
            f"Waveform data loaded in {time.time() - start_time:.3f}s.")

        return 1
Exemple #2
0
def coprocess(time, timeStep, grid, attributes):
    global coProcessor
    import vtk
    from paraview.vtk import vtkPVCatalyst as catalyst
    import paraview
    from paraview.vtk.util import numpy_support
    dataDescription = catalyst.vtkCPDataDescription()
    dataDescription.SetTimeData(time, timeStep)
    dataDescription.AddInput("input")

    if coProcessor.RequestDataDescription(dataDescription):
        import fedatastructures
        imageData = vtk.vtkImageData()
        imageData.SetExtent(grid.XStartPoint, grid.XEndPoint, 0, grid.NumberOfYPoints-1, 0, grid.NumberOfZPoints-1)
        imageData.SetSpacing(grid.Spacing)

        velocity = numpy_support.numpy_to_vtk(attributes.Velocity)
        velocity.SetName("velocity")
        imageData.GetPointData().AddArray(velocity)

        pressure = numpy_support.numpy_to_vtk(attributes.Pressure)
        pressure.SetName("pressure")
        imageData.GetCellData().AddArray(pressure)
        dataDescription.GetInputDescriptionByName("input").SetGrid(imageData)
        dataDescription.GetInputDescriptionByName("input").SetWholeExtent(0, grid.NumberOfGlobalXPoints-1, 0, grid.NumberOfYPoints-1, 0, grid.NumberOfZPoints-1)
        coProcessor.CoProcess(dataDescription)
    def RequestData(self, request, inInfo, outInfo):
        logger.debug("Requesting data...")
        input = self.GetInputDataObject(0, 0)
        trajectory_data = dsa.WrapDataObject(input)
        output = dsa.WrapDataObject(vtkPolyData.GetData(outInfo))

        # Retrieve current time
        time = timesteps_util.get_timestep(self, logger=logger)

        # Retrieve trajectory data
        trajectory_times = trajectory_data.PointData["Time"]
        trajectory_points = trajectory_data.Points

        # Interpolate along the trajectory to find current position
        current_position = [
            np.interp(time, trajectory_times, trajectory_points[:, i])
            for i in range(3)
        ]

        # Expose to VTK
        points_vtk = vtk.vtkPoints()
        verts_vtk = vtk.vtkCellArray()
        verts_vtk.InsertNextCell(1)
        points_vtk.InsertPoint(0, *current_position)
        verts_vtk.InsertCellPoint(0)
        output.SetPoints(points_vtk)
        output.SetVerts(verts_vtk)

        # Interpolate remaining point data along the trajectory
        for dataset in trajectory_data.PointData.keys():
            if dataset == "Time":
                continue
            point_data = trajectory_data.PointData[dataset]
            data_at_position = np.zeros(point_data.shape[1:])
            if len(data_at_position.shape) > 0:
                for i in itertools.product(
                        *map(range, data_at_position.shape)):
                    point_data_i = point_data[(slice(None), ) + i]
                    if len(trajectory_times) == len(point_data_i):
                        data_at_position[i] = np.interp(
                            time, trajectory_times, point_data_i)
                    else:
                        logger.warning(
                            "Unable to interpolate trajectory dataset"
                            f" {dataset}[{i}]: Length of dataset"
                            f" ({len(point_data_i)}) does not match length of"
                            f" trajectory times ({len(trajectory_times)}).")
            else:
                data_at_position = np.interp(time, trajectory_times,
                                             point_data)
            data_vtk = vtknp.numpy_to_vtk(np.array([data_at_position]))
            data_vtk.SetName(dataset)
            output.GetPointData().AddArray(data_vtk)
        return 1
Exemple #4
0
    def RequestData(self, request, inInfo, outInfo):
        logger.debug("Requesting data...")
        output = dsa.WrapDataObject(vtkPolyData.GetData(outInfo))

        with h5py.File(self._filename, "r") as trajectory_file:
            subfile = trajectory_file[self._subfile]
            coords = np.array(subfile[self._coords_dataset])
        coords[:, 1:] *= self._radial_scale
        logger.debug(f"Loaded coordinates with shape {coords.shape}.")

        # Construct a line of points
        points_vtk = vtk.vtkPoints()
        # Each ID is composed of (1) the order of the point in the line and (2)
        # the index in the `vtkPoints` constructed above
        line_vtk = vtk.vtkPolyLine()
        point_ids = line_vtk.GetPointIds()
        point_ids.SetNumberOfIds(len(coords))
        for i, point in enumerate(coords):
            points_vtk.InsertPoint(i, *point[1:])
            point_ids.SetId(i, i)
        output.SetPoints(points_vtk)
        # Set the line ordering as "cell data"
        output.Allocate(1, 1)
        output.InsertNextCell(line_vtk.GetCellType(), line_vtk.GetPointIds())

        # Add time data to the points
        time = vtknp.numpy_to_vtk(coords[:, 0])
        time.SetName("Time")
        output.GetPointData().AddArray(time)

        # Add remaining datasets from file to trajectory points
        with h5py.File(self._filename, "r") as trajectory_file:
            subfile = trajectory_file[self._subfile]
            for dataset in subfile:
                if dataset == self._coords_dataset:
                    continue
                dataset_vtk = vtknp.numpy_to_vtk(subfile[dataset][:, 1:])
                dataset_vtk.SetName(dataset.replace(".dat", ""))
                output.GetPointData().AddArray(dataset_vtk)
        return 1
Exemple #5
0
    def RequestData(self, request, in_info_vec, out_info_vec):
        if self._basis_functions is None:
            self._load_basis_functions()
        if self._mu is None:
            self._init_mu()

        if self._action == "View basis functions":
            # Get basis function number from time step
            out_info = out_info_vec.GetInformationObject(0)
            selection = self.GetExecutive().UPDATE_TIME_STEP()
            if out_info.Has(selection):
                basis_function_number = int(round(out_info.Get(selection)))
            else:
                basis_function_number = 0

            # Copy corresponding basis function to output
            output = vtkUnstructuredGrid.GetData(out_info_vec)
            output.ShallowCopy(self._basis_functions[basis_function_number])
        elif self._action == "Run non-intrusive ROM":
            if self._networks is None:
                self._load_networks()

            # Compute reduced solution with pytorch
            mu_torch = self._normalize_inputs(tuple(self._mu))
            reduced_solution = dict()
            for c in self._components:
                network_c = self._networks[c][self._N - 1]
                normalize_outputs_c = self._normalize_outputs[c][self._N - 1]
                reduced_solution[c] = normalize_outputs_c.inv(network_c(mu_torch).detach().numpy()[0])

            # Copy mesh to output
            output = vtkUnstructuredGrid.GetData(out_info_vec)
            output.DeepCopy(self._basis_functions[0])
            for (c, _) in enumerate(self._components):
                output.GetPointData().RemoveArray(c)

            # Combine basis functions with coefficients provided by network
            for c in self._components:
                array_c_np = np.dot(self._arrays[c][..., :self._N], reduced_solution[c])
                array_c_vtk = numpy_to_vtk(array_c_np, deep=1)
                array_c_vtk.SetName(c)
                output.GetPointData().AddArray(array_c_vtk)
        else:
            raise RuntimeError("Invalid action")

        return 1
Exemple #6
0
    def RequestData(self, request, inInfo, outInfo):
        logger.debug("Requesting data...")
        input = self.GetInputDataObject(0, 0)
        trajectory_data = dsa.WrapDataObject(input)
        output = dsa.WrapDataObject(vtkPolyData.GetData(outInfo))

        # Shallow-copy input trajectory data to output
        output.ShallowCopy(input)

        # Retrieve current time
        time = timesteps_util.get_timestep(self, logger=logger)

        # Add age data to the points
        age = time - trajectory_data.PointData["Time"]
        age_vtk = vtknp.numpy_to_vtk(age, deep=True)
        age_vtk.SetName("Age")
        output.GetPointData().AddArray(age_vtk)

        return 1
Exemple #7
0
def numpy_to_image(numpy_array):
  """Convert a numpy 2D or 3D array to a vtkImageData object.

  numpy_array
    2D or 3D numpy array containing image data

  return
    vtkImageData with the numpy_array content
  """
  try:
    import numpy
  except:
    paraview.print_error("Error: Cannot import numpy")

  shape = numpy_array.shape
  if len(shape) < 2:
    raise Exception('numpy array must have dimensionality of at least 2')

  h, w = shape[0], shape[1]
  c = 1
  if len(shape) == 3:
    c = shape[2]

  # Reshape 2D image to 1D array suitable for conversion to a
  # vtkArray with numpy_support.numpy_to_vtk()
  linear_array = numpy.reshape(numpy_array, (w*h, c))

  try:
    from paraview.vtk.util import numpy_support
  except:
    paraview.print_error("Error: Cannot import vtk.util.numpy_support")

  vtk_array = numpy_support.numpy_to_vtk(linear_array)

  image = vtk.vtkImageData()
  image.SetDimensions(w, h, 1)
  image.AllocateScalars(vtk_array.GetDataType(), 4)
  image.GetPointData().GetScalars().DeepCopy(vtk_array)

  return image
Exemple #8
0
    def RequestData(self, request, inInfo, outInfo):
        logger.debug("Requesting data...")
        info = outInfo.GetInformationObject(0)
        logger.debug(f"Information object: {info}")
        update_extents = info.Get(self.GetExecutive().UPDATE_EXTENT())
        logger.debug(
            f"Responsible for updating these extents: {update_extents}")

        output = dsa.WrapDataObject(vtkDataSet.GetData(outInfo))

        logger.info("Computing SWSH grid...")
        start_time = time.time()

        # Setup grid
        # TODO: Take the `update_extents` into account to support rendering
        # in parallel
        N = self.num_points_per_dim
        N_y = N // 2 if self.clip_y_normal else N
        size = self.size
        spacing = 2.0 * size / N
        output.SetDimensions(N, N_y, N)
        output.SetOrigin(*(3 * (-size, )))
        output.SetSpacing(*(3 * (spacing, )))

        # Compute the SWSHs on the grid
        swsh_grid, r = swsh_cache.cached_swsh_grid(
            size=size,
            num_points=N,
            spin_weight=self.spin_weight,
            ell_max=self.ell_max,
            clip_y_normal=self.clip_y_normal,
            clip_z_normal=False,
            cache_dir=self.swsh_cache_dir,
        )

        # Expose radial coordinate to VTK
        r_vtk = vtknp.numpy_to_vtk(r, deep=False)
        r_vtk.SetName("RadialCoordinate")
        output.GetPointData().AddArray(r_vtk)

        for l in range(abs(self.spin_weight), self.ell_max + 1):
            for m in range(1, l + 1):
                mode_profile = (swsh_grid[:, LM_index(l, m, 0)] +
                                swsh_grid[:, LM_index(l, -m, 0)])
                mode_name = "Y_l{}_m{}".format(l, m)
                # Expose complex field to VTK as two arrays of floats
                mode_real_vtk = vtknp.numpy_to_vtk(np.real(mode_profile),
                                                   deep=True)
                mode_imag_vtk = vtknp.numpy_to_vtk(np.imag(mode_profile),
                                                   deep=True)
                mode_abs_vtk = vtknp.numpy_to_vtk(np.abs(mode_profile),
                                                  deep=True)
                mode_real_vtk.SetName(mode_name + " Real")
                mode_imag_vtk.SetName(mode_name + " Imag")
                mode_abs_vtk.SetName(mode_name + " Abs")
                output.GetPointData().AddArray(mode_real_vtk)
                output.GetPointData().AddArray(mode_imag_vtk)
                output.GetPointData().AddArray(mode_abs_vtk)

        logger.info(f"SWSH grid computed in {time.time() - start_time:.3f}s.")
        return 1
Exemple #9
0
def execute(inputDO, selectionNode, insidednessArrayName, outputDO):
    field_type = selectionNode.GetFieldType()
    if field_type == selectionNode.CELL:
        attributeType = vtkDataObject.CELL
    elif field_type == selectionNode.POINT:
        attributeType = vtkDataObject.POINT
    elif field_type == selectionNode.ROW:
        attributeType = vtkDataObject.ROW
    else:
        raise RuntimeError ("Unsupported field attributeType %r" % field_type)
    # Evaluate expression on the inputDO.
    # This is equivalent to executing the Python Calculator on the input dataset
    # to produce a mask array.

    inputs = []
    inputs.append(dsa.WrapDataObject(inputDO))

    query = selectionNode.GetQueryString()

    # Get a dictionary for arrays in the dataset attributes. We pass that
    # as the variables in the eval namespace for calculator.compute().
    elocals = calculator.get_arrays(inputs[0].GetAttributes(attributeType))
    if ("id" not in elocals) and re.search(r'\bid\b', query):
        # Add "id" array if the query string refers to id.
        # This is a temporary fix. We should look into
        # accelerating id-based selections in the future.
        elocals["id"] = _create_id_array(inputs[0], attributeType)
    try:
        maskArray = calculator.compute(inputs, query, ns=elocals)
    except:
        from sys import stderr
        print ("Error: Failed to evaluate Expression '%s'. "\
            "The following exception stack should provide additional developer "\
            "specific information. This typically implies a malformed "\
            "expression. Verify that the expression is valid.\n" % query, file=stderr)
        raise

    if not maskarray_is_valid(maskArray):
        raise RuntimeError(
            "Expression '%s' did not produce a valid mask array. The value "\
            "produced is of the type '%s'. This typically implies a malformed "\
            "expression. Verify that the expression is valid." % \
            (query, type(maskArray)))

    # Preserve topology. Just add the mask array as vtkSignedCharArray to the
    # output.
    # Note: we must force the data type to VTK_SIGNED_CHAR or the array will
    # be ignored by the freeze selection operation
    from paraview.vtk.util import numpy_support
    output = dsa.WrapDataObject(outputDO)
    if type(maskArray) is not dsa.VTKNoneArray:
        if isinstance(maskArray, dsa.VTKCompositeDataArray):
            for ds, array in izip(output, maskArray.Arrays):
                if array is not None:
                    insidedness = numpy_support.numpy_to_vtk(array, deep=1, array_type=vtkConstants.VTK_SIGNED_CHAR)
                    insidedness.SetName(insidednessArrayName)
                    ds.GetAttributes(attributeType).VTKObject.AddArray(insidedness)
        else:
            insidedness = numpy_support.numpy_to_vtk(maskArray, deep=1, array_type=vtkConstants.VTK_SIGNED_CHAR)
            insidedness.SetName(insidednessArrayName)
            output.GetAttributes(attributeType).VTKObject.AddArray(insidedness)
Exemple #10
0
def execute(inputDO, selectionNode, insidednessArrayName, outputDO):
    field_type = selectionNode.GetFieldType()
    if field_type == selectionNode.CELL:
        attributeType = vtkDataObject.CELL
    elif field_type == selectionNode.POINT:
        attributeType = vtkDataObject.POINT
    elif field_type == selectionNode.ROW:
        attributeType = vtkDataObject.ROW
    else:
        raise RuntimeError ("Unsupported field attributeType %r" % field_type)
    # Evaluate expression on the inputDO.
    # This is equivalent to executing the Python Calculator on the input dataset
    # to produce a mask array.

    inputs = []
    inputs.append(dsa.WrapDataObject(inputDO))

    query = selectionNode.GetQueryString()

    # Get a dictionary for arrays in the dataset attributes. We pass that
    # as the variables in the eval namespace for calculator.compute().
    elocals = calculator.get_arrays(inputs[0].GetAttributes(attributeType))
    if ("id" not in elocals) and re.search(r'\bid\b', query):
        # Add "id" array if the query string refers to id.
        # This is a temporary fix. We should look into
        # accelerating id-based selections in the future.
        elocals["id"] = _create_id_array(inputs[0], attributeType)
    try:
        maskArray = calculator.compute(inputs, query, ns=elocals)
    except:
        from sys import stderr
        print ("Error: Failed to evaluate Expression '%s'. "\
            "The following exception stack should provide additional developer "\
            "specific information. This typically implies a malformed "\
            "expression. Verify that the expression is valid.\n" % query, file=stderr)
        raise

    if not maskarray_is_valid(maskArray):
        raise RuntimeError(
            "Expression '%s' did not produce a valid mask array. The value "\
            "produced is of the type '%s'. This typically implies a malformed "\
            "expression. Verify that the expression is valid." % \
            (query, type(maskArray)))

    # Preserve topology. Just add the mask array as vtkSignedCharArray to the
    # output.
    # Note: we must force the data type to VTK_SIGNED_CHAR or the array will
    # be ignored by the freeze selection operation
    from paraview.vtk.util import numpy_support
    output = dsa.WrapDataObject(outputDO)
    if maskArray is not dsa.NoneArray:
        if isinstance(maskArray, dsa.VTKCompositeDataArray):
            for ds, array in izip(output, maskArray.Arrays):
                if array is not dsa.NoneArray:
                    insidedness = numpy_support.numpy_to_vtk(array, deep=1, array_type=vtkConstants.VTK_SIGNED_CHAR)
                    insidedness.SetName(insidednessArrayName)
                    ds.GetAttributes(attributeType).VTKObject.AddArray(insidedness)
        else:
            insidedness = numpy_support.numpy_to_vtk(maskArray, deep=1, array_type=vtkConstants.VTK_SIGNED_CHAR)
            insidedness.SetName(insidednessArrayName)
            output.GetAttributes(attributeType).VTKObject.AddArray(insidedness)