def plot_surface(axis: pyplot.Axes.axes,
                 _fun: Callable[[float, float], float],
                 dim_range: Tuple[float, float],
                 colormap=None):
    _x = numpy.linspace(dim_range[0],
                        dim_range[1],
                        endpoint=True,
                        num=int(dim_range[1] - dim_range[0]))
    _y = numpy.linspace(dim_range[0],
                        dim_range[1],
                        endpoint=True,
                        num=int(dim_range[1] - dim_range[0]))
    _z = tuple(_fun(__x, __y) for __x, __y in zip(_x, _y))

    _X, _Y = numpy.meshgrid(_x, _y)
    _Z = _fun(_X, _Y)

    z_min, z_max = get_min_max(_z)
    z_margin = (z_max - z_min) * .1
    min_margin = z_min - z_margin
    max_margin = z_max + z_margin

    try:
        axis.set_zlim((min_margin, max_margin))
    except ValueError:
        print("infinite axis value")

    if colormap is None:
        return axis.plot_surface(_X, _Y, _Z, alpha=.2, antialiased=False)
    return axis.plot_surface(_X,
                             _Y,
                             _Z,
                             alpha=.2,
                             antialiased=False,
                             cmap=colormap)
Example #2
0
def plot_surface(ax: pyplot.Axes.axes, a: float, b: float, c: float,
                 size: int):
    x = numpy.linspace(0, size, endpoint=False, num=size)
    y = numpy.linspace(0, size, endpoint=False, num=size)

    _X, _Y = numpy.meshgrid(x, y)
    _Z = a + b * _Y + c * _X

    ax.plot_surface(_X, _Y, _Z, alpha=.2, antialiased=False)
Example #3
0
    def _plot_h_stacked_bars(axis: pyplot.Axes.axes, segments: Sequence[Sequence[Tuple[Any, float]]]):
        for _i, each_level in enumerate(segments):
            for _x in range(len(each_level) - 1):
                each_left, each_shape = each_level[_x]
                each_right, _ = each_level[_x + 1]
                each_width = each_right - each_left
                hsv = distribute_circular(each_shape), .2, 1.
                axis.barh(_i, each_width, height=1., align="edge", left=each_left, color=hsv_to_rgb(hsv))

                if Timer.time_passed(2000):
                    print("Finished {:5.2f}% of plotting level {:d}/{:d}...".format(100. * _x / (len(each_level) - 1), _i, len(segments)))
Example #4
0
 def _plot_values(self, axis: pyplot.Axes.axes, input_values: Sequence[float]):
     for _j in range(self.output_dimension):
         axis.plot(self.time_axis, self.targets[_j], label="target {:d}".format(_j))
     for _i, method_name in enumerate(self.method_names):
         each_outputs = self.outputs[method_name]
         for _j in range(self.output_dimension):
             axis.plot(self.time_axis, each_outputs[_j], label="output {:d} {:s}".format(_j, method_name), alpha=.5)
     if len(input_values) >= 1:
         assert len(input_values) == len(self.time_axis)
         axis.plot(self.time_axis, input_values, label="inputs")
     axis.set_ylabel("values")
     axis.legend()
Example #5
0
def plot_coordinate_systems(
    cs_data: Tuple[str, Dict],
    axes: plt.Axes.axes = None,
    title: str = None,
    limits: Union[List[Tuple[float, float]], Tuple[float, float]] = None,
    time_index: int = None,
    legend_pos: str = "lower left",
) -> plt.Axes.axes:
    """Plot multiple coordinate systems.

    Parameters
    ----------
    cs_data : Tuple[str, Dict]
        A tuple containing the coordinate system that should be plotted and a dictionary
        with the key word arguments that should be passed to its plot function.
    axes : matplotlib.axes.Axes
        The target axes object that should be drawn to. If `None` is provided, a new
        one will be created.
    title : str
        The title of the plot
    limits :  Tuple[float, float] or List[Tuple[float, float]]
        Each tuple marks lower and upper boundary of the x, y and z axis. If only a
        single tuple is passed, the boundaries are used for all axis. If `None`
        is provided, the axis are adjusted to be of equal length.
    time_index : int
        Index of a specific time step that should be plotted if the corresponding
        coordinate system is time dependent
    legend_pos : str
        A string that specifies the position of the legend. See the matplotlib
        documentation for further details

    Returns
    -------
    matplotlib.axes.Axes :
        The axes object that was used as canvas for the plot

    """
    if axes is None:
        _, axes = new_3d_figure_and_axes()

    for lcs, kwargs in cs_data:
        if "time_index" not in kwargs:
            kwargs["time_index"] = time_index
        lcs.plot(axes, **kwargs)

    _set_limits_matplotlib(axes, limits)

    if title is not None:
        axes.set_title(title)
    axes.legend(loc=legend_pos)

    return axes
def plot_line(axis: pyplot.Axes.axes,
              _coefficients: Sequence[float],
              dim_range: Tuple[float, float],
              color: Optional[str] = None):
    _X = numpy.linspace(dim_range[0],
                        dim_range[1],
                        endpoint=True,
                        num=int(dim_range[1] - dim_range[0]))
    _Z = tuple(
        sum(_c * _x**_i for _i, _c in enumerate(_coefficients)) for _x in _X)

    if color is None:
        axis.plot(_X, _Z)
    else:
        axis.plot(_X, _Z, color=color)
Example #7
0
def plot_4d(axis: pyplot.Axes.axes, _fun: Callable[[float, float, float],
                                                   float],
            dim_ranges: Tuple[Tuple[float, float], ...]):
    resolution = 10
    _X, _Y, _Z = tuple(
        numpy.linspace(*_range, endpoint=True, num=resolution)
        for _range in dim_ranges)

    _X = []
    _Y = []
    _Z = []
    _V = []

    cm = pyplot.cm.get_cmap("rainbow")

    for _x in numpy.linspace(*dim_ranges[0], num=resolution, endpoint=True):
        for _y in numpy.linspace(*dim_ranges[1], num=resolution,
                                 endpoint=True):
            for _z in numpy.linspace(*dim_ranges[2],
                                     num=resolution,
                                     endpoint=True):
                _X.append(_x)
                _Y.append(_y)
                _Z.append(_z)
                _v = _fun(_x, _y, _z)
                _V.append(_v)
    print(f"evaluation range: {min(_V):.2f}, {max(_V):.2f}")
    return axis.scatter(_X, _Y, _Z, c=_V, cmap=cm, alpha=.2)
Example #8
0
    def make_panel(self, axes: plt.Axes.axes) -> plt.pcolormesh:
        """
        Returns the
        :param projection:
        :return:
        """
        radial_dist = self.cluster.radial_distance_CoP(self.cluster.partType0_coordinates)
        spatial_filter = np.where(radial_dist < self.aperture)[0]

        mass        = self.cluster.mass_units(self.cluster.partType0_mass[spatial_filter], unit_system='astro')
        density     = self.cluster.density_units(self.cluster.partType0_sphdensity[spatial_filter], unit_system='nHcgs')
        temperature = self.cluster.partType0_temperature[spatial_filter]

        x_bins = np.logspace(np.log10(self.density_bounds[0]), np.log10(self.density_bounds[1]), self.resolution)
        y_bins = np.logspace(np.log10(self.temperature_bounds[0]), np.log10(self.temperature_bounds[1]), self.resolution)
        A_pix = (x_bins[1] - x_bins[0]) * (y_bins[1] - y_bins[0])
        Cx, Cy = self.bins_meshify(density, temperature, x_bins, y_bins)
        count = self.bins_evaluate(density, temperature, x_bins, y_bins, weights=mass) #/ A_pix

        # Logarithmic normalization
        norm = colors.LogNorm()  # (vmin=10 ** -2, vmax=10 ** 1)

        count2 = np.ma.masked_where(count == 0, count)
        cmap = plt.get_cmap('CMRmap')
        cmap.set_bad(color='grey', alpha=1)

        image = axes.pcolormesh(Cx, Cy, count2, cmap=cmap, norm=norm)

        return image
Example #9
0
    def make_cluster_label(self, axes: plt.Axes.axes):
        items_labels = r"""THERMODYNAMIC PHASE SPACE
                        Cluster {:s}\ {:d}
                        $z$ = {:.3f}
                        $R_{{500\ true}}$ = {:.2f} Mpc
                        Aperture radius = {:.2f} Mpc""".format(self.cluster.simulation,
                                                              self.cluster.clusterID,
                                                              self.cluster.z,
                                                              self.cluster.r500,
                                                              self.aperture)

        print(items_labels)
        axes.text(0.03, 0.97, items_labels,
                  horizontalalignment='left',
                  verticalalignment='top',
                  transform=axes.transAxes,
                  size = 15)
Example #10
0
    def make_cluster_label(self, axes: plt.Axes.axes):
        items_labels = r"""rkSZ PROJECTION MAP
                        Cluster {:s}\ {:d}
                        $z$ = {:.3f}
                        $R_{{500\ true}}$ = {:.2f} Mpc
                        Aperture radius = {:.2f} Mpc
                        Map resolution = {:.4f} kpc""".format(
            cluster.simulation, cluster.clusterID, cluster.z, cluster.r500,
            self.aperture, 2 * self.plotlimits / self.resolution * 1e3)

        print(items_labels)
        axes.text(0.03,
                  0.97,
                  items_labels,
                  horizontalalignment='left',
                  verticalalignment='top',
                  transform=axes.transAxes,
                  size=20)
Example #11
0
def plot_surface(axis: pyplot.Axes.axes,
                 _fun: Callable[[float, float], float],
                 dim_ranges: Tuple[Tuple[float, float], Tuple[float, float]],
                 colormap=None,
                 resize: bool = False):
    _x = numpy.linspace(dim_ranges[0][0],
                        dim_ranges[0][1],
                        endpoint=True,
                        num=100)
    _y = numpy.linspace(dim_ranges[1][0],
                        dim_ranges[1][1],
                        endpoint=True,
                        num=100)

    _X, _Y = numpy.meshgrid(_x, _y)

    _z = numpy.array(
        tuple(
            _fun(__x, __y)
            for __x, __y in zip(numpy.ravel(_X), numpy.ravel(_Y))))

    _Z = _z.reshape(_X.shape)

    if resize:
        z_min, z_max = get_min_max(_z)
        z_margin = (z_max - z_min) * .1
        min_margin = z_min - z_margin
        max_margin = z_max + z_margin

        try:
            axis.set_zlim((min_margin, max_margin))
        except ValueError:
            print("infinite axis value")

    if colormap is None:
        return axis.plot_surface(_X, _Y, _Z, alpha=.2, antialiased=False)
    return axis.plot_surface(_X,
                             _Y,
                             _Z,
                             alpha=.2,
                             antialiased=False,
                             cmap=colormap)
Example #12
0
def _set_limits_matplotlib(axes: plt.Axes.axes,
                           limits: Union[List[Tuple[float, float]],
                                         Tuple[float, float]]):
    """Set the limits of an axes object.

    Parameters
    ----------
    axes : matplotlib.axes.Axes
        The axes object
    limits :  Tuple[float, float] or List[Tuple[float, float]]
        Each tuple marks lower and upper boundary of the x, y and z axis. If only a
        single tuple is passed, the boundaries are used for all axis. If `None`
        is provided, the axis are adjusted to be of equal length.

    """
    if limits is None:
        set_axes_equal(axes)
    else:
        if isinstance(limits, Tuple):
            limits = [limits]
        if len(limits) == 1:
            limits = [limits[0] for _ in range(3)]
        axes.set_xlim(limits[0])
        axes.set_ylim(limits[1])
        axes.set_zlim(limits[2])
Example #13
0
 def _plot_errors(self, axis: pyplot.Axes.axes):
     for _i, method_name in enumerate(self.method_names):
         cumulative_error = []
         for each_error in self.errors[_i]:
             if len(cumulative_error) < 1:
                 cumulative_error.append(each_error ** 2.)
             else:
                 cumulative_error.append(each_error ** 2. + cumulative_error[-1])
         axis.plot(self.time_axis, cumulative_error, label=method_name, alpha=.5)
     axis.set_ylabel("cumulative squared error")
     axis.legend()
Example #14
0
    def make_panel(self, axes: plt.Axes.axes) -> plt.imshow:
        """
        Returns the
        :param projection:
        :return:
        """
        # Derotate cluster
        coords, vel = angular_momentum.derotate(self.cluster,
                                                align='gas',
                                                aperture_radius=self.aperture,
                                                cluster_rest_frame=True)

        # Filter particles
        spatial_filter = np.where(
            (np.abs(coords[:, 0]) < self.plotlimits)
            & (np.abs(coords[:, 1]) < self.plotlimits)
            & (self.cluster.partType0_temperature > 1e5))[0]

        coords = coords[spatial_filter, :]
        vel = vel[spatial_filter, :]
        mass = self.cluster.partType0_mass[spatial_filter]
        SPH_kernel = self.cluster.partType0_sphkernel[spatial_filter]

        constant_factor = (-1) * thompson_cross_section / (
            speed_of_light * hydrogen_mass / 1.16)
        kSZ = np.multiply((vel.T * mass).T, constant_factor)

        x = np.asarray(rescale(coords[:, 0], 0, 1), dtype=np.float64)
        y = np.asarray(rescale(coords[:, 1], 0, 1), dtype=np.float64)
        z = np.asarray(rescale(coords[:, 2], 0, 1), dtype=np.float64)
        m = np.asarray(kSZ[:, 2], dtype=np.float32)
        h = np.asarray(SPH_kernel, dtype=np.float32)

        # Generate the sph-smoothed map
        temp_map = swift.generate_map(x,
                                      y,
                                      m,
                                      h,
                                      self.resolution,
                                      parallel=True)
        norm = colors.SymLogNorm(linthresh=1e-5,
                                 linscale=0.5,
                                 vmin=-np.abs(temp_map).max(),
                                 vmax=np.abs(temp_map).max())

        # Attach the image to the Axes class
        image = axes.imshow(temp_map,
                            cmap='RdBu',
                            norm=norm,
                            origin='lower',
                            extent=(-self.plotlimits, self.plotlimits,
                                    -self.plotlimits, self.plotlimits))

        axes.axhline(y=0,
                     linewidth=1.,
                     color='black',
                     linestyle='-',
                     alpha=0.3)
        axes.axvline(x=0,
                     linewidth=1.,
                     color='black',
                     linestyle='-',
                     alpha=0.3)
        return image
Example #15
0
def plot_local_coordinate_system_matplotlib(
    lcs,
    axes: plt.Axes.axes = None,
    color: Any = None,
    label: str = None,
    time: Union[pd.DatetimeIndex, pd.TimedeltaIndex,
                List[pd.Timestamp]] = None,
    time_ref: pd.Timestamp = None,
    time_index: int = None,
    show_origin: bool = True,
    show_trace: bool = True,
    show_vectors: bool = True,
) -> plt.Axes.axes:
    """Visualize a `weldx.transformations.LocalCoordinateSystem` using matplotlib.

    Parameters
    ----------
    lcs : weldx.transformations.LocalCoordinateSystem
        The coordinate system that should be visualized
    axes : matplotlib.axes.Axes
        The target matplotlib axes. If `None` is provided, a new one will be created
    color : Any
        An arbitrary color. The data type must be compatible with matplotlib.
    label : str
        Name of the coordinate system
    time : pandas.DatetimeIndex, pandas.TimedeltaIndex, List[pandas.Timestamp], or \
           LocalCoordinateSystem
        The time steps that should be plotted
    time_ref : pandas.Timestamp
        A reference timestamp that can be provided if the ``time`` parameter is a
        `pandas.TimedeltaIndex`
    time_index : int
        Index of a specific time step that should be plotted
    show_origin : bool
        If `True`, the origin of the coordinate system will be highlighted in the
        color passed as another parameter
    show_trace :
        If `True`, the trace of a time dependent coordinate system will be visualized in
        the color passed as another parameter
    show_vectors : bool
        If `True`, the the coordinate axes of the coordinate system are visualized

    Returns
    -------
    matplotlib.axes.Axes :
        The axes object that was used as canvas for the plot

    """
    if axes is None:
        _, axes = plt.subplots(subplot_kw={
            "projection": "3d",
            "proj_type": "ortho"
        })

    if lcs.is_time_dependent and time is not None:
        lcs = lcs.interp_time(time, time_ref)

    if lcs.is_time_dependent and time_index is None:
        for i, _ in enumerate(lcs.time):
            draw_coordinate_system_matplotlib(
                lcs,
                axes,
                color=color,
                label=label,
                time_idx=i,
                show_origin=show_origin,
                show_vectors=show_vectors,
            )
            label = None
    else:
        draw_coordinate_system_matplotlib(
            lcs,
            axes,
            color=color,
            label=label,
            time_idx=time_index,
            show_origin=show_origin,
            show_vectors=show_vectors,
        )

    if show_trace and lcs.coordinates.values.ndim > 1:
        coords = lcs.coordinates.values
        if color is None:
            color = "k"
        axes.plot(coords[:, 0], coords[:, 1], coords[:, 2], ":", color=color)

    return axes
Example #16
0
def plot_coordinate_system_manager_matplotlib(
    csm,
    axes: plt.Axes.axes = None,
    reference_system: str = None,
    coordinate_systems: List[str] = None,
    data_sets: List[str] = None,
    colors: Dict[str, int] = None,
    time: Union[pd.DatetimeIndex, pd.TimedeltaIndex,
                List[pd.Timestamp]] = None,
    time_ref: pd.Timestamp = None,
    title: str = None,
    limits: Union[List[Tuple[float, float]], Tuple[float, float]] = None,
    show_origins: bool = True,
    show_trace: bool = True,
    show_vectors: bool = True,
) -> plt.Axes.axes:
    """Plot the coordinate systems of a `weldx.transformations.CoordinateSystemManager`.

    Parameters
    ----------
    csm : weldx.transformations.CoordinateSystemManager
        The `weldx.transformations.CoordinateSystemManager` that should be plotted
    axes : matplotlib.axes.Axes
        The target axes object that should be drawn to. If `None` is provided, a new
        one will be created.
    reference_system : str
        The name of the reference system for the plotted coordinate systems
    coordinate_systems : List[str]
        Names of the coordinate systems that should be drawn. If `None` is provided,
        all systems are plotted.
    data_sets : List[str]
        Names of the data sets that should be drawn. If `None` is provided, all data
        is plotted.
    colors: Dict[str, int]
        A mapping between a coordinate system name or a data set name and a color.
        The colors must be provided as 24 bit integer values that are divided into
        three 8 bit sections for the rgb values. For example `0xFF0000` for pure
        red.
        Each coordinate system or data set that does not have a mapping in this
        dictionary will get a default color assigned to it.
    time : pandas.DatetimeIndex, pandas.TimedeltaIndex, List[pandas.Timestamp], or \
           weldx.transformations.LocalCoordinateSystem
        The time steps that should be plotted
    time_ref : pandas.Timestamp
        A reference timestamp that can be provided if the ``time`` parameter is a
        `pandas.TimedeltaIndex`
    title : str
        The title of the plot
    limits :  Tuple[float, float] or List[Tuple[float, float]]
        Each tuple marks lower and upper boundary of the x, y and z axis. If only a
        single tuple is passed, the boundaries are used for all axis. If `None`
        is provided, the axis are adjusted to be of equal length.
    show_origins : bool
        If `True`, the origins of the coordinate system are visualized in the color
        assigned to the coordinate system.
    show_trace : bool
        If `True`, the trace of time dependent coordinate systems is plotted.
    show_vectors : bool
        If `True`, the coordinate cross of time dependent coordinate systems is plotted.

    Returns
    -------
    matplotlib.axes.Axes :
        The axes object that was used as canvas for the plot

    """
    if time is not None:
        return plot_coordinate_system_manager_matplotlib(
            csm.interp_time(time=time, time_ref=time_ref),
            axes=axes,
            reference_system=reference_system,
            coordinate_systems=coordinate_systems,
            title=title,
            show_origins=show_origins,
            show_trace=show_trace,
            show_vectors=show_vectors,
        )
    if axes is None:
        _, axes = new_3d_figure_and_axes()
        axes.set_xlabel("x")
        axes.set_ylabel("y")
        axes.set_zlabel("z")

    if reference_system is None:
        reference_system = csm.root_system_name
    if coordinate_systems is None:
        coordinate_systems = csm.coordinate_system_names
    if data_sets is None:
        data_sets = csm.data_names
    if title is not None:
        axes.set_title(title)

    # plot coordinate systems
    color_gen = _color_generator_function()
    for lcs_name in coordinate_systems:
        color = _color_int_to_rgb_normalized(
            _get_color(lcs_name, colors, color_gen))
        lcs = csm.get_cs(lcs_name, reference_system)
        lcs.plot(
            axes=axes,
            color=color,
            label=lcs_name,
            show_origin=show_origins,
            show_trace=show_trace,
            show_vectors=show_vectors,
        )
    # plot data
    for data_name in data_sets:
        color = _color_int_to_rgb_normalized(
            _get_color(data_name, colors, color_gen))
        data = csm.get_data(data_name, reference_system)
        triangles = None
        if isinstance(data, geo.SpatialData):
            triangles = data.triangles
            data = data.coordinates

        data = data.data
        while data.ndim > 2:
            data = data[0]

        axes.plot(data[:, 0],
                  data[:, 1],
                  data[:, 2],
                  "x",
                  color=color,
                  label=data_name)
        if triangles is not None:
            for triangle in triangles:
                triangle_data = data[[*triangle, triangle[0]], :]
                axes.plot(
                    triangle_data[:, 0],
                    triangle_data[:, 1],
                    triangle_data[:, 2],
                    color=color,
                )

    _set_limits_matplotlib(axes, limits)
    axes.legend()

    return axes
Example #17
0
 def __call__(self, ax: pyplot.Axes.axes):
     try:
         ax.set_ylim(0., max_levels)
     except RecursionError as e:
         pass
Example #18
0
def draw_coordinate_system_matplotlib(
    coordinate_system,
    axes: plt.Axes.axes,
    color: Any = None,
    label: str = None,
    time_idx: int = None,
    show_origin: bool = True,
    show_vectors: bool = True,
):
    """Draw a coordinate system in a matplotlib 3d plot.

    Parameters
    ----------
    coordinate_system : weldx.transformations.LocalCoordinateSystem
        Coordinate system
    axes : matplotlib.axes.Axes
        Target matplotlib axes object
    color : Any
        Valid matplotlib color selection. The origin of the coordinate system
        will be marked with this color.
    label : str
        Name that appears in the legend. Only viable if a color
        was specified.
    time_idx : int
        Selects time dependent data by index if the coordinate system has
        a time dependency.
    show_origin : bool
        If `True`, the origin of the coordinate system will be highlighted in the
        color passed as another parameter
    show_vectors : bool
        If `True`, the the coordinate axes of the coordinate system are visualized

    """
    if not (show_vectors or show_origin):
        return
    if "time" in coordinate_system.dataset.coords:
        if time_idx is None:
            time_idx = 0
        if isinstance(time_idx, int):
            dsx = coordinate_system.dataset.isel(time=time_idx)
        else:
            dsx = coordinate_system.dataset.sel(time=time_idx).isel(time=0)
    else:
        dsx = coordinate_system.dataset

    p_0 = dsx.coordinates

    if show_vectors:
        orientation = dsx.orientation
        p_x = p_0 + orientation[:, 0]
        p_y = p_0 + orientation[:, 1]
        p_z = p_0 + orientation[:, 2]

        axes.plot([p_0[0], p_x[0]], [p_0[1], p_x[1]], [p_0[2], p_x[2]], "r")
        axes.plot([p_0[0], p_y[0]], [p_0[1], p_y[1]], [p_0[2], p_y[2]], "g")
        axes.plot([p_0[0], p_z[0]], [p_0[1], p_z[1]], [p_0[2], p_z[2]], "b")
    if color is not None:
        if show_origin:
            axes.plot([p_0[0]], [p_0[1]], [p_0[2]],
                      "o",
                      color=color,
                      label=label)
    elif label is not None:
        raise Exception("Labels can only be assigned if a color was specified")